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.

64249 lines
2.0MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. ==============================================================================
  20. This header contains the entire Juce source tree, and can be #included in
  21. all your source files.
  22. As well as including this in your files, you should also add juce_inline.cpp
  23. to your project (or juce_inline.mm on the Mac).
  24. ==============================================================================
  25. */
  26. #ifndef __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  27. #define __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  28. #define DONT_AUTOLINK_TO_JUCE_LIBRARY 1
  29. /*** Start of inlined file: juce.h ***/
  30. #ifndef __JUCE_JUCEHEADER__
  31. #define __JUCE_JUCEHEADER__
  32. /*
  33. This is the main JUCE header file that applications need to include.
  34. */
  35. /* This line is here just to help catch syntax errors caused by mistakes in other header
  36. files that are included before juce.h. If you hit an error at this line, it must be some
  37. kind of syntax problem in whatever code immediately precedes this header.
  38. This also acts as a sanity-check in case you're trying to build with a C or obj-C compiler
  39. rather than a proper C++ one.
  40. */
  41. namespace JuceDummyNamespace {}
  42. #define JUCE_PUBLIC_INCLUDES 1
  43. // (this includes things that need defining outside of the JUCE namespace)
  44. /*** Start of inlined file: juce_StandardHeader.h ***/
  45. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  46. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  47. /** Current Juce version number.
  48. See also SystemStats::getJUCEVersion() for a string version.
  49. */
  50. #define JUCE_MAJOR_VERSION 1
  51. #define JUCE_MINOR_VERSION 53
  52. #define JUCE_BUILDNUMBER 11
  53. /** Current Juce version number.
  54. Bits 16 to 32 = major version.
  55. Bits 8 to 16 = minor version.
  56. Bits 0 to 8 = point release (not currently used).
  57. See also SystemStats::getJUCEVersion() for a string version.
  58. */
  59. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8) + JUCE_BUILDNUMBER)
  60. /*** Start of inlined file: juce_TargetPlatform.h ***/
  61. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  62. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  63. /* This file figures out which platform is being built, and defines some macros
  64. that the rest of the code can use for OS-specific compilation.
  65. Macros that will be set here are:
  66. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  67. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  68. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  69. - Either JUCE_INTEL or JUCE_PPC
  70. - Either JUCE_GCC or JUCE_MSVC
  71. */
  72. #if (defined (_WIN32) || defined (_WIN64))
  73. #define JUCE_WIN32 1
  74. #define JUCE_WINDOWS 1
  75. #elif defined (LINUX) || defined (__linux__)
  76. #define JUCE_LINUX 1
  77. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  78. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  79. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  80. #define JUCE_IPHONE 1
  81. #define JUCE_IOS 1
  82. #else
  83. #define JUCE_MAC 1
  84. #endif
  85. #else
  86. #error "Unknown platform!"
  87. #endif
  88. #if JUCE_WINDOWS
  89. #ifdef _MSC_VER
  90. #ifdef _WIN64
  91. #define JUCE_64BIT 1
  92. #else
  93. #define JUCE_32BIT 1
  94. #endif
  95. #endif
  96. #ifdef _DEBUG
  97. #define JUCE_DEBUG 1
  98. #endif
  99. #ifdef __MINGW32__
  100. #define JUCE_MINGW 1
  101. #endif
  102. /** If defined, this indicates that the processor is little-endian. */
  103. #define JUCE_LITTLE_ENDIAN 1
  104. #define JUCE_INTEL 1
  105. #endif
  106. #if JUCE_MAC || JUCE_IOS
  107. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  108. #define JUCE_DEBUG 1
  109. #endif
  110. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  111. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  112. #endif
  113. #ifdef __LITTLE_ENDIAN__
  114. #define JUCE_LITTLE_ENDIAN 1
  115. #else
  116. #define JUCE_BIG_ENDIAN 1
  117. #endif
  118. #endif
  119. #if JUCE_MAC
  120. #if defined (__ppc__) || defined (__ppc64__)
  121. #define JUCE_PPC 1
  122. #else
  123. #define JUCE_INTEL 1
  124. #endif
  125. #ifdef __LP64__
  126. #define JUCE_64BIT 1
  127. #else
  128. #define JUCE_32BIT 1
  129. #endif
  130. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  131. #error "Building for OSX 10.3 is no longer supported!"
  132. #endif
  133. #ifndef MAC_OS_X_VERSION_10_5
  134. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  135. #endif
  136. #endif
  137. #if JUCE_LINUX
  138. #ifdef _DEBUG
  139. #define JUCE_DEBUG 1
  140. #endif
  141. // Allow override for big-endian Linux platforms
  142. #ifndef JUCE_BIG_ENDIAN
  143. #define JUCE_LITTLE_ENDIAN 1
  144. #endif
  145. #if defined (__LP64__) || defined (_LP64)
  146. #define JUCE_64BIT 1
  147. #else
  148. #define JUCE_32BIT 1
  149. #endif
  150. #define JUCE_INTEL 1
  151. #endif
  152. // Compiler type macros.
  153. #ifdef __GNUC__
  154. #define JUCE_GCC 1
  155. #elif defined (_MSC_VER)
  156. #define JUCE_MSVC 1
  157. #if _MSC_VER < 1500
  158. #define JUCE_VC8_OR_EARLIER 1
  159. #if _MSC_VER < 1400
  160. #define JUCE_VC7_OR_EARLIER 1
  161. #if _MSC_VER < 1300
  162. #define JUCE_VC6 1
  163. #endif
  164. #endif
  165. #endif
  166. #if ! JUCE_VC7_OR_EARLIER
  167. #define JUCE_USE_INTRINSICS 1
  168. #endif
  169. #else
  170. #error unknown compiler
  171. #endif
  172. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  173. /*** End of inlined file: juce_TargetPlatform.h ***/
  174. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  175. /*** Start of inlined file: juce_Config.h ***/
  176. #ifndef __JUCE_CONFIG_JUCEHEADER__
  177. #define __JUCE_CONFIG_JUCEHEADER__
  178. /*
  179. This file contains macros that enable/disable various JUCE features.
  180. */
  181. /** The name of the namespace that all Juce classes and functions will be
  182. put inside. If this is not defined, no namespace will be used.
  183. */
  184. #ifndef JUCE_NAMESPACE
  185. #define JUCE_NAMESPACE juce
  186. #endif
  187. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  188. project settings, but if you define this value, you can override this to force
  189. it to be true or false.
  190. */
  191. #ifndef JUCE_FORCE_DEBUG
  192. //#define JUCE_FORCE_DEBUG 0
  193. #endif
  194. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  195. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  196. Enabling it will also leave this turned on in release builds. When it's disabled,
  197. however, the jassert and jassertfalse macros will not be compiled in a
  198. release build.
  199. @see jassert, jassertfalse, Logger
  200. */
  201. #ifndef JUCE_LOG_ASSERTIONS
  202. #define JUCE_LOG_ASSERTIONS 0
  203. #endif
  204. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  205. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  206. on your Windows build machine.
  207. See the comments in the ASIOAudioIODevice class's header file for more
  208. info about this.
  209. */
  210. #ifndef JUCE_ASIO
  211. #define JUCE_ASIO 0
  212. #endif
  213. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  214. */
  215. #ifndef JUCE_WASAPI
  216. #define JUCE_WASAPI 0
  217. #endif
  218. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  219. */
  220. #ifndef JUCE_DIRECTSOUND
  221. #define JUCE_DIRECTSOUND 1
  222. #endif
  223. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  224. #ifndef JUCE_ALSA
  225. #define JUCE_ALSA 1
  226. #endif
  227. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  228. #ifndef JUCE_JACK
  229. #define JUCE_JACK 0
  230. #endif
  231. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  232. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  233. installed, and its header files will need to be on your include path.
  234. */
  235. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  236. #define JUCE_QUICKTIME 0
  237. #endif
  238. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  239. #undef JUCE_QUICKTIME
  240. #endif
  241. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  242. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  243. */
  244. #ifndef JUCE_OPENGL
  245. #define JUCE_OPENGL 1
  246. #endif
  247. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  248. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  249. */
  250. #ifndef JUCE_DIRECT2D
  251. #define JUCE_DIRECT2D 0
  252. #endif
  253. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  254. If your app doesn't need to read FLAC files, you might want to disable this to
  255. reduce the size of your codebase and build time.
  256. */
  257. #ifndef JUCE_USE_FLAC
  258. #define JUCE_USE_FLAC 1
  259. #endif
  260. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  261. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  262. reduce the size of your codebase and build time.
  263. */
  264. #ifndef JUCE_USE_OGGVORBIS
  265. #define JUCE_USE_OGGVORBIS 1
  266. #endif
  267. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  268. Unless you're using CD-burning, you should probably turn this flag off to
  269. reduce code size.
  270. */
  271. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  272. #define JUCE_USE_CDBURNER 1
  273. #endif
  274. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  275. Unless you're using CD-reading, you should probably turn this flag off to
  276. reduce code size.
  277. */
  278. #ifndef JUCE_USE_CDREADER
  279. #define JUCE_USE_CDREADER 1
  280. #endif
  281. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  282. */
  283. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  284. #define JUCE_USE_CAMERA 0
  285. #endif
  286. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  287. gets repainted will flash in a random colour, so that you can check exactly how much and how
  288. often your components are being drawn.
  289. */
  290. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  291. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  292. #endif
  293. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  294. Unless you specifically want to disable this, it's best to leave this option turned on.
  295. */
  296. #ifndef JUCE_USE_XINERAMA
  297. #define JUCE_USE_XINERAMA 1
  298. #endif
  299. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  300. turned on unless you have a good reason to disable it.
  301. */
  302. #ifndef JUCE_USE_XSHM
  303. #define JUCE_USE_XSHM 1
  304. #endif
  305. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  306. */
  307. #ifndef JUCE_USE_XRENDER
  308. #define JUCE_USE_XRENDER 0
  309. #endif
  310. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  311. unless you have a good reason to disable it.
  312. */
  313. #ifndef JUCE_USE_XCURSOR
  314. #define JUCE_USE_XCURSOR 1
  315. #endif
  316. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  317. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  318. you're building a plugin hosting app.
  319. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  320. */
  321. #ifndef JUCE_PLUGINHOST_VST
  322. #define JUCE_PLUGINHOST_VST 0
  323. #endif
  324. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  325. of course, and should only be enabled if you're building a plugin hosting app.
  326. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  327. */
  328. #ifndef JUCE_PLUGINHOST_AU
  329. #define JUCE_PLUGINHOST_AU 0
  330. #endif
  331. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  332. This should be enabled if you're writing a console application.
  333. */
  334. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  335. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  336. #endif
  337. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  338. If you're not using any embedded web-pages, turning this off may reduce your code size.
  339. */
  340. #ifndef JUCE_WEB_BROWSER
  341. #define JUCE_WEB_BROWSER 1
  342. #endif
  343. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  344. Carbon isn't required for a normal app, but may be needed by specialised classes like
  345. plugin-hosts, which support older APIs.
  346. */
  347. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  348. #define JUCE_SUPPORT_CARBON 1
  349. #endif
  350. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  351. You might need to tweak this if you're linking to an external zlib library in your app,
  352. but for normal apps, this option should be left alone.
  353. */
  354. #ifndef JUCE_INCLUDE_ZLIB_CODE
  355. #define JUCE_INCLUDE_ZLIB_CODE 1
  356. #endif
  357. #ifndef JUCE_INCLUDE_FLAC_CODE
  358. #define JUCE_INCLUDE_FLAC_CODE 1
  359. #endif
  360. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  361. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  362. #endif
  363. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  364. #define JUCE_INCLUDE_PNGLIB_CODE 1
  365. #endif
  366. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  367. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  368. #endif
  369. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  370. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  371. macro for more details about enabling leak checking for specific classes.
  372. */
  373. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  374. #define JUCE_CHECK_MEMORY_LEAKS 1
  375. #endif
  376. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  377. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  378. are passed to the JUCEApplication::unhandledException() callback for logging.
  379. */
  380. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  381. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  382. #endif
  383. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  384. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  385. #undef JUCE_QUICKTIME
  386. #define JUCE_QUICKTIME 0
  387. #undef JUCE_OPENGL
  388. #define JUCE_OPENGL 0
  389. #undef JUCE_USE_CDBURNER
  390. #define JUCE_USE_CDBURNER 0
  391. #undef JUCE_USE_CDREADER
  392. #define JUCE_USE_CDREADER 0
  393. #undef JUCE_WEB_BROWSER
  394. #define JUCE_WEB_BROWSER 0
  395. #undef JUCE_PLUGINHOST_AU
  396. #define JUCE_PLUGINHOST_AU 0
  397. #undef JUCE_PLUGINHOST_VST
  398. #define JUCE_PLUGINHOST_VST 0
  399. #endif
  400. #endif
  401. /*** End of inlined file: juce_Config.h ***/
  402. #ifdef JUCE_NAMESPACE
  403. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  404. #define END_JUCE_NAMESPACE }
  405. #else
  406. #define BEGIN_JUCE_NAMESPACE
  407. #define END_JUCE_NAMESPACE
  408. #endif
  409. /*** Start of inlined file: juce_PlatformDefs.h ***/
  410. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  411. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  412. /* This file defines miscellaneous macros for debugging, assertions, etc.
  413. */
  414. #ifdef JUCE_FORCE_DEBUG
  415. #undef JUCE_DEBUG
  416. #if JUCE_FORCE_DEBUG
  417. #define JUCE_DEBUG 1
  418. #endif
  419. #endif
  420. /** This macro defines the C calling convention used as the standard for Juce calls. */
  421. #if JUCE_MSVC
  422. #define JUCE_CALLTYPE __stdcall
  423. #define JUCE_CDECL __cdecl
  424. #else
  425. #define JUCE_CALLTYPE
  426. #define JUCE_CDECL
  427. #endif
  428. // Debugging and assertion macros
  429. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  430. #if JUCE_LOG_ASSERTIONS
  431. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  432. #elif JUCE_DEBUG
  433. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  434. #else
  435. #define juce_LogCurrentAssertion
  436. #endif
  437. #if JUCE_DEBUG
  438. // If debugging is enabled..
  439. /** Writes a string to the standard error stream.
  440. This is only compiled in a debug build.
  441. @see Logger::outputDebugString
  442. */
  443. #define DBG(dbgtext) { JUCE_NAMESPACE::String tempDbgBuf; tempDbgBuf << dbgtext; JUCE_NAMESPACE::Logger::outputDebugString (tempDbgBuf); }
  444. // Assertions..
  445. #if JUCE_WINDOWS || DOXYGEN
  446. #if JUCE_USE_INTRINSICS
  447. #pragma intrinsic (__debugbreak)
  448. /** This will try to break the debugger if one is currently hosting this app.
  449. @see jassert()
  450. */
  451. #define juce_breakDebugger __debugbreak();
  452. #elif JUCE_GCC
  453. /** This will try to break the debugger if one is currently hosting this app.
  454. @see jassert()
  455. */
  456. #define juce_breakDebugger asm("int $3");
  457. #else
  458. /** This will try to break the debugger if one is currently hosting this app.
  459. @see jassert()
  460. */
  461. #define juce_breakDebugger { __asm int 3 }
  462. #endif
  463. #elif JUCE_MAC
  464. #define juce_breakDebugger Debugger();
  465. #elif JUCE_IOS
  466. #define juce_breakDebugger kill (0, SIGTRAP);
  467. #elif JUCE_LINUX
  468. #define juce_breakDebugger kill (0, SIGTRAP);
  469. #endif
  470. /** This will always cause an assertion failure.
  471. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  472. in juce_Config.h).
  473. @see jassert()
  474. */
  475. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  476. /** Platform-independent assertion macro.
  477. This gets optimised out when not being built with debugging turned on.
  478. Be careful not to call any functions within its arguments that are vital to
  479. the behaviour of the program, because these won't get called in the release
  480. build.
  481. @see jassertfalse
  482. */
  483. #define jassert(expression) { if (! (expression)) jassertfalse; }
  484. #else
  485. // If debugging is disabled, these dummy debug and assertion macros are used..
  486. #define DBG(dbgtext)
  487. #define jassertfalse { juce_LogCurrentAssertion }
  488. #if JUCE_LOG_ASSERTIONS
  489. #define jassert(expression) { if (! (expression)) jassertfalse; }
  490. #else
  491. #define jassert(a) { }
  492. #endif
  493. #endif
  494. #ifndef DOXYGEN
  495. BEGIN_JUCE_NAMESPACE
  496. template <bool b> struct JuceStaticAssert;
  497. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  498. END_JUCE_NAMESPACE
  499. #endif
  500. /** A compile-time assertion macro.
  501. If the expression parameter is false, the macro will cause a compile error.
  502. */
  503. #define static_jassert(expression) JUCE_NAMESPACE::JuceStaticAssert<expression>::dummy();
  504. /** This is a shorthand macro for declaring stubs for a class's copy constructor and
  505. operator=.
  506. For example, instead of
  507. @code
  508. class MyClass
  509. {
  510. etc..
  511. private:
  512. MyClass (const MyClass&);
  513. MyClass& operator= (const MyClass&);
  514. };@endcode
  515. ..you can just write:
  516. @code
  517. class MyClass
  518. {
  519. etc..
  520. private:
  521. JUCE_DECLARE_NON_COPYABLE (MyClass);
  522. };@endcode
  523. */
  524. #define JUCE_DECLARE_NON_COPYABLE(className) \
  525. className (const className&);\
  526. className& operator= (const className&)
  527. /** This is a shorthand way of writing both a JUCE_DECLARE_NON_COPYABLE and
  528. JUCE_LEAK_DETECTOR macro for a class.
  529. */
  530. #define JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className) \
  531. JUCE_DECLARE_NON_COPYABLE(className);\
  532. JUCE_LEAK_DETECTOR(className)
  533. #if ! DOXYGEN
  534. #define JUCE_JOIN_MACRO_HELPER(a, b) a ## b
  535. #endif
  536. /** Good old C macro concatenation helper.
  537. This combines two items (which may themselves be macros) into a single string,
  538. avoiding the pitfalls of the ## macro operator.
  539. */
  540. #define JUCE_JOIN_MACRO(a, b) JUCE_JOIN_MACRO_HELPER (a, b)
  541. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  542. #define JUCE_TRY try
  543. #define JUCE_CATCH_ALL catch (...) {}
  544. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  545. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  546. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  547. #else
  548. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  549. object so they can be logged by the application if it wants to.
  550. */
  551. #define JUCE_CATCH_EXCEPTION \
  552. catch (const std::exception& e) \
  553. { \
  554. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  555. } \
  556. catch (...) \
  557. { \
  558. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  559. }
  560. #endif
  561. #else
  562. #define JUCE_TRY
  563. #define JUCE_CATCH_EXCEPTION
  564. #define JUCE_CATCH_ALL
  565. #define JUCE_CATCH_ALL_ASSERT
  566. #endif
  567. // Macros for inlining.
  568. #if JUCE_MSVC
  569. /** A platform-independent way of forcing an inline function.
  570. Use the syntax: @code
  571. forcedinline void myfunction (int x)
  572. @endcode
  573. */
  574. #ifndef JUCE_DEBUG
  575. #define forcedinline __forceinline
  576. #else
  577. #define forcedinline inline
  578. #endif
  579. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  580. #else
  581. /** A platform-independent way of forcing an inline function.
  582. Use the syntax: @code
  583. forcedinline void myfunction (int x)
  584. @endcode
  585. */
  586. #ifndef JUCE_DEBUG
  587. #define forcedinline inline __attribute__((always_inline))
  588. #else
  589. #define forcedinline inline
  590. #endif
  591. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  592. #endif
  593. // Cross-compiler deprecation macros..
  594. #if JUCE_MSVC && ! JUCE_NO_DEPRECATION_WARNINGS
  595. #define JUCE_DEPRECATED(functionDef) __declspec(deprecated) functionDef
  596. #elif JUCE_GCC && ! JUCE_NO_DEPRECATION_WARNINGS
  597. #define JUCE_DEPRECATED(functionDef) functionDef __attribute__ ((deprecated))
  598. #else
  599. #define JUCE_DEPRECATED(functionDef) functionDef
  600. #endif
  601. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  602. /*** End of inlined file: juce_PlatformDefs.h ***/
  603. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  604. #if JUCE_MSVC
  605. #if JUCE_VC6
  606. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  607. namespace std // VC6 doesn't have sqrt/sin/cos/tan/abs in std, so declare them here:
  608. {
  609. template <typename Type> Type abs (Type a) { if (a < 0) return -a; return a; }
  610. template <typename Type> Type tan (Type a) { return static_cast<Type> (::tan (static_cast<double> (a))); }
  611. template <typename Type> Type sin (Type a) { return static_cast<Type> (::sin (static_cast<double> (a))); }
  612. template <typename Type> Type cos (Type a) { return static_cast<Type> (::cos (static_cast<double> (a))); }
  613. template <typename Type> Type sqrt (Type a) { return static_cast<Type> (::sqrt (static_cast<double> (a))); }
  614. template <typename Type> Type floor (Type a) { return static_cast<Type> (::floor (static_cast<double> (a))); }
  615. template <typename Type> Type ceil (Type a) { return static_cast<Type> (::ceil (static_cast<double> (a))); }
  616. template <typename Type> Type atan2 (Type a, Type b) { return static_cast<Type> (::atan2 (static_cast<double> (a), static_cast<double> (b))); }
  617. }
  618. #endif
  619. #pragma warning (push)
  620. #pragma warning (disable: 4514 4245 4100)
  621. #endif
  622. #include <cstdlib>
  623. #include <cstdarg>
  624. #include <climits>
  625. #include <limits>
  626. #include <cmath>
  627. #include <cwchar>
  628. #include <stdexcept>
  629. #include <typeinfo>
  630. #include <cstring>
  631. #include <cstdio>
  632. #include <iostream>
  633. #if JUCE_USE_INTRINSICS
  634. #include <intrin.h>
  635. #endif
  636. #if JUCE_MAC || JUCE_IOS
  637. #include <libkern/OSAtomic.h>
  638. #endif
  639. #if JUCE_LINUX
  640. #include <signal.h>
  641. #if __INTEL_COMPILER
  642. #if __ia64__
  643. #include <ia64intrin.h>
  644. #else
  645. #include <ia32intrin.h>
  646. #endif
  647. #endif
  648. #endif
  649. #if JUCE_MSVC && JUCE_DEBUG
  650. #include <crtdbg.h>
  651. #endif
  652. #if JUCE_MSVC
  653. #include <malloc.h>
  654. #pragma warning (pop)
  655. #if ! JUCE_PUBLIC_INCLUDES
  656. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  657. #endif
  658. #endif
  659. // DLL building settings on Win32
  660. #if JUCE_MSVC
  661. #ifdef JUCE_DLL_BUILD
  662. #define JUCE_API __declspec (dllexport)
  663. #pragma warning (disable: 4251)
  664. #elif defined (JUCE_DLL)
  665. #define JUCE_API __declspec (dllimport)
  666. #pragma warning (disable: 4251)
  667. #endif
  668. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  669. #ifdef JUCE_DLL_BUILD
  670. #define JUCE_API __attribute__ ((visibility("default")))
  671. #endif
  672. #endif
  673. #ifndef JUCE_API
  674. /** This macro is added to all juce public class declarations. */
  675. #define JUCE_API
  676. #endif
  677. /** This macro is added to all juce public function declarations. */
  678. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  679. /** This turns on some non-essential bits of code that should prevent old code from compiling
  680. in cases where method signatures have changed, etc.
  681. */
  682. #if (! defined (JUCE_CATCH_DEPRECATED_CODE_MISUSE)) && JUCE_DEBUG && ! DOXYGEN
  683. #define JUCE_CATCH_DEPRECATED_CODE_MISUSE 1
  684. #endif
  685. // Now include some basics that are needed by most of the Juce classes...
  686. BEGIN_JUCE_NAMESPACE
  687. extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
  688. #if JUCE_LOG_ASSERTIONS
  689. extern JUCE_API void juce_LogAssertion (const char* filename, int lineNum) throw();
  690. #endif
  691. /*** Start of inlined file: juce_Memory.h ***/
  692. #ifndef __JUCE_MEMORY_JUCEHEADER__
  693. #define __JUCE_MEMORY_JUCEHEADER__
  694. /*
  695. This file defines the various juce_malloc(), juce_free() macros that can be used in
  696. preference to the standard calls.
  697. None of this stuff is actually used in the library itself, and will probably be
  698. deprecated at some point in the future, to force everyone to use HeapBlock and other
  699. safer allocation methods.
  700. */
  701. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS && ! DOXYGEN
  702. #ifndef JUCE_DLL
  703. // Win32 debug non-DLL versions..
  704. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  705. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  706. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  707. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  708. #else
  709. // Win32 debug DLL versions..
  710. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  711. // way all juce calls in the DLL and in the host API will all use the same allocator.
  712. extern JUCE_API void* juce_DebugMalloc (int size, const char* file, int line);
  713. extern JUCE_API void* juce_DebugCalloc (int size, const char* file, int line);
  714. extern JUCE_API void* juce_DebugRealloc (void* block, int size, const char* file, int line);
  715. extern JUCE_API void juce_DebugFree (void* block);
  716. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  717. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  718. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  719. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  720. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  721. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  722. static void* operator new (size_t, void* p) { return p; } \
  723. static void operator delete (void* p) { juce_free (p); } \
  724. static void operator delete (void*, void*) {}
  725. #endif
  726. #elif defined (JUCE_DLL) && ! DOXYGEN
  727. // Win32 DLL (release) versions..
  728. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  729. // way all juce calls in the DLL and in the host API will all use the same allocator.
  730. extern JUCE_API void* juce_Malloc (int size);
  731. extern JUCE_API void* juce_Calloc (int size);
  732. extern JUCE_API void* juce_Realloc (void* block, int size);
  733. extern JUCE_API void juce_Free (void* block);
  734. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  735. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  736. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  737. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  738. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  739. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  740. static void* operator new (size_t, void* p) { return p; } \
  741. static void operator delete (void* p) { juce_free (p); } \
  742. static void operator delete (void*, void*) {}
  743. #else
  744. // Mac, Linux and Win32 (release) versions..
  745. /** This can be used instead of calling malloc directly.
  746. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  747. */
  748. #define juce_malloc(numBytes) malloc (numBytes)
  749. /** This can be used instead of calling calloc directly.
  750. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  751. */
  752. #define juce_calloc(numBytes) calloc (1, numBytes)
  753. /** This can be used instead of calling realloc directly.
  754. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  755. */
  756. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  757. /** This can be used instead of calling free directly.
  758. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  759. */
  760. #define juce_free(location) free (location)
  761. #endif
  762. /** (Deprecated) This was a win32-specific way of checking for object leaks - now please
  763. use the JUCE_LEAK_DETECTOR instead.
  764. */
  765. #ifndef juce_UseDebuggingNewOperator
  766. #define juce_UseDebuggingNewOperator
  767. #endif
  768. #if JUCE_MSVC || DOXYGEN
  769. /** This is a compiler-independent way of declaring a variable as being thread-local.
  770. E.g.
  771. @code
  772. juce_ThreadLocal int myVariable;
  773. @endcode
  774. */
  775. #define juce_ThreadLocal __declspec(thread)
  776. #else
  777. #define juce_ThreadLocal __thread
  778. #endif
  779. #if JUCE_MINGW
  780. /** This allocator is not defined in mingw gcc. */
  781. #define alloca __builtin_alloca
  782. #endif
  783. /** Fills a block of memory with zeros. */
  784. inline void zeromem (void* memory, size_t numBytes) throw() { memset (memory, 0, numBytes); }
  785. /** Overwrites a structure or object with zeros. */
  786. template <typename Type>
  787. inline void zerostruct (Type& structure) throw() { memset (&structure, 0, sizeof (structure)); }
  788. /** Delete an object pointer, and sets the pointer to null.
  789. Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
  790. or other automatic lieftime-management system rather than resorting to deleting raw pointers!
  791. */
  792. template <typename Type>
  793. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  794. /** A handy function which adds a number of bytes to any type of pointer and returns the result.
  795. This can be useful to avoid casting pointers to a char* and back when you want to move them by
  796. a specific number of bytes,
  797. */
  798. template <typename Type>
  799. inline Type* addBytesToPointer (Type* pointer, int bytes) throw() { return (Type*) (((char*) pointer) + bytes); }
  800. #endif // __JUCE_MEMORY_JUCEHEADER__
  801. /*** End of inlined file: juce_Memory.h ***/
  802. /*** Start of inlined file: juce_MathsFunctions.h ***/
  803. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  804. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  805. /*
  806. This file sets up some handy mathematical typdefs and functions.
  807. */
  808. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  809. /** A platform-independent 8-bit signed integer type. */
  810. typedef signed char int8;
  811. /** A platform-independent 8-bit unsigned integer type. */
  812. typedef unsigned char uint8;
  813. /** A platform-independent 16-bit signed integer type. */
  814. typedef signed short int16;
  815. /** A platform-independent 16-bit unsigned integer type. */
  816. typedef unsigned short uint16;
  817. /** A platform-independent 32-bit signed integer type. */
  818. typedef signed int int32;
  819. /** A platform-independent 32-bit unsigned integer type. */
  820. typedef unsigned int uint32;
  821. #if JUCE_MSVC
  822. /** A platform-independent 64-bit integer type. */
  823. typedef __int64 int64;
  824. /** A platform-independent 64-bit unsigned integer type. */
  825. typedef unsigned __int64 uint64;
  826. /** A platform-independent macro for writing 64-bit literals, needed because
  827. different compilers have different syntaxes for this.
  828. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  829. GCC, or 0x1000000000 for MSVC.
  830. */
  831. #define literal64bit(longLiteral) ((__int64) longLiteral)
  832. #else
  833. /** A platform-independent 64-bit integer type. */
  834. typedef long long int64;
  835. /** A platform-independent 64-bit unsigned integer type. */
  836. typedef unsigned long long uint64;
  837. /** A platform-independent macro for writing 64-bit literals, needed because
  838. different compilers have different syntaxes for this.
  839. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  840. GCC, or 0x1000000000 for MSVC.
  841. */
  842. #define literal64bit(longLiteral) (longLiteral##LL)
  843. #endif
  844. #if JUCE_64BIT
  845. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  846. typedef int64 pointer_sized_int;
  847. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  848. typedef uint64 pointer_sized_uint;
  849. #elif JUCE_MSVC && ! JUCE_VC6
  850. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  851. typedef _W64 int pointer_sized_int;
  852. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  853. typedef _W64 unsigned int pointer_sized_uint;
  854. #else
  855. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  856. typedef int pointer_sized_int;
  857. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  858. typedef unsigned int pointer_sized_uint;
  859. #endif
  860. /** A platform-independent unicode character type. */
  861. typedef wchar_t juce_wchar;
  862. // Some indispensible min/max functions
  863. /** Returns the larger of two values. */
  864. template <typename Type>
  865. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  866. /** Returns the larger of three values. */
  867. template <typename Type>
  868. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  869. /** Returns the larger of four values. */
  870. template <typename Type>
  871. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  872. /** Returns the smaller of two values. */
  873. template <typename Type>
  874. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  875. /** Returns the smaller of three values. */
  876. template <typename Type>
  877. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  878. /** Returns the smaller of four values. */
  879. template <typename Type>
  880. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  881. /** Scans an array of values, returning the minimum value that it contains. */
  882. template <typename Type>
  883. const Type findMinimum (const Type* data, int numValues)
  884. {
  885. if (numValues <= 0)
  886. return Type();
  887. Type result (*data++);
  888. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  889. {
  890. const Type& v = *data++;
  891. if (v < result) result = v;
  892. }
  893. return result;
  894. }
  895. /** Scans an array of values, returning the minimum value that it contains. */
  896. template <typename Type>
  897. const Type findMaximum (const Type* values, int numValues)
  898. {
  899. if (numValues <= 0)
  900. return Type();
  901. Type result (*values++);
  902. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  903. {
  904. const Type& v = *values++;
  905. if (result > v) result = v;
  906. }
  907. return result;
  908. }
  909. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  910. template <typename Type>
  911. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  912. {
  913. if (numValues <= 0)
  914. {
  915. lowest = Type();
  916. highest = Type();
  917. }
  918. else
  919. {
  920. Type mn (*values++);
  921. Type mx (mn);
  922. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  923. {
  924. const Type& v = *values++;
  925. if (mx < v) mx = v;
  926. if (v < mn) mn = v;
  927. }
  928. lowest = mn;
  929. highest = mx;
  930. }
  931. }
  932. /** Constrains a value to keep it within a given range.
  933. This will check that the specified value lies between the lower and upper bounds
  934. specified, and if not, will return the nearest value that would be in-range. Effectively,
  935. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  936. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  937. the results will be unpredictable.
  938. @param lowerLimit the minimum value to return
  939. @param upperLimit the maximum value to return
  940. @param valueToConstrain the value to try to return
  941. @returns the closest value to valueToConstrain which lies between lowerLimit
  942. and upperLimit (inclusive)
  943. @see jlimit0To, jmin, jmax
  944. */
  945. template <typename Type>
  946. inline Type jlimit (const Type lowerLimit,
  947. const Type upperLimit,
  948. const Type valueToConstrain) throw()
  949. {
  950. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  951. return (valueToConstrain < lowerLimit) ? lowerLimit
  952. : ((upperLimit < valueToConstrain) ? upperLimit
  953. : valueToConstrain);
  954. }
  955. /** Returns true if a value is at least zero, and also below a specified upper limit.
  956. This is basically a quicker way to write:
  957. @code valueToTest >= 0 && valueToTest < upperLimit
  958. @endcode
  959. */
  960. template <typename Type>
  961. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) throw()
  962. {
  963. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  964. return Type() <= valueToTest && valueToTest < upperLimit;
  965. }
  966. #if ! JUCE_VC6
  967. template <>
  968. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) throw()
  969. {
  970. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  971. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  972. }
  973. #endif
  974. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  975. This is basically a quicker way to write:
  976. @code valueToTest >= 0 && valueToTest <= upperLimit
  977. @endcode
  978. */
  979. template <typename Type>
  980. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) throw()
  981. {
  982. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  983. return Type() <= valueToTest && valueToTest <= upperLimit;
  984. }
  985. #if ! JUCE_VC6
  986. template <>
  987. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) throw()
  988. {
  989. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  990. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  991. }
  992. #endif
  993. /** Handy function to swap two values over.
  994. */
  995. template <typename Type>
  996. inline void swapVariables (Type& variable1, Type& variable2)
  997. {
  998. const Type tempVal = variable1;
  999. variable1 = variable2;
  1000. variable2 = tempVal;
  1001. }
  1002. #if JUCE_VC6
  1003. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  1004. #else
  1005. /** Handy function for getting the number of elements in a simple const C array.
  1006. E.g.
  1007. @code
  1008. static int myArray[] = { 1, 2, 3 };
  1009. int numElements = numElementsInArray (myArray) // returns 3
  1010. @endcode
  1011. */
  1012. template <typename Type, int N>
  1013. inline int numElementsInArray (Type (&array)[N])
  1014. {
  1015. (void) array; // (required to avoid a spurious warning in MS compilers)
  1016. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  1017. return N;
  1018. }
  1019. #endif
  1020. // Some useful maths functions that aren't always present with all compilers and build settings.
  1021. /** Using juce_hypot is easier than dealing with the different types of hypot function
  1022. that are provided by the various platforms and compilers. */
  1023. template <typename Type>
  1024. inline Type juce_hypot (Type a, Type b) throw()
  1025. {
  1026. #if JUCE_WINDOWS
  1027. return static_cast <Type> (_hypot (a, b));
  1028. #else
  1029. return static_cast <Type> (hypot (a, b));
  1030. #endif
  1031. }
  1032. /** 64-bit abs function. */
  1033. inline int64 abs64 (const int64 n) throw()
  1034. {
  1035. return (n >= 0) ? n : -n;
  1036. }
  1037. /** This templated negate function will negate pointers as well as integers */
  1038. template <typename Type>
  1039. inline Type juce_negate (Type n) throw()
  1040. {
  1041. return sizeof (Type) == 1 ? (Type) -(char) n
  1042. : (sizeof (Type) == 2 ? (Type) -(short) n
  1043. : (sizeof (Type) == 4 ? (Type) -(int) n
  1044. : ((Type) -(int64) n)));
  1045. }
  1046. /** This templated negate function will negate pointers as well as integers */
  1047. template <typename Type>
  1048. inline Type* juce_negate (Type* n) throw()
  1049. {
  1050. return (Type*) -(pointer_sized_int) n;
  1051. }
  1052. /** A predefined value for Pi, at double-precision.
  1053. @see float_Pi
  1054. */
  1055. const double double_Pi = 3.1415926535897932384626433832795;
  1056. /** A predefined value for Pi, at sngle-precision.
  1057. @see double_Pi
  1058. */
  1059. const float float_Pi = 3.14159265358979323846f;
  1060. /** The isfinite() method seems to vary between platforms, so this is a
  1061. platform-independent function for it.
  1062. */
  1063. template <typename FloatingPointType>
  1064. inline bool juce_isfinite (FloatingPointType value)
  1065. {
  1066. #if JUCE_WINDOWS
  1067. return _finite (value);
  1068. #else
  1069. return std::isfinite (value);
  1070. #endif
  1071. }
  1072. /** Fast floating-point-to-integer conversion.
  1073. This is faster than using the normal c++ cast to convert a float to an int, and
  1074. it will round the value to the nearest integer, rather than rounding it down
  1075. like the normal cast does.
  1076. Note that this routine gets its speed at the expense of some accuracy, and when
  1077. rounding values whose floating point component is exactly 0.5, odd numbers and
  1078. even numbers will be rounded up or down differently.
  1079. */
  1080. template <typename FloatType>
  1081. inline int roundToInt (const FloatType value) throw()
  1082. {
  1083. union { int asInt[2]; double asDouble; } n;
  1084. n.asDouble = ((double) value) + 6755399441055744.0;
  1085. #if JUCE_BIG_ENDIAN
  1086. return n.asInt [1];
  1087. #else
  1088. return n.asInt [0];
  1089. #endif
  1090. }
  1091. /** Fast floating-point-to-integer conversion.
  1092. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1093. fine for values above zero, but negative numbers are rounded the wrong way.
  1094. */
  1095. inline int roundToIntAccurate (const double value) throw()
  1096. {
  1097. return roundToInt (value + 1.5e-8);
  1098. }
  1099. /** Fast floating-point-to-integer conversion.
  1100. This is faster than using the normal c++ cast to convert a double to an int, and
  1101. it will round the value to the nearest integer, rather than rounding it down
  1102. like the normal cast does.
  1103. Note that this routine gets its speed at the expense of some accuracy, and when
  1104. rounding values whose floating point component is exactly 0.5, odd numbers and
  1105. even numbers will be rounded up or down differently. For a more accurate conversion,
  1106. see roundDoubleToIntAccurate().
  1107. */
  1108. inline int roundDoubleToInt (const double value) throw()
  1109. {
  1110. return roundToInt (value);
  1111. }
  1112. /** Fast floating-point-to-integer conversion.
  1113. This is faster than using the normal c++ cast to convert a float to an int, and
  1114. it will round the value to the nearest integer, rather than rounding it down
  1115. like the normal cast does.
  1116. Note that this routine gets its speed at the expense of some accuracy, and when
  1117. rounding values whose floating point component is exactly 0.5, odd numbers and
  1118. even numbers will be rounded up or down differently.
  1119. */
  1120. inline int roundFloatToInt (const float value) throw()
  1121. {
  1122. return roundToInt (value);
  1123. }
  1124. /** This namespace contains a few template classes for helping work out class type variations.
  1125. */
  1126. namespace TypeHelpers
  1127. {
  1128. #if JUCE_VC8_OR_EARLIER
  1129. #define PARAMETER_TYPE(a) a
  1130. #else
  1131. /** The ParameterType struct is used to find the best type to use when passing some kind
  1132. of object as a parameter.
  1133. Of course, this is only likely to be useful in certain esoteric template situations.
  1134. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1135. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1136. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1137. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1138. pass-by-value, but passing objects as a const reference, to avoid copying.
  1139. */
  1140. template <typename Type> struct ParameterType { typedef const Type& type; };
  1141. #if ! DOXYGEN
  1142. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1143. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1144. template <> struct ParameterType <char> { typedef char type; };
  1145. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1146. template <> struct ParameterType <short> { typedef short type; };
  1147. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1148. template <> struct ParameterType <int> { typedef int type; };
  1149. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1150. template <> struct ParameterType <long> { typedef long type; };
  1151. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1152. template <> struct ParameterType <int64> { typedef int64 type; };
  1153. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1154. template <> struct ParameterType <bool> { typedef bool type; };
  1155. template <> struct ParameterType <float> { typedef float type; };
  1156. template <> struct ParameterType <double> { typedef double type; };
  1157. #endif
  1158. /** A helpful macro to simplify the use of the ParameterType template.
  1159. @see ParameterType
  1160. */
  1161. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1162. #endif
  1163. }
  1164. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1165. /*** End of inlined file: juce_MathsFunctions.h ***/
  1166. /*** Start of inlined file: juce_ByteOrder.h ***/
  1167. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1168. #define __JUCE_BYTEORDER_JUCEHEADER__
  1169. /** Contains static methods for converting the byte order between different
  1170. endiannesses.
  1171. */
  1172. class JUCE_API ByteOrder
  1173. {
  1174. public:
  1175. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1176. static uint16 swap (uint16 value);
  1177. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1178. static uint32 swap (uint32 value);
  1179. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1180. static uint64 swap (uint64 value);
  1181. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1182. static uint16 swapIfBigEndian (uint16 value);
  1183. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1184. static uint32 swapIfBigEndian (uint32 value);
  1185. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1186. static uint64 swapIfBigEndian (uint64 value);
  1187. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1188. static uint16 swapIfLittleEndian (uint16 value);
  1189. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1190. static uint32 swapIfLittleEndian (uint32 value);
  1191. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1192. static uint64 swapIfLittleEndian (uint64 value);
  1193. /** Turns 4 bytes into a little-endian integer. */
  1194. static uint32 littleEndianInt (const void* bytes);
  1195. /** Turns 2 bytes into a little-endian integer. */
  1196. static uint16 littleEndianShort (const void* bytes);
  1197. /** Turns 4 bytes into a big-endian integer. */
  1198. static uint32 bigEndianInt (const void* bytes);
  1199. /** Turns 2 bytes into a big-endian integer. */
  1200. static uint16 bigEndianShort (const void* bytes);
  1201. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1202. static int littleEndian24Bit (const char* bytes);
  1203. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1204. static int bigEndian24Bit (const char* bytes);
  1205. /** Copies a 24-bit number to 3 little-endian bytes. */
  1206. static void littleEndian24BitToChars (int value, char* destBytes);
  1207. /** Copies a 24-bit number to 3 big-endian bytes. */
  1208. static void bigEndian24BitToChars (int value, char* destBytes);
  1209. /** Returns true if the current CPU is big-endian. */
  1210. static bool isBigEndian();
  1211. private:
  1212. ByteOrder();
  1213. JUCE_DECLARE_NON_COPYABLE (ByteOrder);
  1214. };
  1215. #if JUCE_USE_INTRINSICS
  1216. #pragma intrinsic (_byteswap_ulong)
  1217. #endif
  1218. inline uint16 ByteOrder::swap (uint16 n)
  1219. {
  1220. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1221. return static_cast <uint16> (_byteswap_ushort (n));
  1222. #else
  1223. return static_cast <uint16> ((n << 8) | (n >> 8));
  1224. #endif
  1225. }
  1226. inline uint32 ByteOrder::swap (uint32 n)
  1227. {
  1228. #if JUCE_MAC || JUCE_IOS
  1229. return OSSwapInt32 (n);
  1230. #elif JUCE_GCC
  1231. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1232. return n;
  1233. #elif JUCE_USE_INTRINSICS
  1234. return _byteswap_ulong (n);
  1235. #else
  1236. __asm {
  1237. mov eax, n
  1238. bswap eax
  1239. mov n, eax
  1240. }
  1241. return n;
  1242. #endif
  1243. }
  1244. inline uint64 ByteOrder::swap (uint64 value)
  1245. {
  1246. #if JUCE_MAC || JUCE_IOS
  1247. return OSSwapInt64 (value);
  1248. #elif JUCE_USE_INTRINSICS
  1249. return _byteswap_uint64 (value);
  1250. #else
  1251. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1252. #endif
  1253. }
  1254. #if JUCE_LITTLE_ENDIAN
  1255. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1256. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1257. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1258. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1259. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1260. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1261. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1262. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1263. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1264. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1265. inline bool ByteOrder::isBigEndian() { return false; }
  1266. #else
  1267. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1268. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1269. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1270. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1271. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1272. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1273. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1274. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1275. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1276. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1277. inline bool ByteOrder::isBigEndian() { return true; }
  1278. #endif
  1279. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1280. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1281. inline void ByteOrder::littleEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); }
  1282. inline void ByteOrder::bigEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); }
  1283. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1284. /*** End of inlined file: juce_ByteOrder.h ***/
  1285. /*** Start of inlined file: juce_Logger.h ***/
  1286. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1287. #define __JUCE_LOGGER_JUCEHEADER__
  1288. /*** Start of inlined file: juce_String.h ***/
  1289. #ifndef __JUCE_STRING_JUCEHEADER__
  1290. #define __JUCE_STRING_JUCEHEADER__
  1291. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1292. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1293. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1294. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1295. typedef juce_wchar tchar;
  1296. #if ! JUCE_DONT_DEFINE_MACROS
  1297. /** The 'T' macro allows a literal string to be compiled as unicode.
  1298. If you write your string literals in the form T("xyz"), it will be compiled as L"xyz"
  1299. or "xyz", depending on which representation is best for the String class to work with.
  1300. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1301. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1302. the juce/src directory) to avoid defining this macro. See the comments in
  1303. juce_withoutMacros.h for more info.
  1304. */
  1305. #define T(stringLiteral) JUCE_T(stringLiteral)
  1306. #endif
  1307. /**
  1308. A set of methods for manipulating characters and character strings, with
  1309. duplicate methods to handle 8-bit and unicode characters.
  1310. These are defined as wrappers around the basic C string handlers, to provide
  1311. a clean, cross-platform layer, (because various platforms differ in the
  1312. range of C library calls that they provide).
  1313. @see String
  1314. */
  1315. class JUCE_API CharacterFunctions
  1316. {
  1317. public:
  1318. static int length (const char* s) throw();
  1319. static int length (const juce_wchar* s) throw();
  1320. static void copy (char* dest, const char* src, int maxBytes) throw();
  1321. static void copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw();
  1322. static void copy (juce_wchar* dest, const char* src, int maxChars) throw();
  1323. static void copy (char* dest, const juce_wchar* src, int maxBytes) throw();
  1324. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1325. static void append (char* dest, const char* src) throw();
  1326. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1327. static int compare (const char* s1, const char* s2) throw();
  1328. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1329. static int compare (const juce_wchar* s1, const char* s2) throw();
  1330. static int compare (const char* s1, const juce_wchar* s2) throw();
  1331. static int compare (const char* s1, const char* s2, int maxChars) throw();
  1332. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1333. static int compareIgnoreCase (const char* s1, const char* s2) throw();
  1334. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1335. static int compareIgnoreCase (const juce_wchar* s1, const char* s2) throw();
  1336. static int compareIgnoreCase (const char* s1, const char* s2, int maxChars) throw();
  1337. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1338. static const char* find (const char* haystack, const char* needle) throw();
  1339. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* needle) throw();
  1340. static int indexOfChar (const char* haystack, char needle, bool ignoreCase) throw();
  1341. static int indexOfChar (const juce_wchar* haystack, juce_wchar needle, bool ignoreCase) throw();
  1342. static int indexOfCharFast (const char* haystack, char needle) throw();
  1343. static int indexOfCharFast (const juce_wchar* haystack, juce_wchar needle) throw();
  1344. static int getIntialSectionContainingOnly (const char* text, const char* allowedChars) throw();
  1345. static int getIntialSectionContainingOnly (const juce_wchar* text, const juce_wchar* allowedChars) throw();
  1346. static int ftime (char* dest, int maxChars, const char* format, const struct tm* tm) throw();
  1347. static int ftime (juce_wchar* dest, int maxChars, const juce_wchar* format, const struct tm* tm) throw();
  1348. static int getIntValue (const char* s) throw();
  1349. static int getIntValue (const juce_wchar* s) throw();
  1350. static int64 getInt64Value (const char* s) throw();
  1351. static int64 getInt64Value (const juce_wchar* s) throw();
  1352. static double getDoubleValue (const char* s) throw();
  1353. static double getDoubleValue (const juce_wchar* s) throw();
  1354. static char toUpperCase (char character) throw();
  1355. static juce_wchar toUpperCase (juce_wchar character) throw();
  1356. static void toUpperCase (char* s) throw();
  1357. static void toUpperCase (juce_wchar* s) throw();
  1358. static bool isUpperCase (char character) throw();
  1359. static bool isUpperCase (juce_wchar character) throw();
  1360. static char toLowerCase (char character) throw();
  1361. static juce_wchar toLowerCase (juce_wchar character) throw();
  1362. static void toLowerCase (char* s) throw();
  1363. static void toLowerCase (juce_wchar* s) throw();
  1364. static bool isLowerCase (char character) throw();
  1365. static bool isLowerCase (juce_wchar character) throw();
  1366. static bool isWhitespace (char character) throw();
  1367. static bool isWhitespace (juce_wchar character) throw();
  1368. static bool isDigit (char character) throw();
  1369. static bool isDigit (juce_wchar character) throw();
  1370. static bool isLetter (char character) throw();
  1371. static bool isLetter (juce_wchar character) throw();
  1372. static bool isLetterOrDigit (char character) throw();
  1373. static bool isLetterOrDigit (juce_wchar character) throw();
  1374. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1375. hex digit.
  1376. */
  1377. static int getHexDigitValue (juce_wchar digit) throw();
  1378. };
  1379. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1380. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1381. class OutputStream;
  1382. /**
  1383. The JUCE String class!
  1384. Using a reference-counted internal representation, these strings are fast
  1385. and efficient, and there are methods to do just about any operation you'll ever
  1386. dream of.
  1387. @see StringArray, StringPairArray
  1388. */
  1389. class JUCE_API String
  1390. {
  1391. public:
  1392. /** Creates an empty string.
  1393. @see empty
  1394. */
  1395. String() throw();
  1396. /** Creates a copy of another string. */
  1397. String (const String& other) throw();
  1398. /** Creates a string from a zero-terminated text string.
  1399. The string is assumed to be stored in the default system encoding.
  1400. */
  1401. String (const char* text);
  1402. /** Creates a string from an string of characters.
  1403. This will use up the the first maxChars characters of the string (or
  1404. less if the string is actually shorter)
  1405. */
  1406. String (const char* text, size_t maxChars);
  1407. /** Creates a string from a zero-terminated unicode text string. */
  1408. String (const juce_wchar* unicodeText);
  1409. /** Creates a string from a unicode text string.
  1410. This will use up the the first maxChars characters of the string (or
  1411. less if the string is actually shorter)
  1412. */
  1413. String (const juce_wchar* unicodeText, size_t maxChars);
  1414. /** Creates a string from a single character. */
  1415. static const String charToString (juce_wchar character);
  1416. /** Destructor. */
  1417. ~String() throw();
  1418. /** This is an empty string that can be used whenever one is needed.
  1419. It's better to use this than String() because it explains what's going on
  1420. and is more efficient.
  1421. */
  1422. static const String empty;
  1423. /** Generates a probably-unique 32-bit hashcode from this string. */
  1424. int hashCode() const throw();
  1425. /** Generates a probably-unique 64-bit hashcode from this string. */
  1426. int64 hashCode64() const throw();
  1427. /** Returns the number of characters in the string. */
  1428. int length() const throw();
  1429. // Assignment and concatenation operators..
  1430. /** Replaces this string's contents with another string. */
  1431. String& operator= (const String& other) throw();
  1432. /** Appends another string at the end of this one. */
  1433. String& operator+= (const juce_wchar* textToAppend);
  1434. /** Appends another string at the end of this one. */
  1435. String& operator+= (const String& stringToAppend);
  1436. /** Appends a character at the end of this string. */
  1437. String& operator+= (char characterToAppend);
  1438. /** Appends a character at the end of this string. */
  1439. String& operator+= (juce_wchar characterToAppend);
  1440. /** Appends a decimal number at the end of this string. */
  1441. String& operator+= (int numberToAppend);
  1442. /** Appends a decimal number at the end of this string. */
  1443. String& operator+= (unsigned int numberToAppend);
  1444. /** Appends a string at the end of this one.
  1445. @param textToAppend the string to add
  1446. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1447. */
  1448. void append (const juce_wchar* textToAppend, int maxCharsToTake);
  1449. // Comparison methods..
  1450. /** Returns true if the string contains no characters.
  1451. Note that there's also an isNotEmpty() method to help write readable code.
  1452. @see containsNonWhitespaceChars()
  1453. */
  1454. inline bool isEmpty() const throw() { return text[0] == 0; }
  1455. /** Returns true if the string contains at least one character.
  1456. Note that there's also an isEmpty() method to help write readable code.
  1457. @see containsNonWhitespaceChars()
  1458. */
  1459. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  1460. /** Case-insensitive comparison with another string. */
  1461. bool equalsIgnoreCase (const String& other) const throw();
  1462. /** Case-insensitive comparison with another string. */
  1463. bool equalsIgnoreCase (const juce_wchar* other) const throw();
  1464. /** Case-insensitive comparison with another string. */
  1465. bool equalsIgnoreCase (const char* other) const throw();
  1466. /** Case-sensitive comparison with another string.
  1467. @returns 0 if the two strings are identical; negative if this string
  1468. comes before the other one alphabetically, or positive if it
  1469. comes after it.
  1470. */
  1471. int compare (const String& other) const throw();
  1472. /** Case-sensitive comparison with another string.
  1473. @returns 0 if the two strings are identical; negative if this string
  1474. comes before the other one alphabetically, or positive if it
  1475. comes after it.
  1476. */
  1477. int compare (const char* other) const throw();
  1478. /** Case-sensitive comparison with another string.
  1479. @returns 0 if the two strings are identical; negative if this string
  1480. comes before the other one alphabetically, or positive if it
  1481. comes after it.
  1482. */
  1483. int compare (const juce_wchar* other) const throw();
  1484. /** Case-insensitive comparison with another string.
  1485. @returns 0 if the two strings are identical; negative if this string
  1486. comes before the other one alphabetically, or positive if it
  1487. comes after it.
  1488. */
  1489. int compareIgnoreCase (const String& other) const throw();
  1490. /** Lexicographic comparison with another string.
  1491. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1492. characters, making it good for sorting human-readable strings.
  1493. @returns 0 if the two strings are identical; negative if this string
  1494. comes before the other one alphabetically, or positive if it
  1495. comes after it.
  1496. */
  1497. int compareLexicographically (const String& other) const throw();
  1498. /** Tests whether the string begins with another string.
  1499. If the parameter is an empty string, this will always return true.
  1500. Uses a case-sensitive comparison.
  1501. */
  1502. bool startsWith (const String& text) const throw();
  1503. /** Tests whether the string begins with a particular character.
  1504. If the character is 0, this will always return false.
  1505. Uses a case-sensitive comparison.
  1506. */
  1507. bool startsWithChar (juce_wchar character) const throw();
  1508. /** Tests whether the string begins with another string.
  1509. If the parameter is an empty string, this will always return true.
  1510. Uses a case-insensitive comparison.
  1511. */
  1512. bool startsWithIgnoreCase (const String& text) const throw();
  1513. /** Tests whether the string ends with another string.
  1514. If the parameter is an empty string, this will always return true.
  1515. Uses a case-sensitive comparison.
  1516. */
  1517. bool endsWith (const String& text) const throw();
  1518. /** Tests whether the string ends with a particular character.
  1519. If the character is 0, this will always return false.
  1520. Uses a case-sensitive comparison.
  1521. */
  1522. bool endsWithChar (juce_wchar character) const throw();
  1523. /** Tests whether the string ends with another string.
  1524. If the parameter is an empty string, this will always return true.
  1525. Uses a case-insensitive comparison.
  1526. */
  1527. bool endsWithIgnoreCase (const String& text) const throw();
  1528. /** Tests whether the string contains another substring.
  1529. If the parameter is an empty string, this will always return true.
  1530. Uses a case-sensitive comparison.
  1531. */
  1532. bool contains (const String& text) const throw();
  1533. /** Tests whether the string contains a particular character.
  1534. Uses a case-sensitive comparison.
  1535. */
  1536. bool containsChar (juce_wchar character) const throw();
  1537. /** Tests whether the string contains another substring.
  1538. Uses a case-insensitive comparison.
  1539. */
  1540. bool containsIgnoreCase (const String& text) const throw();
  1541. /** Tests whether the string contains another substring as a distict word.
  1542. @returns true if the string contains this word, surrounded by
  1543. non-alphanumeric characters
  1544. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1545. */
  1546. bool containsWholeWord (const String& wordToLookFor) const throw();
  1547. /** Tests whether the string contains another substring as a distict word.
  1548. @returns true if the string contains this word, surrounded by
  1549. non-alphanumeric characters
  1550. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1551. */
  1552. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1553. /** Finds an instance of another substring if it exists as a distict word.
  1554. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1555. then this will return the index of the start of the substring. If it isn't
  1556. found, then it will return -1
  1557. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1558. */
  1559. int indexOfWholeWord (const String& wordToLookFor) const throw();
  1560. /** Finds an instance of another substring if it exists as a distict word.
  1561. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1562. then this will return the index of the start of the substring. If it isn't
  1563. found, then it will return -1
  1564. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1565. */
  1566. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1567. /** Looks for any of a set of characters in the string.
  1568. Uses a case-sensitive comparison.
  1569. @returns true if the string contains any of the characters from
  1570. the string that is passed in.
  1571. */
  1572. bool containsAnyOf (const String& charactersItMightContain) const throw();
  1573. /** Looks for a set of characters in the string.
  1574. Uses a case-sensitive comparison.
  1575. @returns Returns false if any of the characters in this string do not occur in
  1576. the parameter string. If this string is empty, the return value will
  1577. always be true.
  1578. */
  1579. bool containsOnly (const String& charactersItMightContain) const throw();
  1580. /** Returns true if this string contains any non-whitespace characters.
  1581. This will return false if the string contains only whitespace characters, or
  1582. if it's empty.
  1583. It is equivalent to calling "myString.trim().isNotEmpty()".
  1584. */
  1585. bool containsNonWhitespaceChars() const throw();
  1586. /** Returns true if the string matches this simple wildcard expression.
  1587. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1588. This isn't a full-blown regex though! The only wildcard characters supported
  1589. are "*" and "?". It's mainly intended for filename pattern matching.
  1590. */
  1591. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  1592. // Substring location methods..
  1593. /** Searches for a character inside this string.
  1594. Uses a case-sensitive comparison.
  1595. @returns the index of the first occurrence of the character in this
  1596. string, or -1 if it's not found.
  1597. */
  1598. int indexOfChar (juce_wchar characterToLookFor) const throw();
  1599. /** Searches for a character inside this string.
  1600. Uses a case-sensitive comparison.
  1601. @param startIndex the index from which the search should proceed
  1602. @param characterToLookFor the character to look for
  1603. @returns the index of the first occurrence of the character in this
  1604. string, or -1 if it's not found.
  1605. */
  1606. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  1607. /** Returns the index of the first character that matches one of the characters
  1608. passed-in to this method.
  1609. This scans the string, beginning from the startIndex supplied, and if it finds
  1610. a character that appears in the string charactersToLookFor, it returns its index.
  1611. If none of these characters are found, it returns -1.
  1612. If ignoreCase is true, the comparison will be case-insensitive.
  1613. @see indexOfChar, lastIndexOfAnyOf
  1614. */
  1615. int indexOfAnyOf (const String& charactersToLookFor,
  1616. int startIndex = 0,
  1617. bool ignoreCase = false) const throw();
  1618. /** Searches for a substring within this string.
  1619. Uses a case-sensitive comparison.
  1620. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1621. */
  1622. int indexOf (const String& text) const throw();
  1623. /** Searches for a substring within this string.
  1624. Uses a case-sensitive comparison.
  1625. @param startIndex the index from which the search should proceed
  1626. @param textToLookFor the string to search for
  1627. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1628. */
  1629. int indexOf (int startIndex,
  1630. const String& textToLookFor) const throw();
  1631. /** Searches for a substring within this string.
  1632. Uses a case-insensitive comparison.
  1633. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1634. */
  1635. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  1636. /** Searches for a substring within this string.
  1637. Uses a case-insensitive comparison.
  1638. @param startIndex the index from which the search should proceed
  1639. @param textToLookFor the string to search for
  1640. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1641. */
  1642. int indexOfIgnoreCase (int startIndex,
  1643. const String& textToLookFor) const throw();
  1644. /** Searches for a character inside this string (working backwards from the end of the string).
  1645. Uses a case-sensitive comparison.
  1646. @returns the index of the last occurrence of the character in this
  1647. string, or -1 if it's not found.
  1648. */
  1649. int lastIndexOfChar (juce_wchar character) const throw();
  1650. /** Searches for a substring inside this string (working backwards from the end of the string).
  1651. Uses a case-sensitive comparison.
  1652. @returns the index of the start of the last occurrence of the
  1653. substring within this string, or -1 if it's not found.
  1654. */
  1655. int lastIndexOf (const String& textToLookFor) const throw();
  1656. /** Searches for a substring inside this string (working backwards from the end of the string).
  1657. Uses a case-insensitive comparison.
  1658. @returns the index of the start of the last occurrence of the
  1659. substring within this string, or -1 if it's not found.
  1660. */
  1661. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  1662. /** Returns the index of the last character in this string that matches one of the
  1663. characters passed-in to this method.
  1664. This scans the string backwards, starting from its end, and if it finds
  1665. a character that appears in the string charactersToLookFor, it returns its index.
  1666. If none of these characters are found, it returns -1.
  1667. If ignoreCase is true, the comparison will be case-insensitive.
  1668. @see lastIndexOf, indexOfAnyOf
  1669. */
  1670. int lastIndexOfAnyOf (const String& charactersToLookFor,
  1671. bool ignoreCase = false) const throw();
  1672. // Substring extraction and manipulation methods..
  1673. /** Returns the character at this index in the string.
  1674. No checks are made to see if the index is within a valid range, so be careful!
  1675. */
  1676. inline const juce_wchar& operator[] (int index) const throw() { jassert (isPositiveAndNotGreaterThan (index, length())); return text [index]; }
  1677. /** Returns a character from the string such that it can also be altered.
  1678. This can be used as a way of easily changing characters in the string.
  1679. Note that the index passed-in is not checked to see whether it's in-range, so
  1680. be careful when using this.
  1681. */
  1682. juce_wchar& operator[] (int index);
  1683. /** Returns the final character of the string.
  1684. If the string is empty this will return 0.
  1685. */
  1686. juce_wchar getLastCharacter() const throw();
  1687. /** Returns a subsection of the string.
  1688. If the range specified is beyond the limits of the string, as much as
  1689. possible is returned.
  1690. @param startIndex the index of the start of the substring needed
  1691. @param endIndex all characters from startIndex up to (but not including)
  1692. this index are returned
  1693. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1694. */
  1695. const String substring (int startIndex, int endIndex) const;
  1696. /** Returns a section of the string, starting from a given position.
  1697. @param startIndex the first character to include. If this is beyond the end
  1698. of the string, an empty string is returned. If it is zero or
  1699. less, the whole string is returned.
  1700. @returns the substring from startIndex up to the end of the string
  1701. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1702. */
  1703. const String substring (int startIndex) const;
  1704. /** Returns a version of this string with a number of characters removed
  1705. from the end.
  1706. @param numberToDrop the number of characters to drop from the end of the
  1707. string. If this is greater than the length of the string,
  1708. an empty string will be returned. If zero or less, the
  1709. original string will be returned.
  1710. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1711. */
  1712. const String dropLastCharacters (int numberToDrop) const;
  1713. /** Returns a number of characters from the end of the string.
  1714. This returns the last numCharacters characters from the end of the string. If the
  1715. string is shorter than numCharacters, the whole string is returned.
  1716. @see substring, dropLastCharacters, getLastCharacter
  1717. */
  1718. const String getLastCharacters (int numCharacters) const;
  1719. /** Returns a section of the string starting from a given substring.
  1720. This will search for the first occurrence of the given substring, and
  1721. return the section of the string starting from the point where this is
  1722. found (optionally not including the substring itself).
  1723. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1724. fromFirstOccurrenceOf ("34", false) would return "56".
  1725. If the substring isn't found, the method will return an empty string.
  1726. If ignoreCase is true, the comparison will be case-insensitive.
  1727. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1728. */
  1729. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  1730. bool includeSubStringInResult,
  1731. bool ignoreCase) const;
  1732. /** Returns a section of the string starting from the last occurrence of a given substring.
  1733. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1734. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1735. return the whole of the original string.
  1736. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1737. */
  1738. const String fromLastOccurrenceOf (const String& substringToFind,
  1739. bool includeSubStringInResult,
  1740. bool ignoreCase) const;
  1741. /** Returns the start of this string, up to the first occurrence of a substring.
  1742. This will search for the first occurrence of a given substring, and then
  1743. return a copy of the string, up to the position of this substring,
  1744. optionally including or excluding the substring itself in the result.
  1745. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1746. upTo ("34", true) would return "1234".
  1747. If the substring isn't found, this will return the whole of the original string.
  1748. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1749. */
  1750. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  1751. bool includeSubStringInResult,
  1752. bool ignoreCase) const;
  1753. /** Returns the start of this string, up to the last occurrence of a substring.
  1754. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1755. If the substring isn't found, this will return the whole of the original string.
  1756. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1757. */
  1758. const String upToLastOccurrenceOf (const String& substringToFind,
  1759. bool includeSubStringInResult,
  1760. bool ignoreCase) const;
  1761. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1762. const String trim() const;
  1763. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1764. const String trimStart() const;
  1765. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1766. const String trimEnd() const;
  1767. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1768. Characters are removed from the start of the string until it finds one that is not in the
  1769. specified set, and then it stops.
  1770. @param charactersToTrim the set of characters to remove.
  1771. @see trim, trimStart, trimCharactersAtEnd
  1772. */
  1773. const String trimCharactersAtStart (const String& charactersToTrim) const;
  1774. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1775. Characters are removed from the end of the string until it finds one that is not in the
  1776. specified set, and then it stops.
  1777. @param charactersToTrim the set of characters to remove.
  1778. @see trim, trimEnd, trimCharactersAtStart
  1779. */
  1780. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  1781. /** Returns an upper-case version of this string. */
  1782. const String toUpperCase() const;
  1783. /** Returns an lower-case version of this string. */
  1784. const String toLowerCase() const;
  1785. /** Replaces a sub-section of the string with another string.
  1786. This will return a copy of this string, with a set of characters
  1787. from startIndex to startIndex + numCharsToReplace removed, and with
  1788. a new string inserted in their place.
  1789. Note that this is a const method, and won't alter the string itself.
  1790. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1791. it will be constrained to a valid range.
  1792. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1793. characters will be taken out.
  1794. @param stringToInsert the new string to insert at startIndex after the characters have been
  1795. removed.
  1796. */
  1797. const String replaceSection (int startIndex,
  1798. int numCharactersToReplace,
  1799. const String& stringToInsert) const;
  1800. /** Replaces all occurrences of a substring with another string.
  1801. Returns a copy of this string, with any occurrences of stringToReplace
  1802. swapped for stringToInsertInstead.
  1803. Note that this is a const method, and won't alter the string itself.
  1804. */
  1805. const String replace (const String& stringToReplace,
  1806. const String& stringToInsertInstead,
  1807. bool ignoreCase = false) const;
  1808. /** Returns a string with all occurrences of a character replaced with a different one. */
  1809. const String replaceCharacter (juce_wchar characterToReplace,
  1810. juce_wchar characterToInsertInstead) const;
  1811. /** Replaces a set of characters with another set.
  1812. Returns a string in which each character from charactersToReplace has been replaced
  1813. by the character at the equivalent position in newCharacters (so the two strings
  1814. passed in must be the same length).
  1815. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1816. Note that this is a const method, and won't affect the string itself.
  1817. */
  1818. const String replaceCharacters (const String& charactersToReplace,
  1819. const String& charactersToInsertInstead) const;
  1820. /** Returns a version of this string that only retains a fixed set of characters.
  1821. This will return a copy of this string, omitting any characters which are not
  1822. found in the string passed-in.
  1823. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1824. Note that this is a const method, and won't alter the string itself.
  1825. */
  1826. const String retainCharacters (const String& charactersToRetain) const;
  1827. /** Returns a version of this string with a set of characters removed.
  1828. This will return a copy of this string, omitting any characters which are
  1829. found in the string passed-in.
  1830. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1831. Note that this is a const method, and won't alter the string itself.
  1832. */
  1833. const String removeCharacters (const String& charactersToRemove) const;
  1834. /** Returns a section from the start of the string that only contains a certain set of characters.
  1835. This returns the leftmost section of the string, up to (and not including) the
  1836. first character that doesn't appear in the string passed in.
  1837. */
  1838. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  1839. /** Returns a section from the start of the string that only contains a certain set of characters.
  1840. This returns the leftmost section of the string, up to (and not including) the
  1841. first character that occurs in the string passed in.
  1842. */
  1843. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  1844. /** Checks whether the string might be in quotation marks.
  1845. @returns true if the string begins with a quote character (either a double or single quote).
  1846. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1847. @see unquoted, quoted
  1848. */
  1849. bool isQuotedString() const;
  1850. /** Removes quotation marks from around the string, (if there are any).
  1851. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1852. at the ends of the string are not affected. If there aren't any quotes, the original string
  1853. is returned.
  1854. Note that this is a const method, and won't alter the string itself.
  1855. @see isQuotedString, quoted
  1856. */
  1857. const String unquoted() const;
  1858. /** Adds quotation marks around a string.
  1859. This will return a copy of the string with a quote at the start and end, (but won't
  1860. add the quote if there's already one there, so it's safe to call this on strings that
  1861. may already have quotes around them).
  1862. Note that this is a const method, and won't alter the string itself.
  1863. @param quoteCharacter the character to add at the start and end
  1864. @see isQuotedString, unquoted
  1865. */
  1866. const String quoted (juce_wchar quoteCharacter = '"') const;
  1867. /** Creates a string which is a version of a string repeated and joined together.
  1868. @param stringToRepeat the string to repeat
  1869. @param numberOfTimesToRepeat how many times to repeat it
  1870. */
  1871. static const String repeatedString (const String& stringToRepeat,
  1872. int numberOfTimesToRepeat);
  1873. /** Returns a copy of this string with the specified character repeatedly added to its
  1874. beginning until the total length is at least the minimum length specified.
  1875. */
  1876. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  1877. /** Returns a copy of this string with the specified character repeatedly added to its
  1878. end until the total length is at least the minimum length specified.
  1879. */
  1880. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  1881. /** Creates a string from data in an unknown format.
  1882. This looks at some binary data and tries to guess whether it's Unicode
  1883. or 8-bit characters, then returns a string that represents it correctly.
  1884. Should be able to handle Unicode endianness correctly, by looking at
  1885. the first two bytes.
  1886. */
  1887. static const String createStringFromData (const void* data, int size);
  1888. /** Creates a String from a printf-style parameter list.
  1889. I don't like this method. I don't use it myself, and I recommend avoiding it and
  1890. using the operator<< methods or pretty much anything else instead. It's only provided
  1891. here because of the popular unrest that was stirred-up when I tried to remove it...
  1892. If you're really determined to use it, at least make sure that you never, ever,
  1893. pass any String objects to it as parameters.
  1894. */
  1895. static const String formatted (const juce_wchar* formatString, ... );
  1896. // Numeric conversions..
  1897. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1898. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1899. */
  1900. explicit String (int decimalInteger);
  1901. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1902. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1903. */
  1904. explicit String (unsigned int decimalInteger);
  1905. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1906. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1907. */
  1908. explicit String (short decimalInteger);
  1909. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1910. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1911. */
  1912. explicit String (unsigned short decimalInteger);
  1913. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1914. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1915. */
  1916. explicit String (int64 largeIntegerValue);
  1917. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1918. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1919. */
  1920. explicit String (uint64 largeIntegerValue);
  1921. /** Creates a string representing this floating-point number.
  1922. @param floatValue the value to convert to a string
  1923. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1924. decimal places, and will not use exponent notation. If 0 or
  1925. less, it will use exponent notation if necessary.
  1926. @see getDoubleValue, getIntValue
  1927. */
  1928. explicit String (float floatValue,
  1929. int numberOfDecimalPlaces = 0);
  1930. /** Creates a string representing this floating-point number.
  1931. @param doubleValue the value to convert to a string
  1932. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1933. decimal places, and will not use exponent notation. If 0 or
  1934. less, it will use exponent notation if necessary.
  1935. @see getFloatValue, getIntValue
  1936. */
  1937. explicit String (double doubleValue,
  1938. int numberOfDecimalPlaces = 0);
  1939. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1940. @returns the value of the string as a 32 bit signed base-10 integer.
  1941. @see getTrailingIntValue, getHexValue32, getHexValue64
  1942. */
  1943. int getIntValue() const throw();
  1944. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1945. @returns the value of the string as a 64 bit signed base-10 integer.
  1946. */
  1947. int64 getLargeIntValue() const throw();
  1948. /** Parses a decimal number from the end of the string.
  1949. This will look for a value at the end of the string.
  1950. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1951. Negative numbers are not handled, so "xyz-5" returns 5.
  1952. @see getIntValue
  1953. */
  1954. int getTrailingIntValue() const throw();
  1955. /** Parses this string as a floating point number.
  1956. @returns the value of the string as a 32-bit floating point value.
  1957. @see getDoubleValue
  1958. */
  1959. float getFloatValue() const throw();
  1960. /** Parses this string as a floating point number.
  1961. @returns the value of the string as a 64-bit floating point value.
  1962. @see getFloatValue
  1963. */
  1964. double getDoubleValue() const throw();
  1965. /** Parses the string as a hexadecimal number.
  1966. Non-hexadecimal characters in the string are ignored.
  1967. If the string contains too many characters, then the lowest significant
  1968. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1969. @returns a 32-bit number which is the value of the string in hex.
  1970. */
  1971. int getHexValue32() const throw();
  1972. /** Parses the string as a hexadecimal number.
  1973. Non-hexadecimal characters in the string are ignored.
  1974. If the string contains too many characters, then the lowest significant
  1975. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1976. @returns a 64-bit number which is the value of the string in hex.
  1977. */
  1978. int64 getHexValue64() const throw();
  1979. /** Creates a string representing this 32-bit value in hexadecimal. */
  1980. static const String toHexString (int number);
  1981. /** Creates a string representing this 64-bit value in hexadecimal. */
  1982. static const String toHexString (int64 number);
  1983. /** Creates a string representing this 16-bit value in hexadecimal. */
  1984. static const String toHexString (short number);
  1985. /** Creates a string containing a hex dump of a block of binary data.
  1986. @param data the binary data to use as input
  1987. @param size how many bytes of data to use
  1988. @param groupSize how many bytes are grouped together before inserting a
  1989. space into the output. e.g. group size 0 has no spaces,
  1990. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1991. like "bea1 c2ff".
  1992. */
  1993. static const String toHexString (const unsigned char* data,
  1994. int size,
  1995. int groupSize = 1);
  1996. /** Returns a unicode version of this string.
  1997. Because it returns a reference to the string's internal data, the pointer
  1998. that is returned must not be stored anywhere, as it can become invalid whenever
  1999. any string methods (even some const ones!) are called.
  2000. */
  2001. inline operator const juce_wchar*() const throw() { return text; }
  2002. /** Returns a unicode version of this string.
  2003. Because it returns a reference to the string's internal data, the pointer
  2004. that is returned must not be stored anywhere, as it can become invalid whenever
  2005. any string methods (even some const ones!) are called.
  2006. */
  2007. inline operator juce_wchar*() throw() { return text; }
  2008. /** Returns a pointer to a UTF-8 version of this string.
  2009. Because it returns a reference to the string's internal data, the pointer
  2010. that is returned must not be stored anywhere, as it can be deleted whenever the
  2011. string changes.
  2012. @see getNumBytesAsUTF8, fromUTF8, copyToUTF8, toCString
  2013. */
  2014. const char* toUTF8() const;
  2015. /** Creates a String from a UTF-8 encoded buffer.
  2016. If the size is < 0, it'll keep reading until it hits a zero.
  2017. */
  2018. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  2019. /** Returns the number of bytes required to represent this string as UTF8.
  2020. The number returned does NOT include the trailing zero.
  2021. @see toUTF8, copyToUTF8
  2022. */
  2023. int getNumBytesAsUTF8() const throw();
  2024. /** Copies the string to a buffer as UTF-8 characters.
  2025. Returns the number of bytes copied to the buffer, including the terminating null
  2026. character.
  2027. @param destBuffer the place to copy it to; if this is a null pointer,
  2028. the method just returns the number of bytes required
  2029. (including the terminating null character).
  2030. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  2031. string won't fit, it'll put in as many as it can while
  2032. still allowing for a terminating null char at the end, and
  2033. will return the number of bytes that were actually used.
  2034. */
  2035. int copyToUTF8 (char* destBuffer, int maxBufferSizeBytes) const throw();
  2036. /** Returns a version of this string using the default 8-bit multi-byte system encoding.
  2037. Because it returns a reference to the string's internal data, the pointer
  2038. that is returned must not be stored anywhere, as it can be deleted whenever the
  2039. string changes.
  2040. @see getNumBytesAsCString, copyToCString, toUTF8
  2041. */
  2042. const char* toCString() const;
  2043. /** Returns the number of bytes
  2044. */
  2045. int getNumBytesAsCString() const throw();
  2046. /** Copies the string to a buffer.
  2047. @param destBuffer the place to copy it to; if this is a null pointer,
  2048. the method just returns the number of bytes required
  2049. (including the terminating null character).
  2050. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  2051. string won't fit, it'll put in as many as it can while
  2052. still allowing for a terminating null char at the end, and
  2053. will return the number of bytes that were actually used.
  2054. */
  2055. int copyToCString (char* destBuffer, int maxBufferSizeBytes) const throw();
  2056. /** Copies the string to a unicode buffer.
  2057. @param destBuffer the place to copy it to
  2058. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  2059. NOT including the trailing zero, so this shouldn't be
  2060. larger than the size of your destination buffer - 1
  2061. */
  2062. void copyToUnicode (juce_wchar* destBuffer, int maxCharsToCopy) const throw();
  2063. /** Increases the string's internally allocated storage.
  2064. Although the string's contents won't be affected by this call, it will
  2065. increase the amount of memory allocated internally for the string to grow into.
  2066. If you're about to make a large number of calls to methods such
  2067. as += or <<, it's more efficient to preallocate enough extra space
  2068. beforehand, so that these methods won't have to keep resizing the string
  2069. to append the extra characters.
  2070. @param numCharsNeeded the number of characters to allocate storage for. If this
  2071. value is less than the currently allocated size, it will
  2072. have no effect.
  2073. */
  2074. void preallocateStorage (size_t numCharsNeeded);
  2075. /** Swaps the contents of this string with another one.
  2076. This is a very fast operation, as no allocation or copying needs to be done.
  2077. */
  2078. void swapWith (String& other) throw();
  2079. /** A helper class to improve performance when concatenating many large strings
  2080. together.
  2081. Because appending one string to another involves measuring the length of
  2082. both strings, repeatedly doing this for many long strings will become
  2083. an exponentially slow operation. This class uses some internal state to
  2084. avoid that, so that each append operation only needs to measure the length
  2085. of the appended string.
  2086. */
  2087. class JUCE_API Concatenator
  2088. {
  2089. public:
  2090. Concatenator (String& stringToAppendTo);
  2091. ~Concatenator();
  2092. void append (const String& s);
  2093. private:
  2094. String& result;
  2095. int nextIndex;
  2096. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  2097. };
  2098. private:
  2099. juce_wchar* text;
  2100. struct Preallocation
  2101. {
  2102. explicit Preallocation (size_t);
  2103. size_t numChars;
  2104. };
  2105. // This constructor preallocates a certain amount of memory
  2106. explicit String (const Preallocation&);
  2107. String (const String& stringToCopy, size_t charsToAllocate);
  2108. void createInternal (const juce_wchar* text, size_t numChars);
  2109. void appendInternal (const juce_wchar* text, int numExtraChars);
  2110. // This private cast operator should prevent strings being accidentally cast
  2111. // to bools (this is possible because the compiler can add an implicit cast
  2112. // via a const char*)
  2113. operator bool() const throw() { return false; }
  2114. };
  2115. /** Concatenates two strings. */
  2116. JUCE_API const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  2117. /** Concatenates two strings. */
  2118. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* string1, const String& string2);
  2119. /** Concatenates two strings. */
  2120. JUCE_API const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  2121. /** Concatenates two strings. */
  2122. JUCE_API const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  2123. /** Concatenates two strings. */
  2124. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  2125. /** Concatenates two strings. */
  2126. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  2127. /** Concatenates two strings. */
  2128. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* string2);
  2129. /** Concatenates two strings. */
  2130. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  2131. /** Concatenates two strings. */
  2132. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  2133. /** Appends a character at the end of a string. */
  2134. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  2135. /** Appends a character at the end of a string. */
  2136. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  2137. /** Appends a string to the end of the first one. */
  2138. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  2139. /** Appends a string to the end of the first one. */
  2140. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* string2);
  2141. /** Appends a string to the end of the first one. */
  2142. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  2143. /** Appends a decimal number at the end of a string. */
  2144. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  2145. /** Appends a decimal number at the end of a string. */
  2146. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  2147. /** Appends a decimal number at the end of a string. */
  2148. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, unsigned int number);
  2149. /** Appends a decimal number at the end of a string. */
  2150. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  2151. /** Appends a decimal number at the end of a string. */
  2152. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, unsigned long number);
  2153. /** Appends a decimal number at the end of a string. */
  2154. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  2155. /** Appends a decimal number at the end of a string. */
  2156. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  2157. /** Case-sensitive comparison of two strings. */
  2158. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  2159. /** Case-sensitive comparison of two strings. */
  2160. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  2161. /** Case-sensitive comparison of two strings. */
  2162. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw();
  2163. /** Case-sensitive comparison of two strings. */
  2164. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  2165. /** Case-sensitive comparison of two strings. */
  2166. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  2167. /** Case-sensitive comparison of two strings. */
  2168. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw();
  2169. /** Case-sensitive comparison of two strings. */
  2170. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  2171. /** Case-sensitive comparison of two strings. */
  2172. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  2173. /** Case-sensitive comparison of two strings. */
  2174. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  2175. /** Case-sensitive comparison of two strings. */
  2176. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  2177. /** This streaming override allows you to pass a juce String directly into std output streams.
  2178. This is very handy for writing strings to std::cout, std::cerr, etc.
  2179. */
  2180. template <class charT, class traits>
  2181. JUCE_API std::basic_ostream <charT, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  2182. {
  2183. return stream << stringToWrite.toUTF8();
  2184. }
  2185. /** Writes a string to an OutputStream as UTF8. */
  2186. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text);
  2187. #endif // __JUCE_STRING_JUCEHEADER__
  2188. /*** End of inlined file: juce_String.h ***/
  2189. /**
  2190. Acts as an application-wide logging class.
  2191. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  2192. method and this will then be used by all calls to writeToLog.
  2193. The logger class also contains methods for writing messages to the debugger's
  2194. output stream.
  2195. @see FileLogger
  2196. */
  2197. class JUCE_API Logger
  2198. {
  2199. public:
  2200. /** Destructor. */
  2201. virtual ~Logger();
  2202. /** Sets the current logging class to use.
  2203. Note that the object passed in won't be deleted when no longer needed.
  2204. A null pointer can be passed-in to disable any logging.
  2205. If deleteOldLogger is set to true, the existing logger will be
  2206. deleted (if there is one).
  2207. */
  2208. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  2209. bool deleteOldLogger = false);
  2210. /** Writes a string to the current logger.
  2211. This will pass the string to the logger's logMessage() method if a logger
  2212. has been set.
  2213. @see logMessage
  2214. */
  2215. static void JUCE_CALLTYPE writeToLog (const String& message);
  2216. /** Writes a message to the standard error stream.
  2217. This can be called directly, or by using the DBG() macro in
  2218. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2219. */
  2220. static void JUCE_CALLTYPE outputDebugString (const String& text);
  2221. protected:
  2222. Logger();
  2223. /** This is overloaded by subclasses to implement custom logging behaviour.
  2224. @see setCurrentLogger
  2225. */
  2226. virtual void logMessage (const String& message) = 0;
  2227. private:
  2228. static Logger* currentLogger;
  2229. };
  2230. #endif // __JUCE_LOGGER_JUCEHEADER__
  2231. /*** End of inlined file: juce_Logger.h ***/
  2232. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  2233. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  2234. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  2235. /*** Start of inlined file: juce_Atomic.h ***/
  2236. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  2237. #define __JUCE_ATOMIC_JUCEHEADER__
  2238. /**
  2239. Simple class to hold a primitive value and perform atomic operations on it.
  2240. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  2241. There are methods to perform most of the basic atomic operations.
  2242. */
  2243. template <typename Type>
  2244. class Atomic
  2245. {
  2246. public:
  2247. /** Creates a new value, initialised to zero. */
  2248. inline Atomic() throw()
  2249. : value (0)
  2250. {
  2251. }
  2252. /** Creates a new value, with a given initial value. */
  2253. inline Atomic (const Type initialValue) throw()
  2254. : value (initialValue)
  2255. {
  2256. }
  2257. /** Copies another value (atomically). */
  2258. inline Atomic (const Atomic& other) throw()
  2259. : value (other.get())
  2260. {
  2261. }
  2262. /** Destructor. */
  2263. inline ~Atomic() throw()
  2264. {
  2265. // This class can only be used for types which are 32 or 64 bits in size.
  2266. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  2267. }
  2268. /** Atomically reads and returns the current value. */
  2269. Type get() const throw();
  2270. /** Copies another value onto this one (atomically). */
  2271. inline Atomic& operator= (const Atomic& other) throw() { exchange (other.get()); return *this; }
  2272. /** Copies another value onto this one (atomically). */
  2273. inline Atomic& operator= (const Type newValue) throw() { exchange (newValue); return *this; }
  2274. /** Atomically sets the current value. */
  2275. void set (Type newValue) throw() { exchange (newValue); }
  2276. /** Atomically sets the current value, returning the value that was replaced. */
  2277. Type exchange (Type value) throw();
  2278. /** Atomically adds a number to this value, returning the new value. */
  2279. Type operator+= (Type amountToAdd) throw();
  2280. /** Atomically subtracts a number from this value, returning the new value. */
  2281. Type operator-= (Type amountToSubtract) throw();
  2282. /** Atomically increments this value, returning the new value. */
  2283. Type operator++() throw();
  2284. /** Atomically decrements this value, returning the new value. */
  2285. Type operator--() throw();
  2286. /** Atomically compares this value with a target value, and if it is equal, sets
  2287. this to be equal to a new value.
  2288. This operation is the atomic equivalent of doing this:
  2289. @code
  2290. bool compareAndSetBool (Type newValue, Type valueToCompare)
  2291. {
  2292. if (get() == valueToCompare)
  2293. {
  2294. set (newValue);
  2295. return true;
  2296. }
  2297. return false;
  2298. }
  2299. @endcode
  2300. @returns true if the comparison was true and the value was replaced; false if
  2301. the comparison failed and the value was left unchanged.
  2302. @see compareAndSetValue
  2303. */
  2304. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  2305. /** Atomically compares this value with a target value, and if it is equal, sets
  2306. this to be equal to a new value.
  2307. This operation is the atomic equivalent of doing this:
  2308. @code
  2309. Type compareAndSetValue (Type newValue, Type valueToCompare)
  2310. {
  2311. Type oldValue = get();
  2312. if (oldValue == valueToCompare)
  2313. set (newValue);
  2314. return oldValue;
  2315. }
  2316. @endcode
  2317. @returns the old value before it was changed.
  2318. @see compareAndSetBool
  2319. */
  2320. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  2321. /** Implements a memory read/write barrier. */
  2322. static void memoryBarrier() throw();
  2323. JUCE_ALIGN(8)
  2324. /** The raw value that this class operates on.
  2325. This is exposed publically in case you need to manipulate it directly
  2326. for performance reasons.
  2327. */
  2328. volatile Type value;
  2329. private:
  2330. static inline Type castFrom32Bit (int32 value) throw() { return *(Type*) &value; }
  2331. static inline Type castFrom64Bit (int64 value) throw() { return *(Type*) &value; }
  2332. static inline int32 castTo32Bit (Type value) throw() { return *(int32*) &value; }
  2333. static inline int64 castTo64Bit (Type value) throw() { return *(int64*) &value; }
  2334. Type operator++ (int); // better to just use pre-increment with atomics..
  2335. Type operator-- (int);
  2336. };
  2337. /*
  2338. The following code is in the header so that the atomics can be inlined where possible...
  2339. */
  2340. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  2341. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  2342. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  2343. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  2344. #define JUCE_MAC_ATOMICS_VOLATILE
  2345. #else
  2346. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  2347. #endif
  2348. #if JUCE_PPC || JUCE_IOS
  2349. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  2350. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return *a += b; }
  2351. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return ++*a; }
  2352. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return --*a; }
  2353. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) throw()
  2354. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  2355. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  2356. #endif
  2357. #elif JUCE_GCC
  2358. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  2359. #if JUCE_IOS
  2360. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  2361. #endif
  2362. #else
  2363. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  2364. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  2365. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  2366. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  2367. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  2368. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  2369. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  2370. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  2371. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  2372. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  2373. #define juce_MemoryBarrier _ReadWriteBarrier
  2374. #else
  2375. // (these are defined in juce_win32_Threads.cpp)
  2376. long juce_InterlockedExchange (volatile long* a, long b) throw();
  2377. long juce_InterlockedIncrement (volatile long* a) throw();
  2378. long juce_InterlockedDecrement (volatile long* a) throw();
  2379. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  2380. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  2381. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  2382. inline void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  2383. #endif
  2384. #if JUCE_64BIT
  2385. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  2386. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  2387. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  2388. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  2389. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  2390. #else
  2391. // None of these atomics are available in a 32-bit Windows build!!
  2392. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  2393. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  2394. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  2395. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  2396. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  2397. #endif
  2398. #endif
  2399. #if JUCE_MSVC
  2400. #pragma warning (push)
  2401. #pragma warning (disable: 4311) // (truncation warning)
  2402. #endif
  2403. template <typename Type>
  2404. inline Type Atomic<Type>::get() const throw()
  2405. {
  2406. #if JUCE_ATOMICS_MAC
  2407. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  2408. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  2409. #elif JUCE_ATOMICS_WINDOWS
  2410. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  2411. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  2412. #elif JUCE_ATOMICS_GCC
  2413. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  2414. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  2415. #endif
  2416. }
  2417. template <typename Type>
  2418. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  2419. {
  2420. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  2421. Type currentVal = value;
  2422. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  2423. return currentVal;
  2424. #elif JUCE_ATOMICS_WINDOWS
  2425. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  2426. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  2427. #endif
  2428. }
  2429. template <typename Type>
  2430. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  2431. {
  2432. #if JUCE_ATOMICS_MAC
  2433. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  2434. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  2435. #elif JUCE_ATOMICS_WINDOWS
  2436. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  2437. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  2438. #elif JUCE_ATOMICS_GCC
  2439. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  2440. #endif
  2441. }
  2442. template <typename Type>
  2443. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  2444. {
  2445. return operator+= (juce_negate (amountToSubtract));
  2446. }
  2447. template <typename Type>
  2448. inline Type Atomic<Type>::operator++() throw()
  2449. {
  2450. #if JUCE_ATOMICS_MAC
  2451. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  2452. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  2453. #elif JUCE_ATOMICS_WINDOWS
  2454. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  2455. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  2456. #elif JUCE_ATOMICS_GCC
  2457. return (Type) __sync_add_and_fetch (&value, 1);
  2458. #endif
  2459. }
  2460. template <typename Type>
  2461. inline Type Atomic<Type>::operator--() throw()
  2462. {
  2463. #if JUCE_ATOMICS_MAC
  2464. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  2465. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  2466. #elif JUCE_ATOMICS_WINDOWS
  2467. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  2468. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  2469. #elif JUCE_ATOMICS_GCC
  2470. return (Type) __sync_add_and_fetch (&value, -1);
  2471. #endif
  2472. }
  2473. template <typename Type>
  2474. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  2475. {
  2476. #if JUCE_ATOMICS_MAC
  2477. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  2478. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  2479. #elif JUCE_ATOMICS_WINDOWS
  2480. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  2481. #elif JUCE_ATOMICS_GCC
  2482. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  2483. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  2484. #endif
  2485. }
  2486. template <typename Type>
  2487. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  2488. {
  2489. #if JUCE_ATOMICS_MAC
  2490. for (;;) // Annoying workaround for OSX only having a bool CAS operation..
  2491. {
  2492. if (compareAndSetBool (newValue, valueToCompare))
  2493. return valueToCompare;
  2494. const Type result = value;
  2495. if (result != valueToCompare)
  2496. return result;
  2497. }
  2498. #elif JUCE_ATOMICS_WINDOWS
  2499. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  2500. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  2501. #elif JUCE_ATOMICS_GCC
  2502. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  2503. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  2504. #endif
  2505. }
  2506. template <typename Type>
  2507. inline void Atomic<Type>::memoryBarrier() throw()
  2508. {
  2509. #if JUCE_ATOMICS_MAC
  2510. OSMemoryBarrier();
  2511. #elif JUCE_ATOMICS_GCC
  2512. __sync_synchronize();
  2513. #elif JUCE_ATOMICS_WINDOWS
  2514. juce_MemoryBarrier();
  2515. #endif
  2516. }
  2517. #if JUCE_MSVC
  2518. #pragma warning (pop)
  2519. #endif
  2520. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2521. /*** End of inlined file: juce_Atomic.h ***/
  2522. /**
  2523. Embedding an instance of this class inside another class can be used as a low-overhead
  2524. way of detecting leaked instances.
  2525. This class keeps an internal static count of the number of instances that are
  2526. active, so that when the app is shutdown and the static destructors are called,
  2527. it can check whether there are any left-over instances that may have been leaked.
  2528. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  2529. class declaration. Have a look through the juce codebase for examples, it's used
  2530. in most of the classes.
  2531. */
  2532. template <class OwnerClass>
  2533. class LeakedObjectDetector
  2534. {
  2535. public:
  2536. LeakedObjectDetector() throw() { ++(getCounter().numObjects); }
  2537. LeakedObjectDetector (const LeakedObjectDetector&) throw() { ++(getCounter().numObjects); }
  2538. ~LeakedObjectDetector()
  2539. {
  2540. if (--(getCounter().numObjects) < 0)
  2541. {
  2542. DBG ("*** Dangling pointer deletion! Class: " << String (typeid (OwnerClass).name()));
  2543. /** If you hit this, then you've managed to delete more instances of this class than you've
  2544. created.. That indicates that you're deleting some dangling pointers.
  2545. Note that although this assertion will have been triggered during a destructor, it might
  2546. not be this particular deletion that's at fault - the incorrect one may have happened
  2547. at an earlier point in the program, and simply not been detected until now.
  2548. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  2549. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  2550. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  2551. */
  2552. jassertfalse;
  2553. }
  2554. }
  2555. private:
  2556. class LeakCounter
  2557. {
  2558. public:
  2559. LeakCounter() {}
  2560. ~LeakCounter()
  2561. {
  2562. if (numObjects.value > 0)
  2563. {
  2564. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << String (typeid (OwnerClass).name()));
  2565. /** If you hit this, then you've leaked one or more objects of the type specified by
  2566. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  2567. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  2568. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  2569. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  2570. */
  2571. jassertfalse;
  2572. }
  2573. }
  2574. Atomic<int> numObjects;
  2575. };
  2576. static LeakCounter& getCounter() throw()
  2577. {
  2578. static LeakCounter counter;
  2579. return counter;
  2580. }
  2581. };
  2582. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  2583. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  2584. /** This macro lets you embed a leak-detecting object inside a class.
  2585. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  2586. of the class declaration. E.g.
  2587. @code
  2588. class MyClass
  2589. {
  2590. public:
  2591. MyClass();
  2592. void blahBlah();
  2593. private:
  2594. JUCE_LEAK_DETECTOR (MyClass);
  2595. };@endcode
  2596. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  2597. */
  2598. #define JUCE_LEAK_DETECTOR(OwnerClass) JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  2599. #else
  2600. #define JUCE_LEAK_DETECTOR(OwnerClass)
  2601. #endif
  2602. #endif
  2603. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  2604. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  2605. END_JUCE_NAMESPACE
  2606. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2607. /*** End of inlined file: juce_StandardHeader.h ***/
  2608. BEGIN_JUCE_NAMESPACE
  2609. #if JUCE_MSVC
  2610. // this is set explicitly in case the app is using a different packing size.
  2611. #pragma pack (push, 8)
  2612. #pragma warning (push)
  2613. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2614. #endif
  2615. // this is where all the class header files get brought in..
  2616. /*** Start of inlined file: juce_core_includes.h ***/
  2617. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2618. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2619. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  2620. /*** Start of inlined file: juce_AbstractFifo.h ***/
  2621. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  2622. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  2623. /**
  2624. Encapsulates the logic required to implement a lock-free FIFO.
  2625. This class handles the logic needed when building a single-reader, single-writer FIFO.
  2626. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  2627. its position and status when reading or writing to it.
  2628. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  2629. an incoming block of data should be stored, and prepareToRead() to find out when the next
  2630. outgoing block should be read from.
  2631. e.g.
  2632. @code
  2633. class MyFifo
  2634. {
  2635. public:
  2636. MyFifo() : abstractFifo (1024)
  2637. {
  2638. }
  2639. void addToFifo (const int* someData, int numItems)
  2640. {
  2641. int start1, size1, start2, size2;
  2642. prepareToWrite (numItems, start1, size1, start2, size2);
  2643. if (size1 > 0)
  2644. copySomeData (myBuffer + start1, someData, size1);
  2645. if (size2 > 0)
  2646. copySomeData (myBuffer + start2, someData + size1, size2);
  2647. finishedWrite (size1 + size2);
  2648. }
  2649. void readFromFifo (int* someData, int numItems)
  2650. {
  2651. int start1, size1, start2, size2;
  2652. prepareToRead (numSamples, start1, size1, start2, size2);
  2653. if (size1 > 0)
  2654. copySomeData (someData, myBuffer + start1, size1);
  2655. if (size2 > 0)
  2656. copySomeData (someData + size1, myBuffer + start2, size2);
  2657. finishedRead (size1 + size2);
  2658. }
  2659. private:
  2660. AbstractFifo abstractFifo;
  2661. int myBuffer [1024];
  2662. };
  2663. @endcode
  2664. */
  2665. class JUCE_API AbstractFifo
  2666. {
  2667. public:
  2668. /** Creates a FIFO to manage a buffer with the specified capacity. */
  2669. AbstractFifo (int capacity) throw();
  2670. /** Destructor */
  2671. ~AbstractFifo();
  2672. /** Returns the total size of the buffer being managed. */
  2673. int getTotalSize() const throw();
  2674. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  2675. int getFreeSpace() const throw();
  2676. /** Returns the number of items that can currently be read from the buffer. */
  2677. int getNumReady() const throw();
  2678. /** Clears the buffer positions, so that it appears empty. */
  2679. void reset() throw();
  2680. /** Changes the buffer's total size.
  2681. Note that this isn't thread-safe, so don't call it if there's any danger that it
  2682. might overlap with a call to any other method in this class!
  2683. */
  2684. void setTotalSize (int newSize) throw();
  2685. /** Returns the location within the buffer at which an incoming block of data should be written.
  2686. Because the section of data that you want to add to the buffer may overlap the end
  2687. and wrap around to the start, two blocks within your buffer are returned, and you
  2688. should copy your data into the first one, with any remaining data spilling over into
  2689. the second.
  2690. If the number of items you ask for is too large to fit within the buffer's free space, then
  2691. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  2692. may decide to keep waiting and re-trying the method until there's enough space available.
  2693. After calling this method, if you choose to write your data into the blocks returned, you
  2694. must call finishedWrite() to tell the FIFO how much data you actually added.
  2695. e.g.
  2696. @code
  2697. void addToFifo (const int* someData, int numItems)
  2698. {
  2699. int start1, size1, start2, size2;
  2700. prepareToWrite (numItems, start1, size1, start2, size2);
  2701. if (size1 > 0)
  2702. copySomeData (myBuffer + start1, someData, size1);
  2703. if (size2 > 0)
  2704. copySomeData (myBuffer + start2, someData + size1, size2);
  2705. finishedWrite (size1 + size2);
  2706. }
  2707. @endcode
  2708. @param numToWrite indicates how many items you'd like to add to the buffer
  2709. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  2710. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  2711. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  2712. the first block should be written
  2713. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  2714. @see finishedWrite
  2715. */
  2716. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  2717. /** Called after reading from the FIFO, to indicate that this many items have been added.
  2718. @see prepareToWrite
  2719. */
  2720. void finishedWrite (int numWritten) throw();
  2721. /** Returns the location within the buffer from which the next block of data should be read.
  2722. Because the section of data that you want to read from the buffer may overlap the end
  2723. and wrap around to the start, two blocks within your buffer are returned, and you
  2724. should read from both of them.
  2725. If the number of items you ask for is greater than the amount of data available, then
  2726. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  2727. may decide to keep waiting and re-trying the method until there's enough data available.
  2728. After calling this method, if you choose to read the data, you must call finishedRead() to
  2729. tell the FIFO how much data you have consumed.
  2730. e.g.
  2731. @code
  2732. void readFromFifo (int* someData, int numItems)
  2733. {
  2734. int start1, size1, start2, size2;
  2735. prepareToRead (numSamples, start1, size1, start2, size2);
  2736. if (size1 > 0)
  2737. copySomeData (someData, myBuffer + start1, size1);
  2738. if (size2 > 0)
  2739. copySomeData (someData + size1, myBuffer + start2, size2);
  2740. finishedRead (size1 + size2);
  2741. }
  2742. @endcode
  2743. @param numWanted indicates how many items you'd like to add to the buffer
  2744. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  2745. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  2746. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  2747. the first block should be written
  2748. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  2749. @see finishedRead
  2750. */
  2751. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  2752. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  2753. @see prepareToRead
  2754. */
  2755. void finishedRead (int numRead) throw();
  2756. private:
  2757. int bufferSize;
  2758. Atomic <int> validStart, validEnd;
  2759. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  2760. };
  2761. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  2762. /*** End of inlined file: juce_AbstractFifo.h ***/
  2763. #endif
  2764. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2765. /*** Start of inlined file: juce_Array.h ***/
  2766. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2767. #define __JUCE_ARRAY_JUCEHEADER__
  2768. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  2769. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2770. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2771. /*** Start of inlined file: juce_HeapBlock.h ***/
  2772. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  2773. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  2774. /**
  2775. Very simple container class to hold a pointer to some data on the heap.
  2776. When you need to allocate some heap storage for something, always try to use
  2777. this class instead of allocating the memory directly using malloc/free.
  2778. A HeapBlock<char> object can be treated in pretty much exactly the same way
  2779. as an char*, but as long as you allocate it on the stack or as a class member,
  2780. it's almost impossible for it to leak memory.
  2781. It also makes your code much more concise and readable than doing the same thing
  2782. using direct allocations,
  2783. E.g. instead of this:
  2784. @code
  2785. int* temp = (int*) malloc (1024 * sizeof (int));
  2786. memcpy (temp, xyz, 1024 * sizeof (int));
  2787. free (temp);
  2788. temp = (int*) calloc (2048 * sizeof (int));
  2789. temp[0] = 1234;
  2790. memcpy (foobar, temp, 2048 * sizeof (int));
  2791. free (temp);
  2792. @endcode
  2793. ..you could just write this:
  2794. @code
  2795. HeapBlock <int> temp (1024);
  2796. memcpy (temp, xyz, 1024 * sizeof (int));
  2797. temp.calloc (2048);
  2798. temp[0] = 1234;
  2799. memcpy (foobar, temp, 2048 * sizeof (int));
  2800. @endcode
  2801. The class is extremely lightweight, containing only a pointer to the
  2802. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  2803. as their less object-oriented counterparts. Despite adding safety, you probably
  2804. won't sacrifice any performance by using this in place of normal pointers.
  2805. @see Array, OwnedArray, MemoryBlock
  2806. */
  2807. template <class ElementType>
  2808. class HeapBlock
  2809. {
  2810. public:
  2811. /** Creates a HeapBlock which is initially just a null pointer.
  2812. After creation, you can resize the array using the malloc(), calloc(),
  2813. or realloc() methods.
  2814. */
  2815. HeapBlock() throw() : data (0)
  2816. {
  2817. }
  2818. /** Creates a HeapBlock containing a number of elements.
  2819. The contents of the block are undefined, as it will have been created by a
  2820. malloc call.
  2821. If you want an array of zero values, you can use the calloc() method instead.
  2822. */
  2823. explicit HeapBlock (const size_t numElements)
  2824. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  2825. {
  2826. }
  2827. /** Destructor.
  2828. This will free the data, if any has been allocated.
  2829. */
  2830. ~HeapBlock()
  2831. {
  2832. ::free (data);
  2833. }
  2834. /** Returns a raw pointer to the allocated data.
  2835. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2836. freed by calling the free() method.
  2837. */
  2838. inline operator ElementType*() const throw() { return data; }
  2839. /** Returns a raw pointer to the allocated data.
  2840. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2841. freed by calling the free() method.
  2842. */
  2843. inline ElementType* getData() const throw() { return data; }
  2844. /** Returns a void pointer to the allocated data.
  2845. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2846. freed by calling the free() method.
  2847. */
  2848. inline operator void*() const throw() { return static_cast <void*> (data); }
  2849. /** Returns a void pointer to the allocated data.
  2850. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2851. freed by calling the free() method.
  2852. */
  2853. inline operator const void*() const throw() { return static_cast <const void*> (data); }
  2854. /** Lets you use indirect calls to the first element in the array.
  2855. Obviously this will cause problems if the array hasn't been initialised, because it'll
  2856. be referencing a null pointer.
  2857. */
  2858. inline ElementType* operator->() const throw() { return data; }
  2859. /** Returns a reference to one of the data elements.
  2860. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  2861. has no idea of the size it currently has allocated.
  2862. */
  2863. template <typename IndexType>
  2864. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  2865. /** Returns a pointer to a data element at an offset from the start of the array.
  2866. This is the same as doing pointer arithmetic on the raw pointer itself.
  2867. */
  2868. template <typename IndexType>
  2869. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  2870. /** Compares the pointer with another pointer.
  2871. This can be handy for checking whether this is a null pointer.
  2872. */
  2873. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  2874. /** Compares the pointer with another pointer.
  2875. This can be handy for checking whether this is a null pointer.
  2876. */
  2877. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  2878. /** Allocates a specified amount of memory.
  2879. This uses the normal malloc to allocate an amount of memory for this object.
  2880. Any previously allocated memory will be freed by this method.
  2881. The number of bytes allocated will be (newNumElements * elementSize). Normally
  2882. you wouldn't need to specify the second parameter, but it can be handy if you need
  2883. to allocate a size in bytes rather than in terms of the number of elements.
  2884. The data that is allocated will be freed when this object is deleted, or when you
  2885. call free() or any of the allocation methods.
  2886. */
  2887. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2888. {
  2889. ::free (data);
  2890. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  2891. }
  2892. /** Allocates a specified amount of memory and clears it.
  2893. This does the same job as the malloc() method, but clears the memory that it allocates.
  2894. */
  2895. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2896. {
  2897. ::free (data);
  2898. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  2899. }
  2900. /** Allocates a specified amount of memory and optionally clears it.
  2901. This does the same job as either malloc() or calloc(), depending on the
  2902. initialiseToZero parameter.
  2903. */
  2904. void allocate (const size_t newNumElements, const bool initialiseToZero)
  2905. {
  2906. ::free (data);
  2907. if (initialiseToZero)
  2908. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  2909. else
  2910. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  2911. }
  2912. /** Re-allocates a specified amount of memory.
  2913. The semantics of this method are the same as malloc() and calloc(), but it
  2914. uses realloc() to keep as much of the existing data as possible.
  2915. */
  2916. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2917. {
  2918. if (data == 0)
  2919. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  2920. else
  2921. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  2922. }
  2923. /** Frees any currently-allocated data.
  2924. This will free the data and reset this object to be a null pointer.
  2925. */
  2926. void free()
  2927. {
  2928. ::free (data);
  2929. data = 0;
  2930. }
  2931. /** Swaps this object's data with the data of another HeapBlock.
  2932. The two objects simply exchange their data pointers.
  2933. */
  2934. void swapWith (HeapBlock <ElementType>& other) throw()
  2935. {
  2936. swapVariables (data, other.data);
  2937. }
  2938. private:
  2939. ElementType* data;
  2940. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  2941. };
  2942. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  2943. /*** End of inlined file: juce_HeapBlock.h ***/
  2944. /**
  2945. Implements some basic array storage allocation functions.
  2946. This class isn't really for public use - it's used by the other
  2947. array classes, but might come in handy for some purposes.
  2948. It inherits from a critical section class to allow the arrays to use
  2949. the "empty base class optimisation" pattern to reduce their footprint.
  2950. @see Array, OwnedArray, ReferenceCountedArray
  2951. */
  2952. template <class ElementType, class TypeOfCriticalSectionToUse>
  2953. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  2954. {
  2955. public:
  2956. /** Creates an empty array. */
  2957. ArrayAllocationBase() throw()
  2958. : numAllocated (0)
  2959. {
  2960. }
  2961. /** Destructor. */
  2962. ~ArrayAllocationBase()
  2963. {
  2964. }
  2965. /** Changes the amount of storage allocated.
  2966. This will retain any data currently held in the array, and either add or
  2967. remove extra space at the end.
  2968. @param numElements the number of elements that are needed
  2969. */
  2970. void setAllocatedSize (const int numElements)
  2971. {
  2972. if (numAllocated != numElements)
  2973. {
  2974. if (numElements > 0)
  2975. elements.realloc (numElements);
  2976. else
  2977. elements.free();
  2978. numAllocated = numElements;
  2979. }
  2980. }
  2981. /** Increases the amount of storage allocated if it is less than a given amount.
  2982. This will retain any data currently held in the array, but will add
  2983. extra space at the end to make sure there it's at least as big as the size
  2984. passed in. If it's already bigger, no action is taken.
  2985. @param minNumElements the minimum number of elements that are needed
  2986. */
  2987. void ensureAllocatedSize (const int minNumElements)
  2988. {
  2989. if (minNumElements > numAllocated)
  2990. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  2991. }
  2992. /** Minimises the amount of storage allocated so that it's no more than
  2993. the given number of elements.
  2994. */
  2995. void shrinkToNoMoreThan (const int maxNumElements)
  2996. {
  2997. if (maxNumElements < numAllocated)
  2998. setAllocatedSize (maxNumElements);
  2999. }
  3000. /** Swap the contents of two objects. */
  3001. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3002. {
  3003. elements.swapWith (other.elements);
  3004. swapVariables (numAllocated, other.numAllocated);
  3005. }
  3006. HeapBlock <ElementType> elements;
  3007. int numAllocated;
  3008. private:
  3009. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  3010. };
  3011. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3012. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  3013. /*** Start of inlined file: juce_ElementComparator.h ***/
  3014. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  3015. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  3016. /**
  3017. Sorts a range of elements in an array.
  3018. The comparator object that is passed-in must define a public method with the following
  3019. signature:
  3020. @code
  3021. int compareElements (ElementType first, ElementType second);
  3022. @endcode
  3023. ..and this method must return:
  3024. - a value of < 0 if the first comes before the second
  3025. - a value of 0 if the two objects are equivalent
  3026. - a value of > 0 if the second comes before the first
  3027. To improve performance, the compareElements() method can be declared as static or const.
  3028. @param comparator an object which defines a compareElements() method
  3029. @param array the array to sort
  3030. @param firstElement the index of the first element of the range to be sorted
  3031. @param lastElement the index of the last element in the range that needs
  3032. sorting (this is inclusive)
  3033. @param retainOrderOfEquivalentItems if true, the order of items that the
  3034. comparator deems the same will be maintained - this will be
  3035. a slower algorithm than if they are allowed to be moved around.
  3036. @see sortArrayRetainingOrder
  3037. */
  3038. template <class ElementType, class ElementComparator>
  3039. static void sortArray (ElementComparator& comparator,
  3040. ElementType* const array,
  3041. int firstElement,
  3042. int lastElement,
  3043. const bool retainOrderOfEquivalentItems)
  3044. {
  3045. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3046. // avoids getting warning messages about the parameter being unused
  3047. if (lastElement > firstElement)
  3048. {
  3049. if (retainOrderOfEquivalentItems)
  3050. {
  3051. for (int i = firstElement; i < lastElement; ++i)
  3052. {
  3053. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  3054. {
  3055. swapVariables (array[i], array[i + 1]);
  3056. if (i > firstElement)
  3057. i -= 2;
  3058. }
  3059. }
  3060. }
  3061. else
  3062. {
  3063. int fromStack[30], toStack[30];
  3064. int stackIndex = 0;
  3065. for (;;)
  3066. {
  3067. const int size = (lastElement - firstElement) + 1;
  3068. if (size <= 8)
  3069. {
  3070. int j = lastElement;
  3071. int maxIndex;
  3072. while (j > firstElement)
  3073. {
  3074. maxIndex = firstElement;
  3075. for (int k = firstElement + 1; k <= j; ++k)
  3076. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  3077. maxIndex = k;
  3078. swapVariables (array[j], array[maxIndex]);
  3079. --j;
  3080. }
  3081. }
  3082. else
  3083. {
  3084. const int mid = firstElement + (size >> 1);
  3085. swapVariables (array[mid], array[firstElement]);
  3086. int i = firstElement;
  3087. int j = lastElement + 1;
  3088. for (;;)
  3089. {
  3090. while (++i <= lastElement
  3091. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  3092. {}
  3093. while (--j > firstElement
  3094. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  3095. {}
  3096. if (j < i)
  3097. break;
  3098. swapVariables (array[i], array[j]);
  3099. }
  3100. swapVariables (array[j], array[firstElement]);
  3101. if (j - 1 - firstElement >= lastElement - i)
  3102. {
  3103. if (firstElement + 1 < j)
  3104. {
  3105. fromStack [stackIndex] = firstElement;
  3106. toStack [stackIndex] = j - 1;
  3107. ++stackIndex;
  3108. }
  3109. if (i < lastElement)
  3110. {
  3111. firstElement = i;
  3112. continue;
  3113. }
  3114. }
  3115. else
  3116. {
  3117. if (i < lastElement)
  3118. {
  3119. fromStack [stackIndex] = i;
  3120. toStack [stackIndex] = lastElement;
  3121. ++stackIndex;
  3122. }
  3123. if (firstElement + 1 < j)
  3124. {
  3125. lastElement = j - 1;
  3126. continue;
  3127. }
  3128. }
  3129. }
  3130. if (--stackIndex < 0)
  3131. break;
  3132. jassert (stackIndex < numElementsInArray (fromStack));
  3133. firstElement = fromStack [stackIndex];
  3134. lastElement = toStack [stackIndex];
  3135. }
  3136. }
  3137. }
  3138. }
  3139. /**
  3140. Searches a sorted array of elements, looking for the index at which a specified value
  3141. should be inserted for it to be in the correct order.
  3142. The comparator object that is passed-in must define a public method with the following
  3143. signature:
  3144. @code
  3145. int compareElements (ElementType first, ElementType second);
  3146. @endcode
  3147. ..and this method must return:
  3148. - a value of < 0 if the first comes before the second
  3149. - a value of 0 if the two objects are equivalent
  3150. - a value of > 0 if the second comes before the first
  3151. To improve performance, the compareElements() method can be declared as static or const.
  3152. @param comparator an object which defines a compareElements() method
  3153. @param array the array to search
  3154. @param newElement the value that is going to be inserted
  3155. @param firstElement the index of the first element to search
  3156. @param lastElement the index of the last element in the range (this is non-inclusive)
  3157. */
  3158. template <class ElementType, class ElementComparator>
  3159. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  3160. ElementType* const array,
  3161. const ElementType newElement,
  3162. int firstElement,
  3163. int lastElement)
  3164. {
  3165. jassert (firstElement <= lastElement);
  3166. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3167. // avoids getting warning messages about the parameter being unused
  3168. while (firstElement < lastElement)
  3169. {
  3170. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  3171. {
  3172. ++firstElement;
  3173. break;
  3174. }
  3175. else
  3176. {
  3177. const int halfway = (firstElement + lastElement) >> 1;
  3178. if (halfway == firstElement)
  3179. {
  3180. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  3181. ++firstElement;
  3182. break;
  3183. }
  3184. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  3185. {
  3186. firstElement = halfway;
  3187. }
  3188. else
  3189. {
  3190. lastElement = halfway;
  3191. }
  3192. }
  3193. }
  3194. return firstElement;
  3195. }
  3196. /**
  3197. A simple ElementComparator class that can be used to sort an array of
  3198. objects that support the '<' operator.
  3199. This will work for primitive types and objects that implement operator<().
  3200. Example: @code
  3201. Array <int> myArray;
  3202. DefaultElementComparator<int> sorter;
  3203. myArray.sort (sorter);
  3204. @endcode
  3205. @see ElementComparator
  3206. */
  3207. template <class ElementType>
  3208. class DefaultElementComparator
  3209. {
  3210. private:
  3211. typedef PARAMETER_TYPE (ElementType) ParameterType;
  3212. public:
  3213. static int compareElements (ParameterType first, ParameterType second)
  3214. {
  3215. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  3216. }
  3217. };
  3218. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  3219. /*** End of inlined file: juce_ElementComparator.h ***/
  3220. /*** Start of inlined file: juce_CriticalSection.h ***/
  3221. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  3222. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  3223. #ifndef DOXYGEN
  3224. class JUCE_API ScopedLock;
  3225. class JUCE_API ScopedUnlock;
  3226. #endif
  3227. /**
  3228. Prevents multiple threads from accessing shared objects at the same time.
  3229. @see ScopedLock, Thread, InterProcessLock
  3230. */
  3231. class JUCE_API CriticalSection
  3232. {
  3233. public:
  3234. /**
  3235. Creates a CriticalSection object
  3236. */
  3237. CriticalSection() throw();
  3238. /** Destroys a CriticalSection object.
  3239. If the critical section is deleted whilst locked, its subsequent behaviour
  3240. is unpredictable.
  3241. */
  3242. ~CriticalSection() throw();
  3243. /** Locks this critical section.
  3244. If the lock is currently held by another thread, this will wait until it
  3245. becomes free.
  3246. If the lock is already held by the caller thread, the method returns immediately.
  3247. @see exit, ScopedLock
  3248. */
  3249. void enter() const throw();
  3250. /** Attempts to lock this critical section without blocking.
  3251. This method behaves identically to CriticalSection::enter, except that the caller thread
  3252. does not wait if the lock is currently held by another thread but returns false immediately.
  3253. @returns false if the lock is currently held by another thread, true otherwise.
  3254. @see enter
  3255. */
  3256. bool tryEnter() const throw();
  3257. /** Releases the lock.
  3258. If the caller thread hasn't got the lock, this can have unpredictable results.
  3259. If the enter() method has been called multiple times by the thread, each
  3260. call must be matched by a call to exit() before other threads will be allowed
  3261. to take over the lock.
  3262. @see enter, ScopedLock
  3263. */
  3264. void exit() const throw();
  3265. /** Provides the type of scoped lock to use with this type of critical section object. */
  3266. typedef ScopedLock ScopedLockType;
  3267. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  3268. typedef ScopedUnlock ScopedUnlockType;
  3269. private:
  3270. #if JUCE_WINDOWS
  3271. #if JUCE_64BIT
  3272. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  3273. // block of memory here that's big enough to be used internally as a windows critical
  3274. // section object.
  3275. uint8 internal [44];
  3276. #else
  3277. uint8 internal [24];
  3278. #endif
  3279. #else
  3280. mutable pthread_mutex_t internal;
  3281. #endif
  3282. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  3283. };
  3284. /**
  3285. A class that can be used in place of a real CriticalSection object.
  3286. This is currently used by some templated classes, and should get
  3287. optimised out by the compiler.
  3288. @see Array, OwnedArray, ReferenceCountedArray
  3289. */
  3290. class JUCE_API DummyCriticalSection
  3291. {
  3292. public:
  3293. inline DummyCriticalSection() throw() {}
  3294. inline ~DummyCriticalSection() throw() {}
  3295. inline void enter() const throw() {}
  3296. inline void exit() const throw() {}
  3297. /** A dummy scoped-lock type to use with a dummy critical section. */
  3298. struct ScopedLockType
  3299. {
  3300. ScopedLockType (const DummyCriticalSection&) throw() {}
  3301. };
  3302. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  3303. typedef ScopedLockType ScopedUnlockType;
  3304. private:
  3305. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  3306. };
  3307. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  3308. /*** End of inlined file: juce_CriticalSection.h ***/
  3309. /**
  3310. Holds a resizable array of primitive or copy-by-value objects.
  3311. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  3312. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  3313. do so, the class must fulfil these requirements:
  3314. - it must have a copy constructor and assignment operator
  3315. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  3316. objects whose functionality relies on external pointers or references to themselves can be used.
  3317. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  3318. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  3319. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  3320. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  3321. specialised class StringArray, which provides more useful functions.
  3322. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3323. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3324. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3325. */
  3326. template <typename ElementType,
  3327. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  3328. class Array
  3329. {
  3330. private:
  3331. #if JUCE_VC8_OR_EARLIER
  3332. typedef const ElementType& ParameterType;
  3333. #else
  3334. typedef PARAMETER_TYPE (ElementType) ParameterType;
  3335. #endif
  3336. public:
  3337. /** Creates an empty array. */
  3338. Array() throw()
  3339. : numUsed (0)
  3340. {
  3341. }
  3342. /** Creates a copy of another array.
  3343. @param other the array to copy
  3344. */
  3345. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  3346. {
  3347. const ScopedLockType lock (other.getLock());
  3348. numUsed = other.numUsed;
  3349. data.setAllocatedSize (other.numUsed);
  3350. for (int i = 0; i < numUsed; ++i)
  3351. new (data.elements + i) ElementType (other.data.elements[i]);
  3352. }
  3353. /** Initalises from a null-terminated C array of values.
  3354. @param values the array to copy from
  3355. */
  3356. template <typename TypeToCreateFrom>
  3357. explicit Array (const TypeToCreateFrom* values)
  3358. : numUsed (0)
  3359. {
  3360. while (*values != TypeToCreateFrom())
  3361. add (*values++);
  3362. }
  3363. /** Initalises from a C array of values.
  3364. @param values the array to copy from
  3365. @param numValues the number of values in the array
  3366. */
  3367. template <typename TypeToCreateFrom>
  3368. Array (const TypeToCreateFrom* values, int numValues)
  3369. : numUsed (numValues)
  3370. {
  3371. data.setAllocatedSize (numValues);
  3372. for (int i = 0; i < numValues; ++i)
  3373. new (data.elements + i) ElementType (values[i]);
  3374. }
  3375. /** Destructor. */
  3376. ~Array()
  3377. {
  3378. for (int i = 0; i < numUsed; ++i)
  3379. data.elements[i].~ElementType();
  3380. }
  3381. /** Copies another array.
  3382. @param other the array to copy
  3383. */
  3384. Array& operator= (const Array& other)
  3385. {
  3386. if (this != &other)
  3387. {
  3388. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  3389. swapWithArray (otherCopy);
  3390. }
  3391. return *this;
  3392. }
  3393. /** Compares this array to another one.
  3394. Two arrays are considered equal if they both contain the same set of
  3395. elements, in the same order.
  3396. @param other the other array to compare with
  3397. */
  3398. template <class OtherArrayType>
  3399. bool operator== (const OtherArrayType& other) const
  3400. {
  3401. const ScopedLockType lock (getLock());
  3402. if (numUsed != other.numUsed)
  3403. return false;
  3404. for (int i = numUsed; --i >= 0;)
  3405. if (! (data.elements [i] == other.data.elements [i]))
  3406. return false;
  3407. return true;
  3408. }
  3409. /** Compares this array to another one.
  3410. Two arrays are considered equal if they both contain the same set of
  3411. elements, in the same order.
  3412. @param other the other array to compare with
  3413. */
  3414. template <class OtherArrayType>
  3415. bool operator!= (const OtherArrayType& other) const
  3416. {
  3417. return ! operator== (other);
  3418. }
  3419. /** Removes all elements from the array.
  3420. This will remove all the elements, and free any storage that the array is
  3421. using. To clear the array without freeing the storage, use the clearQuick()
  3422. method instead.
  3423. @see clearQuick
  3424. */
  3425. void clear()
  3426. {
  3427. const ScopedLockType lock (getLock());
  3428. for (int i = 0; i < numUsed; ++i)
  3429. data.elements[i].~ElementType();
  3430. data.setAllocatedSize (0);
  3431. numUsed = 0;
  3432. }
  3433. /** Removes all elements from the array without freeing the array's allocated storage.
  3434. @see clear
  3435. */
  3436. void clearQuick()
  3437. {
  3438. const ScopedLockType lock (getLock());
  3439. for (int i = 0; i < numUsed; ++i)
  3440. data.elements[i].~ElementType();
  3441. numUsed = 0;
  3442. }
  3443. /** Returns the current number of elements in the array.
  3444. */
  3445. inline int size() const throw()
  3446. {
  3447. return numUsed;
  3448. }
  3449. /** Returns one of the elements in the array.
  3450. If the index passed in is beyond the range of valid elements, this
  3451. will return zero.
  3452. If you're certain that the index will always be a valid element, you
  3453. can call getUnchecked() instead, which is faster.
  3454. @param index the index of the element being requested (0 is the first element in the array)
  3455. @see getUnchecked, getFirst, getLast
  3456. */
  3457. inline ElementType operator[] (const int index) const
  3458. {
  3459. const ScopedLockType lock (getLock());
  3460. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  3461. : ElementType();
  3462. }
  3463. /** Returns one of the elements in the array, without checking the index passed in.
  3464. Unlike the operator[] method, this will try to return an element without
  3465. checking that the index is within the bounds of the array, so should only
  3466. be used when you're confident that it will always be a valid index.
  3467. @param index the index of the element being requested (0 is the first element in the array)
  3468. @see operator[], getFirst, getLast
  3469. */
  3470. inline const ElementType getUnchecked (const int index) const
  3471. {
  3472. const ScopedLockType lock (getLock());
  3473. jassert (isPositiveAndBelow (index, numUsed));
  3474. return data.elements [index];
  3475. }
  3476. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3477. This is like getUnchecked, but returns a direct reference to the element, so that
  3478. you can alter it directly. Obviously this can be dangerous, so only use it when
  3479. absolutely necessary.
  3480. @param index the index of the element being requested (0 is the first element in the array)
  3481. @see operator[], getFirst, getLast
  3482. */
  3483. inline ElementType& getReference (const int index) const throw()
  3484. {
  3485. const ScopedLockType lock (getLock());
  3486. jassert (isPositiveAndBelow (index, numUsed));
  3487. return data.elements [index];
  3488. }
  3489. /** Returns the first element in the array, or 0 if the array is empty.
  3490. @see operator[], getUnchecked, getLast
  3491. */
  3492. inline ElementType getFirst() const
  3493. {
  3494. const ScopedLockType lock (getLock());
  3495. return (numUsed > 0) ? data.elements [0]
  3496. : ElementType();
  3497. }
  3498. /** Returns the last element in the array, or 0 if the array is empty.
  3499. @see operator[], getUnchecked, getFirst
  3500. */
  3501. inline ElementType getLast() const
  3502. {
  3503. const ScopedLockType lock (getLock());
  3504. return (numUsed > 0) ? data.elements [numUsed - 1]
  3505. : ElementType();
  3506. }
  3507. /** Returns a pointer to the actual array data.
  3508. This pointer will only be valid until the next time a non-const method
  3509. is called on the array.
  3510. */
  3511. inline ElementType* getRawDataPointer() throw()
  3512. {
  3513. return data.elements;
  3514. }
  3515. /** Finds the index of the first element which matches the value passed in.
  3516. This will search the array for the given object, and return the index
  3517. of its first occurrence. If the object isn't found, the method will return -1.
  3518. @param elementToLookFor the value or object to look for
  3519. @returns the index of the object, or -1 if it's not found
  3520. */
  3521. int indexOf (ParameterType elementToLookFor) const
  3522. {
  3523. const ScopedLockType lock (getLock());
  3524. const ElementType* e = data.elements.getData();
  3525. const ElementType* const end = e + numUsed;
  3526. while (e != end)
  3527. {
  3528. if (elementToLookFor == *e)
  3529. return static_cast <int> (e - data.elements.getData());
  3530. ++e;
  3531. }
  3532. return -1;
  3533. }
  3534. /** Returns true if the array contains at least one occurrence of an object.
  3535. @param elementToLookFor the value or object to look for
  3536. @returns true if the item is found
  3537. */
  3538. bool contains (ParameterType elementToLookFor) const
  3539. {
  3540. const ScopedLockType lock (getLock());
  3541. const ElementType* e = data.elements.getData();
  3542. const ElementType* const end = e + numUsed;
  3543. while (e != end)
  3544. {
  3545. if (elementToLookFor == *e)
  3546. return true;
  3547. ++e;
  3548. }
  3549. return false;
  3550. }
  3551. /** Appends a new element at the end of the array.
  3552. @param newElement the new object to add to the array
  3553. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  3554. */
  3555. void add (ParameterType newElement)
  3556. {
  3557. const ScopedLockType lock (getLock());
  3558. data.ensureAllocatedSize (numUsed + 1);
  3559. new (data.elements + numUsed++) ElementType (newElement);
  3560. }
  3561. /** Inserts a new element into the array at a given position.
  3562. If the index is less than 0 or greater than the size of the array, the
  3563. element will be added to the end of the array.
  3564. Otherwise, it will be inserted into the array, moving all the later elements
  3565. along to make room.
  3566. @param indexToInsertAt the index at which the new element should be
  3567. inserted (pass in -1 to add it to the end)
  3568. @param newElement the new object to add to the array
  3569. @see add, addSorted, addUsingDefaultSort, set
  3570. */
  3571. void insert (int indexToInsertAt, ParameterType newElement)
  3572. {
  3573. const ScopedLockType lock (getLock());
  3574. data.ensureAllocatedSize (numUsed + 1);
  3575. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  3576. {
  3577. ElementType* const insertPos = data.elements + indexToInsertAt;
  3578. const int numberToMove = numUsed - indexToInsertAt;
  3579. if (numberToMove > 0)
  3580. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3581. new (insertPos) ElementType (newElement);
  3582. ++numUsed;
  3583. }
  3584. else
  3585. {
  3586. new (data.elements + numUsed++) ElementType (newElement);
  3587. }
  3588. }
  3589. /** Inserts multiple copies of an element into the array at a given position.
  3590. If the index is less than 0 or greater than the size of the array, the
  3591. element will be added to the end of the array.
  3592. Otherwise, it will be inserted into the array, moving all the later elements
  3593. along to make room.
  3594. @param indexToInsertAt the index at which the new element should be inserted
  3595. @param newElement the new object to add to the array
  3596. @param numberOfTimesToInsertIt how many copies of the value to insert
  3597. @see insert, add, addSorted, set
  3598. */
  3599. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  3600. int numberOfTimesToInsertIt)
  3601. {
  3602. if (numberOfTimesToInsertIt > 0)
  3603. {
  3604. const ScopedLockType lock (getLock());
  3605. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3606. ElementType* insertPos;
  3607. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  3608. {
  3609. insertPos = data.elements + indexToInsertAt;
  3610. const int numberToMove = numUsed - indexToInsertAt;
  3611. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3612. }
  3613. else
  3614. {
  3615. insertPos = data.elements + numUsed;
  3616. }
  3617. numUsed += numberOfTimesToInsertIt;
  3618. while (--numberOfTimesToInsertIt >= 0)
  3619. new (insertPos++) ElementType (newElement);
  3620. }
  3621. }
  3622. /** Inserts an array of values into this array at a given position.
  3623. If the index is less than 0 or greater than the size of the array, the
  3624. new elements will be added to the end of the array.
  3625. Otherwise, they will be inserted into the array, moving all the later elements
  3626. along to make room.
  3627. @param indexToInsertAt the index at which the first new element should be inserted
  3628. @param newElements the new values to add to the array
  3629. @param numberOfElements how many items are in the array
  3630. @see insert, add, addSorted, set
  3631. */
  3632. void insertArray (int indexToInsertAt,
  3633. const ElementType* newElements,
  3634. int numberOfElements)
  3635. {
  3636. if (numberOfElements > 0)
  3637. {
  3638. const ScopedLockType lock (getLock());
  3639. data.ensureAllocatedSize (numUsed + numberOfElements);
  3640. ElementType* insertPos;
  3641. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  3642. {
  3643. insertPos = data.elements + indexToInsertAt;
  3644. const int numberToMove = numUsed - indexToInsertAt;
  3645. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3646. }
  3647. else
  3648. {
  3649. insertPos = data.elements + numUsed;
  3650. }
  3651. numUsed += numberOfElements;
  3652. while (--numberOfElements >= 0)
  3653. new (insertPos++) ElementType (*newElements++);
  3654. }
  3655. }
  3656. /** Appends a new element at the end of the array as long as the array doesn't
  3657. already contain it.
  3658. If the array already contains an element that matches the one passed in, nothing
  3659. will be done.
  3660. @param newElement the new object to add to the array
  3661. */
  3662. void addIfNotAlreadyThere (ParameterType newElement)
  3663. {
  3664. const ScopedLockType lock (getLock());
  3665. if (! contains (newElement))
  3666. add (newElement);
  3667. }
  3668. /** Replaces an element with a new value.
  3669. If the index is less than zero, this method does nothing.
  3670. If the index is beyond the end of the array, the item is added to the end of the array.
  3671. @param indexToChange the index whose value you want to change
  3672. @param newValue the new value to set for this index.
  3673. @see add, insert
  3674. */
  3675. void set (const int indexToChange, ParameterType newValue)
  3676. {
  3677. jassert (indexToChange >= 0);
  3678. const ScopedLockType lock (getLock());
  3679. if (isPositiveAndBelow (indexToChange, numUsed))
  3680. {
  3681. data.elements [indexToChange] = newValue;
  3682. }
  3683. else if (indexToChange >= 0)
  3684. {
  3685. data.ensureAllocatedSize (numUsed + 1);
  3686. new (data.elements + numUsed++) ElementType (newValue);
  3687. }
  3688. }
  3689. /** Replaces an element with a new value without doing any bounds-checking.
  3690. This just sets a value directly in the array's internal storage, so you'd
  3691. better make sure it's in range!
  3692. @param indexToChange the index whose value you want to change
  3693. @param newValue the new value to set for this index.
  3694. @see set, getUnchecked
  3695. */
  3696. void setUnchecked (const int indexToChange, ParameterType newValue)
  3697. {
  3698. const ScopedLockType lock (getLock());
  3699. jassert (isPositiveAndBelow (indexToChange, numUsed));
  3700. data.elements [indexToChange] = newValue;
  3701. }
  3702. /** Adds elements from an array to the end of this array.
  3703. @param elementsToAdd the array of elements to add
  3704. @param numElementsToAdd how many elements are in this other array
  3705. @see add
  3706. */
  3707. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  3708. {
  3709. const ScopedLockType lock (getLock());
  3710. if (numElementsToAdd > 0)
  3711. {
  3712. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  3713. while (--numElementsToAdd >= 0)
  3714. {
  3715. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  3716. ++numUsed;
  3717. }
  3718. }
  3719. }
  3720. /** This swaps the contents of this array with those of another array.
  3721. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3722. because it just swaps their internal pointers.
  3723. */
  3724. void swapWithArray (Array& otherArray) throw()
  3725. {
  3726. const ScopedLockType lock1 (getLock());
  3727. const ScopedLockType lock2 (otherArray.getLock());
  3728. data.swapWith (otherArray.data);
  3729. swapVariables (numUsed, otherArray.numUsed);
  3730. }
  3731. /** Adds elements from another array to the end of this array.
  3732. @param arrayToAddFrom the array from which to copy the elements
  3733. @param startIndex the first element of the other array to start copying from
  3734. @param numElementsToAdd how many elements to add from the other array. If this
  3735. value is negative or greater than the number of available elements,
  3736. all available elements will be copied.
  3737. @see add
  3738. */
  3739. template <class OtherArrayType>
  3740. void addArray (const OtherArrayType& arrayToAddFrom,
  3741. int startIndex = 0,
  3742. int numElementsToAdd = -1)
  3743. {
  3744. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  3745. {
  3746. const ScopedLockType lock2 (getLock());
  3747. if (startIndex < 0)
  3748. {
  3749. jassertfalse;
  3750. startIndex = 0;
  3751. }
  3752. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3753. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3754. while (--numElementsToAdd >= 0)
  3755. add (arrayToAddFrom.getUnchecked (startIndex++));
  3756. }
  3757. }
  3758. /** Inserts a new element into the array, assuming that the array is sorted.
  3759. This will use a comparator to find the position at which the new element
  3760. should go. If the array isn't sorted, the behaviour of this
  3761. method will be unpredictable.
  3762. @param comparator the comparator to use to compare the elements - see the sort()
  3763. method for details about the form this object should take
  3764. @param newElement the new element to insert to the array
  3765. @see addUsingDefaultSort, add, sort
  3766. */
  3767. template <class ElementComparator>
  3768. void addSorted (ElementComparator& comparator, ParameterType newElement)
  3769. {
  3770. const ScopedLockType lock (getLock());
  3771. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  3772. }
  3773. /** Inserts a new element into the array, assuming that the array is sorted.
  3774. This will use the DefaultElementComparator class for sorting, so your ElementType
  3775. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  3776. method will be unpredictable.
  3777. @param newElement the new element to insert to the array
  3778. @see addSorted, sort
  3779. */
  3780. void addUsingDefaultSort (ParameterType newElement)
  3781. {
  3782. DefaultElementComparator <ElementType> comparator;
  3783. addSorted (comparator, newElement);
  3784. }
  3785. /** Finds the index of an element in the array, assuming that the array is sorted.
  3786. This will use a comparator to do a binary-chop to find the index of the given
  3787. element, if it exists. If the array isn't sorted, the behaviour of this
  3788. method will be unpredictable.
  3789. @param comparator the comparator to use to compare the elements - see the sort()
  3790. method for details about the form this object should take
  3791. @param elementToLookFor the element to search for
  3792. @returns the index of the element, or -1 if it's not found
  3793. @see addSorted, sort
  3794. */
  3795. template <class ElementComparator>
  3796. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  3797. {
  3798. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3799. // avoids getting warning messages about the parameter being unused
  3800. const ScopedLockType lock (getLock());
  3801. int start = 0;
  3802. int end = numUsed;
  3803. for (;;)
  3804. {
  3805. if (start >= end)
  3806. {
  3807. return -1;
  3808. }
  3809. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  3810. {
  3811. return start;
  3812. }
  3813. else
  3814. {
  3815. const int halfway = (start + end) >> 1;
  3816. if (halfway == start)
  3817. return -1;
  3818. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  3819. start = halfway;
  3820. else
  3821. end = halfway;
  3822. }
  3823. }
  3824. }
  3825. /** Removes an element from the array.
  3826. This will remove the element at a given index, and move back
  3827. all the subsequent elements to close the gap.
  3828. If the index passed in is out-of-range, nothing will happen.
  3829. @param indexToRemove the index of the element to remove
  3830. @returns the element that has been removed
  3831. @see removeValue, removeRange
  3832. */
  3833. ElementType remove (const int indexToRemove)
  3834. {
  3835. const ScopedLockType lock (getLock());
  3836. if (isPositiveAndBelow (indexToRemove, numUsed))
  3837. {
  3838. --numUsed;
  3839. ElementType* const e = data.elements + indexToRemove;
  3840. ElementType removed (*e);
  3841. e->~ElementType();
  3842. const int numberToShift = numUsed - indexToRemove;
  3843. if (numberToShift > 0)
  3844. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  3845. if ((numUsed << 1) < data.numAllocated)
  3846. minimiseStorageOverheads();
  3847. return removed;
  3848. }
  3849. else
  3850. {
  3851. return ElementType();
  3852. }
  3853. }
  3854. /** Removes an item from the array.
  3855. This will remove the first occurrence of the given element from the array.
  3856. If the item isn't found, no action is taken.
  3857. @param valueToRemove the object to try to remove
  3858. @see remove, removeRange
  3859. */
  3860. void removeValue (ParameterType valueToRemove)
  3861. {
  3862. const ScopedLockType lock (getLock());
  3863. ElementType* e = data.elements;
  3864. for (int i = numUsed; --i >= 0;)
  3865. {
  3866. if (valueToRemove == *e)
  3867. {
  3868. remove (static_cast <int> (e - data.elements.getData()));
  3869. break;
  3870. }
  3871. ++e;
  3872. }
  3873. }
  3874. /** Removes a range of elements from the array.
  3875. This will remove a set of elements, starting from the given index,
  3876. and move subsequent elements down to close the gap.
  3877. If the range extends beyond the bounds of the array, it will
  3878. be safely clipped to the size of the array.
  3879. @param startIndex the index of the first element to remove
  3880. @param numberToRemove how many elements should be removed
  3881. @see remove, removeValue
  3882. */
  3883. void removeRange (int startIndex, int numberToRemove)
  3884. {
  3885. const ScopedLockType lock (getLock());
  3886. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3887. startIndex = jlimit (0, numUsed, startIndex);
  3888. if (endIndex > startIndex)
  3889. {
  3890. ElementType* const e = data.elements + startIndex;
  3891. numberToRemove = endIndex - startIndex;
  3892. for (int i = 0; i < numberToRemove; ++i)
  3893. e[i].~ElementType();
  3894. const int numToShift = numUsed - endIndex;
  3895. if (numToShift > 0)
  3896. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  3897. numUsed -= numberToRemove;
  3898. if ((numUsed << 1) < data.numAllocated)
  3899. minimiseStorageOverheads();
  3900. }
  3901. }
  3902. /** Removes the last n elements from the array.
  3903. @param howManyToRemove how many elements to remove from the end of the array
  3904. @see remove, removeValue, removeRange
  3905. */
  3906. void removeLast (int howManyToRemove = 1)
  3907. {
  3908. const ScopedLockType lock (getLock());
  3909. if (howManyToRemove > numUsed)
  3910. howManyToRemove = numUsed;
  3911. for (int i = 1; i <= howManyToRemove; ++i)
  3912. data.elements [numUsed - i].~ElementType();
  3913. numUsed -= howManyToRemove;
  3914. if ((numUsed << 1) < data.numAllocated)
  3915. minimiseStorageOverheads();
  3916. }
  3917. /** Removes any elements which are also in another array.
  3918. @param otherArray the other array in which to look for elements to remove
  3919. @see removeValuesNotIn, remove, removeValue, removeRange
  3920. */
  3921. template <class OtherArrayType>
  3922. void removeValuesIn (const OtherArrayType& otherArray)
  3923. {
  3924. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3925. const ScopedLockType lock2 (getLock());
  3926. if (this == &otherArray)
  3927. {
  3928. clear();
  3929. }
  3930. else
  3931. {
  3932. if (otherArray.size() > 0)
  3933. {
  3934. for (int i = numUsed; --i >= 0;)
  3935. if (otherArray.contains (data.elements [i]))
  3936. remove (i);
  3937. }
  3938. }
  3939. }
  3940. /** Removes any elements which are not found in another array.
  3941. Only elements which occur in this other array will be retained.
  3942. @param otherArray the array in which to look for elements NOT to remove
  3943. @see removeValuesIn, remove, removeValue, removeRange
  3944. */
  3945. template <class OtherArrayType>
  3946. void removeValuesNotIn (const OtherArrayType& otherArray)
  3947. {
  3948. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3949. const ScopedLockType lock2 (getLock());
  3950. if (this != &otherArray)
  3951. {
  3952. if (otherArray.size() <= 0)
  3953. {
  3954. clear();
  3955. }
  3956. else
  3957. {
  3958. for (int i = numUsed; --i >= 0;)
  3959. if (! otherArray.contains (data.elements [i]))
  3960. remove (i);
  3961. }
  3962. }
  3963. }
  3964. /** Swaps over two elements in the array.
  3965. This swaps over the elements found at the two indexes passed in.
  3966. If either index is out-of-range, this method will do nothing.
  3967. @param index1 index of one of the elements to swap
  3968. @param index2 index of the other element to swap
  3969. */
  3970. void swap (const int index1,
  3971. const int index2)
  3972. {
  3973. const ScopedLockType lock (getLock());
  3974. if (isPositiveAndBelow (index1, numUsed)
  3975. && isPositiveAndBelow (index2, numUsed))
  3976. {
  3977. swapVariables (data.elements [index1],
  3978. data.elements [index2]);
  3979. }
  3980. }
  3981. /** Moves one of the values to a different position.
  3982. This will move the value to a specified index, shuffling along
  3983. any intervening elements as required.
  3984. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3985. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3986. @param currentIndex the index of the value to be moved. If this isn't a
  3987. valid index, then nothing will be done
  3988. @param newIndex the index at which you'd like this value to end up. If this
  3989. is less than zero, the value will be moved to the end
  3990. of the array
  3991. */
  3992. void move (const int currentIndex, int newIndex) throw()
  3993. {
  3994. if (currentIndex != newIndex)
  3995. {
  3996. const ScopedLockType lock (getLock());
  3997. if (isPositiveAndBelow (currentIndex, numUsed))
  3998. {
  3999. if (! isPositiveAndBelow (newIndex, numUsed))
  4000. newIndex = numUsed - 1;
  4001. char tempCopy [sizeof (ElementType)];
  4002. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  4003. if (newIndex > currentIndex)
  4004. {
  4005. memmove (data.elements + currentIndex,
  4006. data.elements + currentIndex + 1,
  4007. (newIndex - currentIndex) * sizeof (ElementType));
  4008. }
  4009. else
  4010. {
  4011. memmove (data.elements + newIndex + 1,
  4012. data.elements + newIndex,
  4013. (currentIndex - newIndex) * sizeof (ElementType));
  4014. }
  4015. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  4016. }
  4017. }
  4018. }
  4019. /** Reduces the amount of storage being used by the array.
  4020. Arrays typically allocate slightly more storage than they need, and after
  4021. removing elements, they may have quite a lot of unused space allocated.
  4022. This method will reduce the amount of allocated storage to a minimum.
  4023. */
  4024. void minimiseStorageOverheads()
  4025. {
  4026. const ScopedLockType lock (getLock());
  4027. data.shrinkToNoMoreThan (numUsed);
  4028. }
  4029. /** Increases the array's internal storage to hold a minimum number of elements.
  4030. Calling this before adding a large known number of elements means that
  4031. the array won't have to keep dynamically resizing itself as the elements
  4032. are added, and it'll therefore be more efficient.
  4033. */
  4034. void ensureStorageAllocated (const int minNumElements)
  4035. {
  4036. const ScopedLockType lock (getLock());
  4037. data.ensureAllocatedSize (minNumElements);
  4038. }
  4039. /** Sorts the elements in the array.
  4040. This will use a comparator object to sort the elements into order. The object
  4041. passed must have a method of the form:
  4042. @code
  4043. int compareElements (ElementType first, ElementType second);
  4044. @endcode
  4045. ..and this method must return:
  4046. - a value of < 0 if the first comes before the second
  4047. - a value of 0 if the two objects are equivalent
  4048. - a value of > 0 if the second comes before the first
  4049. To improve performance, the compareElements() method can be declared as static or const.
  4050. @param comparator the comparator to use for comparing elements.
  4051. @param retainOrderOfEquivalentItems if this is true, then items
  4052. which the comparator says are equivalent will be
  4053. kept in the order in which they currently appear
  4054. in the array. This is slower to perform, but may
  4055. be important in some cases. If it's false, a faster
  4056. algorithm is used, but equivalent elements may be
  4057. rearranged.
  4058. @see addSorted, indexOfSorted, sortArray
  4059. */
  4060. template <class ElementComparator>
  4061. void sort (ElementComparator& comparator,
  4062. const bool retainOrderOfEquivalentItems = false) const
  4063. {
  4064. const ScopedLockType lock (getLock());
  4065. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4066. // avoids getting warning messages about the parameter being unused
  4067. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  4068. }
  4069. /** Returns the CriticalSection that locks this array.
  4070. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  4071. an object of ScopedLockType as an RAII lock for it.
  4072. */
  4073. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  4074. /** Returns the type of scoped lock to use for locking this array */
  4075. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  4076. private:
  4077. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  4078. int numUsed;
  4079. };
  4080. #endif // __JUCE_ARRAY_JUCEHEADER__
  4081. /*** End of inlined file: juce_Array.h ***/
  4082. #endif
  4083. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4084. #endif
  4085. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4086. /*** Start of inlined file: juce_DynamicObject.h ***/
  4087. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4088. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4089. /*** Start of inlined file: juce_NamedValueSet.h ***/
  4090. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  4091. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  4092. /*** Start of inlined file: juce_Variant.h ***/
  4093. #ifndef __JUCE_VARIANT_JUCEHEADER__
  4094. #define __JUCE_VARIANT_JUCEHEADER__
  4095. /*** Start of inlined file: juce_Identifier.h ***/
  4096. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  4097. #define __JUCE_IDENTIFIER_JUCEHEADER__
  4098. /*** Start of inlined file: juce_StringPool.h ***/
  4099. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  4100. #define __JUCE_STRINGPOOL_JUCEHEADER__
  4101. /**
  4102. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  4103. comparison speed when dealing with many duplicate strings.
  4104. When you add a string to a pool using getPooledString, it'll return a character
  4105. array containing the same string. This array is owned by the pool, and the same array
  4106. is returned every time a matching string is asked for. This means that it's trivial to
  4107. compare two pooled strings for equality, as you can simply compare their pointers. It
  4108. also cuts down on storage if you're using many copies of the same string.
  4109. */
  4110. class JUCE_API StringPool
  4111. {
  4112. public:
  4113. /** Creates an empty pool. */
  4114. StringPool() throw();
  4115. /** Destructor */
  4116. ~StringPool();
  4117. /** Returns a pointer to a copy of the string that is passed in.
  4118. The pool will always return the same pointer when asked for a string that matches it.
  4119. The pool will own all the pointers that it returns, deleting them when the pool itself
  4120. is deleted.
  4121. */
  4122. const juce_wchar* getPooledString (const String& original);
  4123. /** Returns a pointer to a copy of the string that is passed in.
  4124. The pool will always return the same pointer when asked for a string that matches it.
  4125. The pool will own all the pointers that it returns, deleting them when the pool itself
  4126. is deleted.
  4127. */
  4128. const juce_wchar* getPooledString (const char* original);
  4129. /** Returns a pointer to a copy of the string that is passed in.
  4130. The pool will always return the same pointer when asked for a string that matches it.
  4131. The pool will own all the pointers that it returns, deleting them when the pool itself
  4132. is deleted.
  4133. */
  4134. const juce_wchar* getPooledString (const juce_wchar* original);
  4135. /** Returns the number of strings in the pool. */
  4136. int size() const throw();
  4137. /** Returns one of the strings in the pool, by index. */
  4138. const juce_wchar* operator[] (int index) const throw();
  4139. private:
  4140. Array <String> strings;
  4141. };
  4142. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  4143. /*** End of inlined file: juce_StringPool.h ***/
  4144. /**
  4145. Represents a string identifier, designed for accessing properties by name.
  4146. Identifier objects are very light and fast to copy, but slower to initialise
  4147. from a string, so it's much faster to keep a static identifier object to refer
  4148. to frequently-used names, rather than constructing them each time you need it.
  4149. @see NamedPropertySet, ValueTree
  4150. */
  4151. class JUCE_API Identifier
  4152. {
  4153. public:
  4154. /** Creates a null identifier. */
  4155. Identifier() throw();
  4156. /** Creates an identifier with a specified name.
  4157. Because this name may need to be used in contexts such as script variables or XML
  4158. tags, it must only contain ascii letters and digits, or the underscore character.
  4159. */
  4160. Identifier (const char* name);
  4161. /** Creates an identifier with a specified name.
  4162. Because this name may need to be used in contexts such as script variables or XML
  4163. tags, it must only contain ascii letters and digits, or the underscore character.
  4164. */
  4165. Identifier (const String& name);
  4166. /** Creates a copy of another identifier. */
  4167. Identifier (const Identifier& other) throw();
  4168. /** Creates a copy of another identifier. */
  4169. Identifier& operator= (const Identifier& other) throw();
  4170. /** Destructor */
  4171. ~Identifier();
  4172. /** Compares two identifiers. This is a very fast operation. */
  4173. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  4174. /** Compares two identifiers. This is a very fast operation. */
  4175. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  4176. /** Returns this identifier as a string. */
  4177. const String toString() const { return name; }
  4178. /** Returns this identifier's raw string pointer. */
  4179. operator const juce_wchar*() const throw() { return name; }
  4180. private:
  4181. const juce_wchar* name;
  4182. static StringPool& getPool();
  4183. };
  4184. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  4185. /*** End of inlined file: juce_Identifier.h ***/
  4186. /*** Start of inlined file: juce_OutputStream.h ***/
  4187. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4188. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4189. /*** Start of inlined file: juce_NewLine.h ***/
  4190. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  4191. #define __JUCE_NEWLINE_JUCEHEADER__
  4192. /** This class is used for represent a new-line character sequence.
  4193. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  4194. @code
  4195. myOutputStream << "Hello World" << newLine << newLine;
  4196. @endcode
  4197. The exact character sequence that will be used for the new-line can be set and
  4198. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  4199. */
  4200. class JUCE_API NewLine
  4201. {
  4202. public:
  4203. /** Returns the default new-line sequence that the library uses.
  4204. @see OutputStream::setNewLineString()
  4205. */
  4206. static const char* getDefault() throw() { return "\r\n"; }
  4207. /** Returns the default new-line sequence that the library uses.
  4208. @see getDefault()
  4209. */
  4210. operator const String() const { return getDefault(); }
  4211. };
  4212. /** An predefined object representing a new-line, which can be written to a string or stream.
  4213. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  4214. @code
  4215. myOutputStream << "Hello World" << newLine << newLine;
  4216. @endcode
  4217. */
  4218. extern NewLine newLine;
  4219. /** Writes a new-line sequence to a string.
  4220. You can use the predefined object 'newLine' to invoke this, e.g.
  4221. @code
  4222. myString << "Hello World" << newLine << newLine;
  4223. @endcode
  4224. */
  4225. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  4226. #endif // __JUCE_NEWLINE_JUCEHEADER__
  4227. /*** End of inlined file: juce_NewLine.h ***/
  4228. /*** Start of inlined file: juce_InputStream.h ***/
  4229. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  4230. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  4231. /*** Start of inlined file: juce_MemoryBlock.h ***/
  4232. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4233. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4234. /**
  4235. A class to hold a resizable block of raw data.
  4236. */
  4237. class JUCE_API MemoryBlock
  4238. {
  4239. public:
  4240. /** Create an uninitialised block with 0 size. */
  4241. MemoryBlock() throw();
  4242. /** Creates a memory block with a given initial size.
  4243. @param initialSize the size of block to create
  4244. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4245. */
  4246. MemoryBlock (const size_t initialSize,
  4247. bool initialiseToZero = false);
  4248. /** Creates a copy of another memory block. */
  4249. MemoryBlock (const MemoryBlock& other);
  4250. /** Creates a memory block using a copy of a block of data.
  4251. @param dataToInitialiseFrom some data to copy into this block
  4252. @param sizeInBytes how much space to use
  4253. */
  4254. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  4255. /** Destructor. */
  4256. ~MemoryBlock() throw();
  4257. /** Copies another memory block onto this one.
  4258. This block will be resized and copied to exactly match the other one.
  4259. */
  4260. MemoryBlock& operator= (const MemoryBlock& other);
  4261. /** Compares two memory blocks.
  4262. @returns true only if the two blocks are the same size and have identical contents.
  4263. */
  4264. bool operator== (const MemoryBlock& other) const throw();
  4265. /** Compares two memory blocks.
  4266. @returns true if the two blocks are different sizes or have different contents.
  4267. */
  4268. bool operator!= (const MemoryBlock& other) const throw();
  4269. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  4270. */
  4271. bool matches (const void* data, size_t dataSize) const throw();
  4272. /** Returns a void pointer to the data.
  4273. Note that the pointer returned will probably become invalid when the
  4274. block is resized.
  4275. */
  4276. void* getData() const throw() { return data; }
  4277. /** Returns a byte from the memory block.
  4278. This returns a reference, so you can also use it to set a byte.
  4279. */
  4280. template <typename Type>
  4281. char& operator[] (const Type offset) const throw() { return data [offset]; }
  4282. /** Returns the block's current allocated size, in bytes. */
  4283. size_t getSize() const throw() { return size; }
  4284. /** Resizes the memory block.
  4285. This will try to keep as much of the block's current content as it can,
  4286. and can optionally be made to clear any new space that gets allocated at
  4287. the end of the block.
  4288. @param newSize the new desired size for the block
  4289. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4290. whether to clear the new section or just leave it
  4291. uninitialised
  4292. @see ensureSize
  4293. */
  4294. void setSize (const size_t newSize,
  4295. bool initialiseNewSpaceToZero = false);
  4296. /** Increases the block's size only if it's smaller than a given size.
  4297. @param minimumSize if the block is already bigger than this size, no action
  4298. will be taken; otherwise it will be increased to this size
  4299. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4300. whether to clear the new section or just leave it
  4301. uninitialised
  4302. @see setSize
  4303. */
  4304. void ensureSize (const size_t minimumSize,
  4305. bool initialiseNewSpaceToZero = false);
  4306. /** Fills the entire memory block with a repeated byte value.
  4307. This is handy for clearing a block of memory to zero.
  4308. */
  4309. void fillWith (uint8 valueToUse) throw();
  4310. /** Adds another block of data to the end of this one.
  4311. This block's size will be increased accordingly.
  4312. */
  4313. void append (const void* data, size_t numBytes);
  4314. /** Exchanges the contents of this and another memory block.
  4315. No actual copying is required for this, so it's very fast.
  4316. */
  4317. void swapWith (MemoryBlock& other) throw();
  4318. /** Copies data into this MemoryBlock from a memory address.
  4319. @param srcData the memory location of the data to copy into this block
  4320. @param destinationOffset the offset in this block at which the data being copied should begin
  4321. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4322. it will be clipped so not to do anything nasty)
  4323. */
  4324. void copyFrom (const void* srcData,
  4325. int destinationOffset,
  4326. size_t numBytes) throw();
  4327. /** Copies data from this MemoryBlock to a memory address.
  4328. @param destData the memory location to write to
  4329. @param sourceOffset the offset within this block from which the copied data will be read
  4330. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4331. zeros will be used for that portion of the data)
  4332. */
  4333. void copyTo (void* destData,
  4334. int sourceOffset,
  4335. size_t numBytes) const throw();
  4336. /** Chops out a section of the block.
  4337. This will remove a section of the memory block and close the gap around it,
  4338. shifting any subsequent data downwards and reducing the size of the block.
  4339. If the range specified goes beyond the size of the block, it will be clipped.
  4340. */
  4341. void removeSection (size_t startByte, size_t numBytesToRemove);
  4342. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4343. characters in the system's default encoding. */
  4344. const String toString() const;
  4345. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4346. The block will be resized to the number of valid bytes read from the string.
  4347. Non-hex characters in the string will be ignored.
  4348. @see String::toHexString()
  4349. */
  4350. void loadFromHexString (const String& sourceHexString);
  4351. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4352. void setBitRange (size_t bitRangeStart,
  4353. size_t numBits,
  4354. int binaryNumberToApply) throw();
  4355. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4356. int getBitRange (size_t bitRangeStart,
  4357. size_t numBitsToRead) const throw();
  4358. /** Returns a string of characters that represent the binary contents of this block.
  4359. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4360. of simple non-extended characters, e.g. for storage in XML.
  4361. @see fromBase64Encoding
  4362. */
  4363. const String toBase64Encoding() const;
  4364. /** Takes a string of encoded characters and turns it into binary data.
  4365. The string passed in must have been created by to64BitEncoding(), and this
  4366. block will be resized to recreate the original data block.
  4367. @see toBase64Encoding
  4368. */
  4369. bool fromBase64Encoding (const String& encodedString);
  4370. private:
  4371. HeapBlock <char> data;
  4372. size_t size;
  4373. static const char* const encodingTable;
  4374. JUCE_LEAK_DETECTOR (MemoryBlock);
  4375. };
  4376. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4377. /*** End of inlined file: juce_MemoryBlock.h ***/
  4378. /** The base class for streams that read data.
  4379. Input and output streams are used throughout the library - subclasses can override
  4380. some or all of the virtual functions to implement their behaviour.
  4381. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  4382. */
  4383. class JUCE_API InputStream
  4384. {
  4385. public:
  4386. /** Destructor. */
  4387. virtual ~InputStream() {}
  4388. /** Returns the total number of bytes available for reading in this stream.
  4389. Note that this is the number of bytes available from the start of the
  4390. stream, not from the current position.
  4391. If the size of the stream isn't actually known, this may return -1.
  4392. */
  4393. virtual int64 getTotalLength() = 0;
  4394. /** Returns true if the stream has no more data to read. */
  4395. virtual bool isExhausted() = 0;
  4396. /** Reads a set of bytes from the stream into a memory buffer.
  4397. This is the only read method that subclasses actually need to implement, as the
  4398. InputStream base class implements the other read methods in terms of this one (although
  4399. it's often more efficient for subclasses to implement them directly).
  4400. @param destBuffer the destination buffer for the data
  4401. @param maxBytesToRead the maximum number of bytes to read - make sure the
  4402. memory block passed in is big enough to contain this
  4403. many bytes.
  4404. @returns the actual number of bytes that were read, which may be less than
  4405. maxBytesToRead if the stream is exhausted before it gets that far
  4406. */
  4407. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  4408. /** Reads a byte from the stream.
  4409. If the stream is exhausted, this will return zero.
  4410. @see OutputStream::writeByte
  4411. */
  4412. virtual char readByte();
  4413. /** Reads a boolean from the stream.
  4414. The bool is encoded as a single byte - 1 for true, 0 for false.
  4415. If the stream is exhausted, this will return false.
  4416. @see OutputStream::writeBool
  4417. */
  4418. virtual bool readBool();
  4419. /** Reads two bytes from the stream as a little-endian 16-bit value.
  4420. If the next two bytes read are byte1 and byte2, this returns
  4421. (byte1 | (byte2 << 8)).
  4422. If the stream is exhausted partway through reading the bytes, this will return zero.
  4423. @see OutputStream::writeShort, readShortBigEndian
  4424. */
  4425. virtual short readShort();
  4426. /** Reads two bytes from the stream as a little-endian 16-bit value.
  4427. If the next two bytes read are byte1 and byte2, this returns
  4428. (byte2 | (byte1 << 8)).
  4429. If the stream is exhausted partway through reading the bytes, this will return zero.
  4430. @see OutputStream::writeShortBigEndian, readShort
  4431. */
  4432. virtual short readShortBigEndian();
  4433. /** Reads four bytes from the stream as a little-endian 32-bit value.
  4434. If the next four bytes are byte1 to byte4, this returns
  4435. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  4436. If the stream is exhausted partway through reading the bytes, this will return zero.
  4437. @see OutputStream::writeInt, readIntBigEndian
  4438. */
  4439. virtual int readInt();
  4440. /** Reads four bytes from the stream as a big-endian 32-bit value.
  4441. If the next four bytes are byte1 to byte4, this returns
  4442. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  4443. If the stream is exhausted partway through reading the bytes, this will return zero.
  4444. @see OutputStream::writeIntBigEndian, readInt
  4445. */
  4446. virtual int readIntBigEndian();
  4447. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  4448. If the next eight bytes are byte1 to byte8, this returns
  4449. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  4450. If the stream is exhausted partway through reading the bytes, this will return zero.
  4451. @see OutputStream::writeInt64, readInt64BigEndian
  4452. */
  4453. virtual int64 readInt64();
  4454. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  4455. If the next eight bytes are byte1 to byte8, this returns
  4456. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  4457. If the stream is exhausted partway through reading the bytes, this will return zero.
  4458. @see OutputStream::writeInt64BigEndian, readInt64
  4459. */
  4460. virtual int64 readInt64BigEndian();
  4461. /** Reads four bytes as a 32-bit floating point value.
  4462. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  4463. If the stream is exhausted partway through reading the bytes, this will return zero.
  4464. @see OutputStream::writeFloat, readDouble
  4465. */
  4466. virtual float readFloat();
  4467. /** Reads four bytes as a 32-bit floating point value.
  4468. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  4469. If the stream is exhausted partway through reading the bytes, this will return zero.
  4470. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  4471. */
  4472. virtual float readFloatBigEndian();
  4473. /** Reads eight bytes as a 64-bit floating point value.
  4474. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  4475. If the stream is exhausted partway through reading the bytes, this will return zero.
  4476. @see OutputStream::writeDouble, readFloat
  4477. */
  4478. virtual double readDouble();
  4479. /** Reads eight bytes as a 64-bit floating point value.
  4480. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  4481. If the stream is exhausted partway through reading the bytes, this will return zero.
  4482. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  4483. */
  4484. virtual double readDoubleBigEndian();
  4485. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  4486. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  4487. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4488. @see OutputStream::writeCompressedInt()
  4489. */
  4490. virtual int readCompressedInt();
  4491. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  4492. This will read up to the next "\n" or "\r\n" or end-of-stream.
  4493. After this call, the stream's position will be left pointing to the next character
  4494. following the line-feed, but the linefeeds aren't included in the string that
  4495. is returned.
  4496. */
  4497. virtual const String readNextLine();
  4498. /** Reads a zero-terminated UTF8 string from the stream.
  4499. This will read characters from the stream until it hits a zero character or
  4500. end-of-stream.
  4501. @see OutputStream::writeString, readEntireStreamAsString
  4502. */
  4503. virtual const String readString();
  4504. /** Tries to read the whole stream and turn it into a string.
  4505. This will read from the stream's current position until the end-of-stream, and
  4506. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  4507. */
  4508. virtual const String readEntireStreamAsString();
  4509. /** Reads from the stream and appends the data to a MemoryBlock.
  4510. @param destBlock the block to append the data onto
  4511. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  4512. of bytes that will be read - if it's negative, data
  4513. will be read until the stream is exhausted.
  4514. @returns the number of bytes that were added to the memory block
  4515. */
  4516. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  4517. int maxNumBytesToRead = -1);
  4518. /** Returns the offset of the next byte that will be read from the stream.
  4519. @see setPosition
  4520. */
  4521. virtual int64 getPosition() = 0;
  4522. /** Tries to move the current read position of the stream.
  4523. The position is an absolute number of bytes from the stream's start.
  4524. Some streams might not be able to do this, in which case they should do
  4525. nothing and return false. Others might be able to manage it by resetting
  4526. themselves and skipping to the correct position, although this is
  4527. obviously a bit slow.
  4528. @returns true if the stream manages to reposition itself correctly
  4529. @see getPosition
  4530. */
  4531. virtual bool setPosition (int64 newPosition) = 0;
  4532. /** Reads and discards a number of bytes from the stream.
  4533. Some input streams might implement this efficiently, but the base
  4534. class will just keep reading data until the requisite number of bytes
  4535. have been done.
  4536. */
  4537. virtual void skipNextBytes (int64 numBytesToSkip);
  4538. protected:
  4539. InputStream() throw() {}
  4540. private:
  4541. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  4542. };
  4543. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  4544. /*** End of inlined file: juce_InputStream.h ***/
  4545. class File;
  4546. /**
  4547. The base class for streams that write data to some kind of destination.
  4548. Input and output streams are used throughout the library - subclasses can override
  4549. some or all of the virtual functions to implement their behaviour.
  4550. @see InputStream, MemoryOutputStream, FileOutputStream
  4551. */
  4552. class JUCE_API OutputStream
  4553. {
  4554. protected:
  4555. OutputStream();
  4556. public:
  4557. /** Destructor.
  4558. Some subclasses might want to do things like call flush() during their
  4559. destructors.
  4560. */
  4561. virtual ~OutputStream();
  4562. /** If the stream is using a buffer, this will ensure it gets written
  4563. out to the destination. */
  4564. virtual void flush() = 0;
  4565. /** Tries to move the stream's output position.
  4566. Not all streams will be able to seek to a new position - this will return
  4567. false if it fails to work.
  4568. @see getPosition
  4569. */
  4570. virtual bool setPosition (int64 newPosition) = 0;
  4571. /** Returns the stream's current position.
  4572. @see setPosition
  4573. */
  4574. virtual int64 getPosition() = 0;
  4575. /** Writes a block of data to the stream.
  4576. When creating a subclass of OutputStream, this is the only write method
  4577. that needs to be overloaded - the base class has methods for writing other
  4578. types of data which use this to do the work.
  4579. @returns false if the write operation fails for some reason
  4580. */
  4581. virtual bool write (const void* dataToWrite,
  4582. int howManyBytes) = 0;
  4583. /** Writes a single byte to the stream.
  4584. @see InputStream::readByte
  4585. */
  4586. virtual void writeByte (char byte);
  4587. /** Writes a boolean to the stream as a single byte.
  4588. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  4589. @see InputStream::readBool
  4590. */
  4591. virtual void writeBool (bool boolValue);
  4592. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  4593. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  4594. @see InputStream::readShort
  4595. */
  4596. virtual void writeShort (short value);
  4597. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  4598. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  4599. @see InputStream::readShortBigEndian
  4600. */
  4601. virtual void writeShortBigEndian (short value);
  4602. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  4603. @see InputStream::readInt
  4604. */
  4605. virtual void writeInt (int value);
  4606. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  4607. @see InputStream::readIntBigEndian
  4608. */
  4609. virtual void writeIntBigEndian (int value);
  4610. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  4611. @see InputStream::readInt64
  4612. */
  4613. virtual void writeInt64 (int64 value);
  4614. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  4615. @see InputStream::readInt64BigEndian
  4616. */
  4617. virtual void writeInt64BigEndian (int64 value);
  4618. /** Writes a 32-bit floating point value to the stream in a binary format.
  4619. The binary 32-bit encoding of the float is written as a little-endian int.
  4620. @see InputStream::readFloat
  4621. */
  4622. virtual void writeFloat (float value);
  4623. /** Writes a 32-bit floating point value to the stream in a binary format.
  4624. The binary 32-bit encoding of the float is written as a big-endian int.
  4625. @see InputStream::readFloatBigEndian
  4626. */
  4627. virtual void writeFloatBigEndian (float value);
  4628. /** Writes a 64-bit floating point value to the stream in a binary format.
  4629. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  4630. @see InputStream::readDouble
  4631. */
  4632. virtual void writeDouble (double value);
  4633. /** Writes a 64-bit floating point value to the stream in a binary format.
  4634. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  4635. @see InputStream::readDoubleBigEndian
  4636. */
  4637. virtual void writeDoubleBigEndian (double value);
  4638. /** Writes a condensed binary encoding of a 32-bit integer.
  4639. If you're storing a lot of integers which are unlikely to have very large values,
  4640. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  4641. under 0xffff only 3 bytes, etc.
  4642. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4643. @see InputStream::readCompressedInt
  4644. */
  4645. virtual void writeCompressedInt (int value);
  4646. /** Stores a string in the stream in a binary format.
  4647. This isn't the method to use if you're trying to append text to the end of a
  4648. text-file! It's intended for storing a string so that it can be retrieved later
  4649. by InputStream::readString().
  4650. It writes the string to the stream as UTF8, including the null termination character.
  4651. For appending text to a file, instead use writeText, or operator<<
  4652. @see InputStream::readString, writeText, operator<<
  4653. */
  4654. virtual void writeString (const String& text);
  4655. /** Writes a string of text to the stream.
  4656. It can either write it as UTF8 characters or as unicode, and
  4657. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  4658. should only be done at the start of a file).
  4659. The method also replaces '\\n' characters in the text with '\\r\\n'.
  4660. */
  4661. virtual void writeText (const String& text,
  4662. bool asUnicode,
  4663. bool writeUnicodeHeaderBytes);
  4664. /** Reads data from an input stream and writes it to this stream.
  4665. @param source the stream to read from
  4666. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  4667. less than zero, it will keep reading until the input
  4668. is exhausted)
  4669. */
  4670. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  4671. /** Sets the string that will be written to the stream when the writeNewLine()
  4672. method is called.
  4673. By default this will be set the the value of NewLine::getDefault().
  4674. */
  4675. void setNewLineString (const String& newLineString);
  4676. /** Returns the current new-line string that was set by setNewLineString(). */
  4677. const String& getNewLineString() const throw() { return newLineString; }
  4678. private:
  4679. String newLineString;
  4680. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  4681. };
  4682. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4683. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  4684. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4685. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  4686. /** Writes a character to a stream. */
  4687. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  4688. /** Writes a null-terminated text string to a stream. */
  4689. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  4690. /** Writes a block of data from a MemoryBlock to a stream. */
  4691. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  4692. /** Writes the contents of a file to a stream. */
  4693. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  4694. /** Writes a new-line to a stream.
  4695. You can use the predefined symbol 'newLine' to invoke this, e.g.
  4696. @code
  4697. myOutputStream << "Hello World" << newLine << newLine;
  4698. @endcode
  4699. @see OutputStream::setNewLineString
  4700. */
  4701. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  4702. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4703. /*** End of inlined file: juce_OutputStream.h ***/
  4704. #ifndef DOXYGEN
  4705. class JUCE_API DynamicObject;
  4706. #endif
  4707. /**
  4708. A variant class, that can be used to hold a range of primitive values.
  4709. A var object can hold a range of simple primitive values, strings, or
  4710. a reference-counted pointer to a DynamicObject. The var class is intended
  4711. to act like the values used in dynamic scripting languages.
  4712. @see DynamicObject
  4713. */
  4714. class JUCE_API var
  4715. {
  4716. public:
  4717. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  4718. typedef Identifier identifier;
  4719. /** Creates a void variant. */
  4720. var() throw();
  4721. /** Destructor. */
  4722. ~var() throw();
  4723. /** A static var object that can be used where you need an empty variant object. */
  4724. static const var null;
  4725. var (const var& valueToCopy);
  4726. var (int value) throw();
  4727. var (bool value) throw();
  4728. var (double value) throw();
  4729. var (const char* value);
  4730. var (const juce_wchar* value);
  4731. var (const String& value);
  4732. var (DynamicObject* object);
  4733. var (MethodFunction method) throw();
  4734. var& operator= (const var& valueToCopy);
  4735. var& operator= (int value);
  4736. var& operator= (bool value);
  4737. var& operator= (double value);
  4738. var& operator= (const char* value);
  4739. var& operator= (const juce_wchar* value);
  4740. var& operator= (const String& value);
  4741. var& operator= (DynamicObject* object);
  4742. var& operator= (MethodFunction method);
  4743. void swapWith (var& other) throw();
  4744. operator int() const;
  4745. operator bool() const;
  4746. operator float() const;
  4747. operator double() const;
  4748. operator const String() const;
  4749. const String toString() const;
  4750. DynamicObject* getObject() const;
  4751. bool isVoid() const throw();
  4752. bool isInt() const throw();
  4753. bool isBool() const throw();
  4754. bool isDouble() const throw();
  4755. bool isString() const throw();
  4756. bool isObject() const throw();
  4757. bool isMethod() const throw();
  4758. /** Writes a binary representation of this value to a stream.
  4759. The data can be read back later using readFromStream().
  4760. */
  4761. void writeToStream (OutputStream& output) const;
  4762. /** Reads back a stored binary representation of a value.
  4763. The data in the stream must have been written using writeToStream(), or this
  4764. will have unpredictable results.
  4765. */
  4766. static const var readFromStream (InputStream& input);
  4767. /** If this variant is an object, this returns one of its properties. */
  4768. const var operator[] (const Identifier& propertyName) const;
  4769. /** If this variant is an object, this invokes one of its methods with no arguments. */
  4770. const var call (const Identifier& method) const;
  4771. /** If this variant is an object, this invokes one of its methods with one argument. */
  4772. const var call (const Identifier& method, const var& arg1) const;
  4773. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  4774. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  4775. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  4776. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  4777. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  4778. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  4779. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  4780. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  4781. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  4782. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  4783. /** If this variant is a method pointer, this invokes it on a target object. */
  4784. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  4785. /** Returns true if this var has the same value as the one supplied. */
  4786. bool equals (const var& other) const throw();
  4787. private:
  4788. class VariantType;
  4789. friend class VariantType;
  4790. class VariantType_Void;
  4791. friend class VariantType_Void;
  4792. class VariantType_Int;
  4793. friend class VariantType_Int;
  4794. class VariantType_Double;
  4795. friend class VariantType_Double;
  4796. class VariantType_Float;
  4797. friend class VariantType_Float;
  4798. class VariantType_Bool;
  4799. friend class VariantType_Bool;
  4800. class VariantType_String;
  4801. friend class VariantType_String;
  4802. class VariantType_Object;
  4803. friend class VariantType_Object;
  4804. class VariantType_Method;
  4805. friend class VariantType_Method;
  4806. union ValueUnion
  4807. {
  4808. int intValue;
  4809. bool boolValue;
  4810. double doubleValue;
  4811. String* stringValue;
  4812. DynamicObject* objectValue;
  4813. MethodFunction methodValue;
  4814. };
  4815. const VariantType* type;
  4816. ValueUnion value;
  4817. };
  4818. bool operator== (const var& v1, const var& v2) throw();
  4819. bool operator!= (const var& v1, const var& v2) throw();
  4820. bool operator== (const var& v1, const String& v2) throw();
  4821. bool operator!= (const var& v1, const String& v2) throw();
  4822. #endif // __JUCE_VARIANT_JUCEHEADER__
  4823. /*** End of inlined file: juce_Variant.h ***/
  4824. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  4825. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  4826. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  4827. /**
  4828. Helps to manipulate singly-linked lists of objects.
  4829. For objects that are designed to contain a pointer to the subsequent item in the
  4830. list, this class contains methods to deal with the list. To use it, the ObjectType
  4831. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  4832. @code
  4833. struct MyObject
  4834. {
  4835. int x, y, z;
  4836. // A linkable object must contain a member with this name and type, which must be
  4837. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  4838. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  4839. LinkedListPointer<MyObject> nextListItem;
  4840. };
  4841. LinkedListPointer<MyObject> myList;
  4842. myList.append (new MyObject());
  4843. myList.append (new MyObject());
  4844. int numItems = myList.size(); // returns 2
  4845. MyObject* lastInList = myList.getLast();
  4846. @endcode
  4847. */
  4848. template <class ObjectType>
  4849. class LinkedListPointer
  4850. {
  4851. public:
  4852. /** Creates a null pointer to an empty list. */
  4853. LinkedListPointer() throw()
  4854. : item (0)
  4855. {
  4856. }
  4857. /** Creates a pointer to a list whose head is the item provided. */
  4858. explicit LinkedListPointer (ObjectType* const headItem) throw()
  4859. : item (headItem)
  4860. {
  4861. }
  4862. /** Sets this pointer to point to a new list. */
  4863. LinkedListPointer& operator= (ObjectType* const newItem) throw()
  4864. {
  4865. item = newItem;
  4866. return *this;
  4867. }
  4868. /** Returns the item which this pointer points to. */
  4869. inline operator ObjectType*() const throw()
  4870. {
  4871. return item;
  4872. }
  4873. /** Returns the item which this pointer points to. */
  4874. inline ObjectType* get() const throw()
  4875. {
  4876. return item;
  4877. }
  4878. /** Returns the last item in the list which this pointer points to.
  4879. This will iterate the list and return the last item found. Obviously the speed
  4880. of this operation will be proportional to the size of the list. If the list is
  4881. empty the return value will be this object.
  4882. If you're planning on appending a number of items to your list, it's much more
  4883. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  4884. */
  4885. LinkedListPointer& getLast() throw()
  4886. {
  4887. LinkedListPointer* l = this;
  4888. while (l->item != 0)
  4889. l = &(l->item->nextListItem);
  4890. return *l;
  4891. }
  4892. /** Returns the number of items in the list.
  4893. Obviously with a simple linked list, getting the size involves iterating the list, so
  4894. this can be a lengthy operation - be careful when using this method in your code.
  4895. */
  4896. int size() const throw()
  4897. {
  4898. int total = 0;
  4899. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  4900. ++total;
  4901. return total;
  4902. }
  4903. /** Returns the item at a given index in the list.
  4904. Since the only way to find an item is to iterate the list, this operation can obviously
  4905. be slow, depending on its size, so you should be careful when using this in algorithms.
  4906. */
  4907. LinkedListPointer& operator[] (int index) throw()
  4908. {
  4909. LinkedListPointer* l = this;
  4910. while (--index >= 0 && l->item != 0)
  4911. l = &(l->item->nextListItem);
  4912. return *l;
  4913. }
  4914. /** Returns the item at a given index in the list.
  4915. Since the only way to find an item is to iterate the list, this operation can obviously
  4916. be slow, depending on its size, so you should be careful when using this in algorithms.
  4917. */
  4918. const LinkedListPointer& operator[] (int index) const throw()
  4919. {
  4920. const LinkedListPointer* l = this;
  4921. while (--index >= 0 && l->item != 0)
  4922. l = &(l->item->nextListItem);
  4923. return *l;
  4924. }
  4925. /** Returns true if the list contains the given item. */
  4926. bool contains (const ObjectType* const itemToLookFor) const throw()
  4927. {
  4928. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  4929. if (itemToLookFor == i)
  4930. return true;
  4931. return false;
  4932. }
  4933. /** Inserts an item into the list, placing it before the item that this pointer
  4934. currently points to.
  4935. */
  4936. void insertNext (ObjectType* const newItem)
  4937. {
  4938. jassert (newItem != 0);
  4939. jassert (newItem->nextListItem == 0);
  4940. newItem->nextListItem = item;
  4941. item = newItem;
  4942. }
  4943. /** Inserts an item at a numeric index in the list.
  4944. Obviously this will involve iterating the list to find the item at the given index,
  4945. so be careful about the impact this may have on execution time.
  4946. */
  4947. void insertAtIndex (int index, ObjectType* newItem)
  4948. {
  4949. jassert (newItem != 0);
  4950. LinkedListPointer* l = this;
  4951. while (index != 0 && l->item != 0)
  4952. {
  4953. l = &(l->item->nextListItem);
  4954. --index;
  4955. }
  4956. l->insertNext (newItem);
  4957. }
  4958. /** Replaces the object that this pointer points to, appending the rest of the list to
  4959. the new object, and returning the old one.
  4960. */
  4961. ObjectType* replaceNext (ObjectType* const newItem) throw()
  4962. {
  4963. jassert (newItem != 0);
  4964. jassert (newItem->nextListItem == 0);
  4965. ObjectType* const oldItem = item;
  4966. item = newItem;
  4967. item->nextListItem = oldItem->nextListItem;
  4968. oldItem->nextListItem = 0;
  4969. return oldItem;
  4970. }
  4971. /** Adds an item to the end of the list.
  4972. This operation involves iterating the whole list, so can be slow - if you need to
  4973. append a number of items to your list, it's much more efficient to use the Appender
  4974. class than to repeatedly call append().
  4975. */
  4976. void append (ObjectType* const newItem)
  4977. {
  4978. getLast().item = newItem;
  4979. }
  4980. /** Creates copies of all the items in another list and adds them to this one.
  4981. This will use the ObjectType's copy constructor to try to create copies of each
  4982. item in the other list, and appends them to this list.
  4983. */
  4984. void addCopyOfList (const LinkedListPointer& other)
  4985. {
  4986. LinkedListPointer* insertPoint = this;
  4987. for (ObjectType* i = other.item; i != 0; i = i->nextListItem)
  4988. {
  4989. insertPoint->insertNext (new ObjectType (*i));
  4990. insertPoint = &(insertPoint->item->nextListItem);
  4991. }
  4992. }
  4993. /** Removes the head item from the list.
  4994. This won't delete the object that is removed, but returns it, so the caller can
  4995. delete it if necessary.
  4996. */
  4997. ObjectType* removeNext() throw()
  4998. {
  4999. ObjectType* const oldItem = item;
  5000. if (oldItem != 0)
  5001. {
  5002. item = oldItem->nextListItem;
  5003. oldItem->nextListItem = 0;
  5004. }
  5005. return oldItem;
  5006. }
  5007. /** Removes a specific item from the list.
  5008. Note that this will not delete the item, it simply unlinks it from the list.
  5009. */
  5010. void remove (ObjectType* const itemToRemove)
  5011. {
  5012. LinkedListPointer* const l = findPointerTo (itemToRemove);
  5013. if (l != 0)
  5014. l->removeNext();
  5015. }
  5016. /** Iterates the list, calling the delete operator on all of its elements and
  5017. leaving this pointer empty.
  5018. */
  5019. void deleteAll()
  5020. {
  5021. while (item != 0)
  5022. {
  5023. ObjectType* const oldItem = item;
  5024. item = oldItem->nextListItem;
  5025. delete oldItem;
  5026. }
  5027. }
  5028. /** Finds a pointer to a given item.
  5029. If the item is found in the list, this returns the pointer that points to it. If
  5030. the item isn't found, this returns null.
  5031. */
  5032. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) throw()
  5033. {
  5034. LinkedListPointer* l = this;
  5035. while (l->item != 0)
  5036. {
  5037. if (l->item == itemToLookFor)
  5038. return l;
  5039. l = &(l->item->nextListItem);
  5040. }
  5041. return 0;
  5042. }
  5043. /** Copies the items in the list to an array.
  5044. The destArray must contain enough elements to hold the entire list - no checks are
  5045. made for this!
  5046. */
  5047. void copyToArray (ObjectType** destArray) const throw()
  5048. {
  5049. jassert (destArray != 0);
  5050. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  5051. *destArray++ = i;
  5052. }
  5053. /**
  5054. Allows efficient repeated insertions into a list.
  5055. You can create an Appender object which points to the last element in your
  5056. list, and then repeatedly call Appender::append() to add items to the end
  5057. of the list in O(1) time.
  5058. */
  5059. class Appender
  5060. {
  5061. public:
  5062. /** Creates an appender which will add items to the given list.
  5063. */
  5064. Appender (LinkedListPointer& endOfListPointer) throw()
  5065. : endOfList (&endOfListPointer)
  5066. {
  5067. // This can only be used to add to the end of a list.
  5068. jassert (endOfListPointer.item == 0);
  5069. }
  5070. /** Appends an item to the list. */
  5071. void append (ObjectType* const newItem) throw()
  5072. {
  5073. *endOfList = newItem;
  5074. endOfList = &(newItem->nextListItem);
  5075. }
  5076. private:
  5077. LinkedListPointer* endOfList;
  5078. JUCE_DECLARE_NON_COPYABLE (Appender);
  5079. };
  5080. private:
  5081. ObjectType* item;
  5082. };
  5083. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  5084. /*** End of inlined file: juce_LinkedListPointer.h ***/
  5085. class XmlElement;
  5086. /** Holds a set of named var objects.
  5087. This can be used as a basic structure to hold a set of var object, which can
  5088. be retrieved by using their identifier.
  5089. */
  5090. class JUCE_API NamedValueSet
  5091. {
  5092. public:
  5093. /** Creates an empty set. */
  5094. NamedValueSet() throw();
  5095. /** Creates a copy of another set. */
  5096. NamedValueSet (const NamedValueSet& other);
  5097. /** Replaces this set with a copy of another set. */
  5098. NamedValueSet& operator= (const NamedValueSet& other);
  5099. /** Destructor. */
  5100. ~NamedValueSet();
  5101. bool operator== (const NamedValueSet& other) const;
  5102. bool operator!= (const NamedValueSet& other) const;
  5103. /** Returns the total number of values that the set contains. */
  5104. int size() const throw();
  5105. /** Returns the value of a named item.
  5106. If the name isn't found, this will return a void variant.
  5107. @see getProperty
  5108. */
  5109. const var& operator[] (const Identifier& name) const;
  5110. /** Tries to return the named value, but if no such value is found, this will
  5111. instead return the supplied default value.
  5112. */
  5113. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  5114. /** Changes or adds a named value.
  5115. @returns true if a value was changed or added; false if the
  5116. value was already set the the value passed-in.
  5117. */
  5118. bool set (const Identifier& name, const var& newValue);
  5119. /** Returns true if the set contains an item with the specified name. */
  5120. bool contains (const Identifier& name) const;
  5121. /** Removes a value from the set.
  5122. @returns true if a value was removed; false if there was no value
  5123. with the name that was given.
  5124. */
  5125. bool remove (const Identifier& name);
  5126. /** Returns the name of the value at a given index.
  5127. The index must be between 0 and size() - 1.
  5128. */
  5129. const Identifier getName (int index) const;
  5130. /** Returns the value of the item at a given index.
  5131. The index must be between 0 and size() - 1.
  5132. */
  5133. const var getValueAt (int index) const;
  5134. /** Removes all values. */
  5135. void clear();
  5136. /** Returns a pointer to the var that holds a named value, or null if there is
  5137. no value with this name.
  5138. Do not use this method unless you really need access to the internal var object
  5139. for some reason - for normal reading and writing always prefer operator[]() and set().
  5140. */
  5141. var* getVarPointer (const Identifier& name) const;
  5142. /** Sets properties to the values of all of an XML element's attributes. */
  5143. void setFromXmlAttributes (const XmlElement& xml);
  5144. /** Sets attributes in an XML element corresponding to each of this object's
  5145. properties.
  5146. */
  5147. void copyToXmlAttributes (XmlElement& xml) const;
  5148. private:
  5149. class NamedValue
  5150. {
  5151. public:
  5152. NamedValue() throw();
  5153. NamedValue (const Identifier& name, const var& value);
  5154. bool operator== (const NamedValue& other) const throw();
  5155. LinkedListPointer<NamedValue> nextListItem;
  5156. Identifier name;
  5157. var value;
  5158. private:
  5159. JUCE_LEAK_DETECTOR (NamedValue);
  5160. };
  5161. friend class LinkedListPointer<NamedValue>;
  5162. LinkedListPointer<NamedValue> values;
  5163. };
  5164. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  5165. /*** End of inlined file: juce_NamedValueSet.h ***/
  5166. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  5167. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  5168. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  5169. /**
  5170. Adds reference-counting to an object.
  5171. To add reference-counting to a class, derive it from this class, and
  5172. use the ReferenceCountedObjectPtr class to point to it.
  5173. e.g. @code
  5174. class MyClass : public ReferenceCountedObject
  5175. {
  5176. void foo();
  5177. // This is a neat way of declaring a typedef for a pointer class,
  5178. // rather than typing out the full templated name each time..
  5179. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  5180. };
  5181. MyClass::Ptr p = new MyClass();
  5182. MyClass::Ptr p2 = p;
  5183. p = 0;
  5184. p2->foo();
  5185. @endcode
  5186. Once a new ReferenceCountedObject has been assigned to a pointer, be
  5187. careful not to delete the object manually.
  5188. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  5189. */
  5190. class JUCE_API ReferenceCountedObject
  5191. {
  5192. public:
  5193. /** Increments the object's reference count.
  5194. This is done automatically by the smart pointer, but is public just
  5195. in case it's needed for nefarious purposes.
  5196. */
  5197. inline void incReferenceCount() throw()
  5198. {
  5199. ++refCount;
  5200. }
  5201. /** Decreases the object's reference count.
  5202. If the count gets to zero, the object will be deleted.
  5203. */
  5204. inline void decReferenceCount() throw()
  5205. {
  5206. jassert (getReferenceCount() > 0);
  5207. if (--refCount == 0)
  5208. delete this;
  5209. }
  5210. /** Returns the object's current reference count. */
  5211. inline int getReferenceCount() const throw()
  5212. {
  5213. return refCount.get();
  5214. }
  5215. protected:
  5216. /** Creates the reference-counted object (with an initial ref count of zero). */
  5217. ReferenceCountedObject()
  5218. {
  5219. }
  5220. /** Destructor. */
  5221. virtual ~ReferenceCountedObject()
  5222. {
  5223. // it's dangerous to delete an object that's still referenced by something else!
  5224. jassert (getReferenceCount() == 0);
  5225. }
  5226. private:
  5227. Atomic <int> refCount;
  5228. };
  5229. /**
  5230. Used to point to an object of type ReferenceCountedObject.
  5231. It's wise to use a typedef instead of typing out the templated name
  5232. each time - e.g.
  5233. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  5234. @see ReferenceCountedObject, ReferenceCountedObjectArray
  5235. */
  5236. template <class ReferenceCountedObjectClass>
  5237. class ReferenceCountedObjectPtr
  5238. {
  5239. public:
  5240. /** Creates a pointer to a null object. */
  5241. inline ReferenceCountedObjectPtr() throw()
  5242. : referencedObject (0)
  5243. {
  5244. }
  5245. /** Creates a pointer to an object.
  5246. This will increment the object's reference-count if it is non-null.
  5247. */
  5248. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  5249. : referencedObject (refCountedObject)
  5250. {
  5251. if (refCountedObject != 0)
  5252. refCountedObject->incReferenceCount();
  5253. }
  5254. /** Copies another pointer.
  5255. This will increment the object's reference-count (if it is non-null).
  5256. */
  5257. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  5258. : referencedObject (other.referencedObject)
  5259. {
  5260. if (referencedObject != 0)
  5261. referencedObject->incReferenceCount();
  5262. }
  5263. /** Changes this pointer to point at a different object.
  5264. The reference count of the old object is decremented, and it might be
  5265. deleted if it hits zero. The new object's count is incremented.
  5266. */
  5267. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  5268. {
  5269. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  5270. if (newObject != referencedObject)
  5271. {
  5272. if (newObject != 0)
  5273. newObject->incReferenceCount();
  5274. ReferenceCountedObjectClass* const oldObject = referencedObject;
  5275. referencedObject = newObject;
  5276. if (oldObject != 0)
  5277. oldObject->decReferenceCount();
  5278. }
  5279. return *this;
  5280. }
  5281. /** Changes this pointer to point at a different object.
  5282. The reference count of the old object is decremented, and it might be
  5283. deleted if it hits zero. The new object's count is incremented.
  5284. */
  5285. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  5286. {
  5287. if (referencedObject != newObject)
  5288. {
  5289. if (newObject != 0)
  5290. newObject->incReferenceCount();
  5291. ReferenceCountedObjectClass* const oldObject = referencedObject;
  5292. referencedObject = newObject;
  5293. if (oldObject != 0)
  5294. oldObject->decReferenceCount();
  5295. }
  5296. return *this;
  5297. }
  5298. /** Destructor.
  5299. This will decrement the object's reference-count, and may delete it if it
  5300. gets to zero.
  5301. */
  5302. inline ~ReferenceCountedObjectPtr()
  5303. {
  5304. if (referencedObject != 0)
  5305. referencedObject->decReferenceCount();
  5306. }
  5307. /** Returns the object that this pointer references.
  5308. The pointer returned may be zero, of course.
  5309. */
  5310. inline operator ReferenceCountedObjectClass*() const throw()
  5311. {
  5312. return referencedObject;
  5313. }
  5314. // the -> operator is called on the referenced object
  5315. inline ReferenceCountedObjectClass* operator->() const throw()
  5316. {
  5317. return referencedObject;
  5318. }
  5319. /** Returns the object that this pointer references.
  5320. The pointer returned may be zero, of course.
  5321. */
  5322. inline ReferenceCountedObjectClass* getObject() const throw()
  5323. {
  5324. return referencedObject;
  5325. }
  5326. private:
  5327. ReferenceCountedObjectClass* referencedObject;
  5328. };
  5329. /** Compares two ReferenceCountedObjectPointers. */
  5330. template <class ReferenceCountedObjectClass>
  5331. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) throw()
  5332. {
  5333. return object1.getObject() == object2;
  5334. }
  5335. /** Compares two ReferenceCountedObjectPointers. */
  5336. template <class ReferenceCountedObjectClass>
  5337. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  5338. {
  5339. return object1.getObject() == object2.getObject();
  5340. }
  5341. /** Compares two ReferenceCountedObjectPointers. */
  5342. template <class ReferenceCountedObjectClass>
  5343. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  5344. {
  5345. return object1 == object2.getObject();
  5346. }
  5347. /** Compares two ReferenceCountedObjectPointers. */
  5348. template <class ReferenceCountedObjectClass>
  5349. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) throw()
  5350. {
  5351. return object1.getObject() != object2;
  5352. }
  5353. /** Compares two ReferenceCountedObjectPointers. */
  5354. template <class ReferenceCountedObjectClass>
  5355. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  5356. {
  5357. return object1.getObject() != object2.getObject();
  5358. }
  5359. /** Compares two ReferenceCountedObjectPointers. */
  5360. template <class ReferenceCountedObjectClass>
  5361. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  5362. {
  5363. return object1 != object2.getObject();
  5364. }
  5365. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  5366. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  5367. /**
  5368. Represents a dynamically implemented object.
  5369. This class is primarily intended for wrapping scripting language objects,
  5370. but could be used for other purposes.
  5371. An instance of a DynamicObject can be used to store named properties, and
  5372. by subclassing hasMethod() and invokeMethod(), you can give your object
  5373. methods.
  5374. */
  5375. class JUCE_API DynamicObject : public ReferenceCountedObject
  5376. {
  5377. public:
  5378. DynamicObject();
  5379. /** Destructor. */
  5380. virtual ~DynamicObject();
  5381. /** Returns true if the object has a property with this name.
  5382. Note that if the property is actually a method, this will return false.
  5383. */
  5384. virtual bool hasProperty (const Identifier& propertyName) const;
  5385. /** Returns a named property.
  5386. This returns a void if no such property exists.
  5387. */
  5388. virtual const var getProperty (const Identifier& propertyName) const;
  5389. /** Sets a named property. */
  5390. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  5391. /** Removes a named property. */
  5392. virtual void removeProperty (const Identifier& propertyName);
  5393. /** Checks whether this object has the specified method.
  5394. The default implementation of this just checks whether there's a property
  5395. with this name that's actually a method, but this can be overridden for
  5396. building objects with dynamic invocation.
  5397. */
  5398. virtual bool hasMethod (const Identifier& methodName) const;
  5399. /** Invokes a named method on this object.
  5400. The default implementation looks up the named property, and if it's a method
  5401. call, then it invokes it.
  5402. This method is virtual to allow more dynamic invocation to used for objects
  5403. where the methods may not already be set as properies.
  5404. */
  5405. virtual const var invokeMethod (const Identifier& methodName,
  5406. const var* parameters,
  5407. int numParameters);
  5408. /** Sets up a method.
  5409. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  5410. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  5411. the code easier to read,
  5412. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  5413. @code
  5414. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  5415. @endcode
  5416. */
  5417. void setMethod (const Identifier& methodName,
  5418. var::MethodFunction methodFunction);
  5419. /** Removes all properties and methods from the object. */
  5420. void clear();
  5421. private:
  5422. NamedValueSet properties;
  5423. JUCE_LEAK_DETECTOR (DynamicObject);
  5424. };
  5425. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  5426. /*** End of inlined file: juce_DynamicObject.h ***/
  5427. #endif
  5428. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5429. #endif
  5430. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  5431. #endif
  5432. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  5433. #endif
  5434. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  5435. /*** Start of inlined file: juce_OwnedArray.h ***/
  5436. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  5437. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  5438. /** An array designed for holding objects.
  5439. This holds a list of pointers to objects, and will automatically
  5440. delete the objects when they are removed from the array, or when the
  5441. array is itself deleted.
  5442. Declare it in the form: OwnedArray<MyObjectClass>
  5443. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  5444. After adding objects, they are 'owned' by the array and will be deleted when
  5445. removed or replaced.
  5446. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5447. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5448. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  5449. */
  5450. template <class ObjectClass,
  5451. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  5452. class OwnedArray
  5453. {
  5454. public:
  5455. /** Creates an empty array. */
  5456. OwnedArray() throw()
  5457. : numUsed (0)
  5458. {
  5459. }
  5460. /** Deletes the array and also deletes any objects inside it.
  5461. To get rid of the array without deleting its objects, use its
  5462. clear (false) method before deleting it.
  5463. */
  5464. ~OwnedArray()
  5465. {
  5466. clear (true);
  5467. }
  5468. /** Clears the array, optionally deleting the objects inside it first. */
  5469. void clear (const bool deleteObjects = true)
  5470. {
  5471. const ScopedLockType lock (getLock());
  5472. if (deleteObjects)
  5473. {
  5474. while (numUsed > 0)
  5475. delete data.elements [--numUsed];
  5476. }
  5477. data.setAllocatedSize (0);
  5478. numUsed = 0;
  5479. }
  5480. /** Returns the number of items currently in the array.
  5481. @see operator[]
  5482. */
  5483. inline int size() const throw()
  5484. {
  5485. return numUsed;
  5486. }
  5487. /** Returns a pointer to the object at this index in the array.
  5488. If the index is out-of-range, this will return a null pointer, (and
  5489. it could be null anyway, because it's ok for the array to hold null
  5490. pointers as well as objects).
  5491. @see getUnchecked
  5492. */
  5493. inline ObjectClass* operator[] (const int index) const throw()
  5494. {
  5495. const ScopedLockType lock (getLock());
  5496. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5497. : static_cast <ObjectClass*> (0);
  5498. }
  5499. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  5500. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  5501. it can be used when you're sure the index if always going to be legal.
  5502. */
  5503. inline ObjectClass* getUnchecked (const int index) const throw()
  5504. {
  5505. const ScopedLockType lock (getLock());
  5506. jassert (isPositiveAndBelow (index, numUsed));
  5507. return data.elements [index];
  5508. }
  5509. /** Returns a pointer to the first object in the array.
  5510. This will return a null pointer if the array's empty.
  5511. @see getLast
  5512. */
  5513. inline ObjectClass* getFirst() const throw()
  5514. {
  5515. const ScopedLockType lock (getLock());
  5516. return numUsed > 0 ? data.elements [0]
  5517. : static_cast <ObjectClass*> (0);
  5518. }
  5519. /** Returns a pointer to the last object in the array.
  5520. This will return a null pointer if the array's empty.
  5521. @see getFirst
  5522. */
  5523. inline ObjectClass* getLast() const throw()
  5524. {
  5525. const ScopedLockType lock (getLock());
  5526. return numUsed > 0 ? data.elements [numUsed - 1]
  5527. : static_cast <ObjectClass*> (0);
  5528. }
  5529. /** Returns a pointer to the actual array data.
  5530. This pointer will only be valid until the next time a non-const method
  5531. is called on the array.
  5532. */
  5533. inline ObjectClass** getRawDataPointer() throw()
  5534. {
  5535. return data.elements;
  5536. }
  5537. /** Finds the index of an object which might be in the array.
  5538. @param objectToLookFor the object to look for
  5539. @returns the index at which the object was found, or -1 if it's not found
  5540. */
  5541. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  5542. {
  5543. const ScopedLockType lock (getLock());
  5544. ObjectClass* const* e = data.elements.getData();
  5545. ObjectClass* const* const end = e + numUsed;
  5546. while (e != end)
  5547. {
  5548. if (objectToLookFor == *e)
  5549. return static_cast <int> (e - data.elements.getData());
  5550. ++e;
  5551. }
  5552. return -1;
  5553. }
  5554. /** Returns true if the array contains a specified object.
  5555. @param objectToLookFor the object to look for
  5556. @returns true if the object is in the array
  5557. */
  5558. bool contains (const ObjectClass* const objectToLookFor) const throw()
  5559. {
  5560. const ScopedLockType lock (getLock());
  5561. ObjectClass* const* e = data.elements.getData();
  5562. ObjectClass* const* const end = e + numUsed;
  5563. while (e != end)
  5564. {
  5565. if (objectToLookFor == *e)
  5566. return true;
  5567. ++e;
  5568. }
  5569. return false;
  5570. }
  5571. /** Appends a new object to the end of the array.
  5572. Note that the this object will be deleted by the OwnedArray when it
  5573. is removed, so be careful not to delete it somewhere else.
  5574. Also be careful not to add the same object to the array more than once,
  5575. as this will obviously cause deletion of dangling pointers.
  5576. @param newObject the new object to add to the array
  5577. @see set, insert, addIfNotAlreadyThere, addSorted
  5578. */
  5579. void add (const ObjectClass* const newObject) throw()
  5580. {
  5581. const ScopedLockType lock (getLock());
  5582. data.ensureAllocatedSize (numUsed + 1);
  5583. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5584. }
  5585. /** Inserts a new object into the array at the given index.
  5586. Note that the this object will be deleted by the OwnedArray when it
  5587. is removed, so be careful not to delete it somewhere else.
  5588. If the index is less than 0 or greater than the size of the array, the
  5589. element will be added to the end of the array.
  5590. Otherwise, it will be inserted into the array, moving all the later elements
  5591. along to make room.
  5592. Be careful not to add the same object to the array more than once,
  5593. as this will obviously cause deletion of dangling pointers.
  5594. @param indexToInsertAt the index at which the new element should be inserted
  5595. @param newObject the new object to add to the array
  5596. @see add, addSorted, addIfNotAlreadyThere, set
  5597. */
  5598. void insert (int indexToInsertAt,
  5599. const ObjectClass* const newObject) throw()
  5600. {
  5601. if (indexToInsertAt >= 0)
  5602. {
  5603. const ScopedLockType lock (getLock());
  5604. if (indexToInsertAt > numUsed)
  5605. indexToInsertAt = numUsed;
  5606. data.ensureAllocatedSize (numUsed + 1);
  5607. ObjectClass** const e = data.elements + indexToInsertAt;
  5608. const int numToMove = numUsed - indexToInsertAt;
  5609. if (numToMove > 0)
  5610. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  5611. *e = const_cast <ObjectClass*> (newObject);
  5612. ++numUsed;
  5613. }
  5614. else
  5615. {
  5616. add (newObject);
  5617. }
  5618. }
  5619. /** Appends a new object at the end of the array as long as the array doesn't
  5620. already contain it.
  5621. If the array already contains a matching object, nothing will be done.
  5622. @param newObject the new object to add to the array
  5623. */
  5624. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  5625. {
  5626. const ScopedLockType lock (getLock());
  5627. if (! contains (newObject))
  5628. add (newObject);
  5629. }
  5630. /** Replaces an object in the array with a different one.
  5631. If the index is less than zero, this method does nothing.
  5632. If the index is beyond the end of the array, the new object is added to the end of the array.
  5633. Be careful not to add the same object to the array more than once,
  5634. as this will obviously cause deletion of dangling pointers.
  5635. @param indexToChange the index whose value you want to change
  5636. @param newObject the new value to set for this index.
  5637. @param deleteOldElement whether to delete the object that's being replaced with the new one
  5638. @see add, insert, remove
  5639. */
  5640. void set (const int indexToChange,
  5641. const ObjectClass* const newObject,
  5642. const bool deleteOldElement = true)
  5643. {
  5644. if (indexToChange >= 0)
  5645. {
  5646. ObjectClass* toDelete = 0;
  5647. {
  5648. const ScopedLockType lock (getLock());
  5649. if (indexToChange < numUsed)
  5650. {
  5651. if (deleteOldElement)
  5652. {
  5653. toDelete = data.elements [indexToChange];
  5654. if (toDelete == newObject)
  5655. toDelete = 0;
  5656. }
  5657. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  5658. }
  5659. else
  5660. {
  5661. data.ensureAllocatedSize (numUsed + 1);
  5662. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5663. }
  5664. }
  5665. delete toDelete; // don't want to use a ScopedPointer here because if the
  5666. // object has a private destructor, both OwnedArray and
  5667. // ScopedPointer would need to be friend classes..
  5668. }
  5669. else
  5670. {
  5671. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  5672. // any effect - but since the object is not being added, it may be leaking..
  5673. }
  5674. }
  5675. /** Adds elements from another array to the end of this array.
  5676. @param arrayToAddFrom the array from which to copy the elements
  5677. @param startIndex the first element of the other array to start copying from
  5678. @param numElementsToAdd how many elements to add from the other array. If this
  5679. value is negative or greater than the number of available elements,
  5680. all available elements will be copied.
  5681. @see add
  5682. */
  5683. template <class OtherArrayType>
  5684. void addArray (const OtherArrayType& arrayToAddFrom,
  5685. int startIndex = 0,
  5686. int numElementsToAdd = -1)
  5687. {
  5688. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5689. const ScopedLockType lock2 (getLock());
  5690. if (startIndex < 0)
  5691. {
  5692. jassertfalse;
  5693. startIndex = 0;
  5694. }
  5695. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5696. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5697. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5698. while (--numElementsToAdd >= 0)
  5699. {
  5700. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  5701. ++numUsed;
  5702. }
  5703. }
  5704. /** Adds copies of the elements in another array to the end of this array.
  5705. The other array must be either an OwnedArray of a compatible type of object, or an Array
  5706. containing pointers to the same kind of object. The objects involved must provide
  5707. a copy constructor, and this will be used to create new copies of each element, and
  5708. add them to this array.
  5709. @param arrayToAddFrom the array from which to copy the elements
  5710. @param startIndex the first element of the other array to start copying from
  5711. @param numElementsToAdd how many elements to add from the other array. If this
  5712. value is negative or greater than the number of available elements,
  5713. all available elements will be copied.
  5714. @see add
  5715. */
  5716. template <class OtherArrayType>
  5717. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  5718. int startIndex = 0,
  5719. int numElementsToAdd = -1)
  5720. {
  5721. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5722. const ScopedLockType lock2 (getLock());
  5723. if (startIndex < 0)
  5724. {
  5725. jassertfalse;
  5726. startIndex = 0;
  5727. }
  5728. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5729. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5730. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5731. while (--numElementsToAdd >= 0)
  5732. {
  5733. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  5734. ++numUsed;
  5735. }
  5736. }
  5737. /** Inserts a new object into the array assuming that the array is sorted.
  5738. This will use a comparator to find the position at which the new object
  5739. should go. If the array isn't sorted, the behaviour of this
  5740. method will be unpredictable.
  5741. @param comparator the comparator to use to compare the elements - see the sort method
  5742. for details about this object's structure
  5743. @param newObject the new object to insert to the array
  5744. @see add, sort, indexOfSorted
  5745. */
  5746. template <class ElementComparator>
  5747. void addSorted (ElementComparator& comparator,
  5748. ObjectClass* const newObject) throw()
  5749. {
  5750. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5751. // avoids getting warning messages about the parameter being unused
  5752. const ScopedLockType lock (getLock());
  5753. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  5754. }
  5755. /** Finds the index of an object in the array, assuming that the array is sorted.
  5756. This will use a comparator to do a binary-chop to find the index of the given
  5757. element, if it exists. If the array isn't sorted, the behaviour of this
  5758. method will be unpredictable.
  5759. @param comparator the comparator to use to compare the elements - see the sort()
  5760. method for details about the form this object should take
  5761. @param objectToLookFor the object to search for
  5762. @returns the index of the element, or -1 if it's not found
  5763. @see addSorted, sort
  5764. */
  5765. template <class ElementComparator>
  5766. int indexOfSorted (ElementComparator& comparator,
  5767. const ObjectClass* const objectToLookFor) const throw()
  5768. {
  5769. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5770. // avoids getting warning messages about the parameter being unused
  5771. const ScopedLockType lock (getLock());
  5772. int start = 0;
  5773. int end = numUsed;
  5774. for (;;)
  5775. {
  5776. if (start >= end)
  5777. {
  5778. return -1;
  5779. }
  5780. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  5781. {
  5782. return start;
  5783. }
  5784. else
  5785. {
  5786. const int halfway = (start + end) >> 1;
  5787. if (halfway == start)
  5788. return -1;
  5789. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  5790. start = halfway;
  5791. else
  5792. end = halfway;
  5793. }
  5794. }
  5795. }
  5796. /** Removes an object from the array.
  5797. This will remove the object at a given index (optionally also
  5798. deleting it) and move back all the subsequent objects to close the gap.
  5799. If the index passed in is out-of-range, nothing will happen.
  5800. @param indexToRemove the index of the element to remove
  5801. @param deleteObject whether to delete the object that is removed
  5802. @see removeObject, removeRange
  5803. */
  5804. void remove (const int indexToRemove,
  5805. const bool deleteObject = true)
  5806. {
  5807. ObjectClass* toDelete = 0;
  5808. {
  5809. const ScopedLockType lock (getLock());
  5810. if (isPositiveAndBelow (indexToRemove, numUsed))
  5811. {
  5812. ObjectClass** const e = data.elements + indexToRemove;
  5813. if (deleteObject)
  5814. toDelete = *e;
  5815. --numUsed;
  5816. const int numToShift = numUsed - indexToRemove;
  5817. if (numToShift > 0)
  5818. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5819. }
  5820. }
  5821. delete toDelete; // don't want to use a ScopedPointer here because if the
  5822. // object has a private destructor, both OwnedArray and
  5823. // ScopedPointer would need to be friend classes..
  5824. if ((numUsed << 1) < data.numAllocated)
  5825. minimiseStorageOverheads();
  5826. }
  5827. /** Removes and returns an object from the array without deleting it.
  5828. This will remove the object at a given index and return it, moving back all
  5829. the subsequent objects to close the gap. If the index passed in is out-of-range,
  5830. nothing will happen.
  5831. @param indexToRemove the index of the element to remove
  5832. @see remove, removeObject, removeRange
  5833. */
  5834. ObjectClass* removeAndReturn (const int indexToRemove)
  5835. {
  5836. ObjectClass* removedItem = 0;
  5837. const ScopedLockType lock (getLock());
  5838. if (isPositiveAndBelow (indexToRemove, numUsed))
  5839. {
  5840. ObjectClass** const e = data.elements + indexToRemove;
  5841. removedItem = *e;
  5842. --numUsed;
  5843. const int numToShift = numUsed - indexToRemove;
  5844. if (numToShift > 0)
  5845. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5846. if ((numUsed << 1) < data.numAllocated)
  5847. minimiseStorageOverheads();
  5848. }
  5849. return removedItem;
  5850. }
  5851. /** Removes a specified object from the array.
  5852. If the item isn't found, no action is taken.
  5853. @param objectToRemove the object to try to remove
  5854. @param deleteObject whether to delete the object (if it's found)
  5855. @see remove, removeRange
  5856. */
  5857. void removeObject (const ObjectClass* const objectToRemove,
  5858. const bool deleteObject = true)
  5859. {
  5860. const ScopedLockType lock (getLock());
  5861. ObjectClass** e = data.elements.getData();
  5862. for (int i = numUsed; --i >= 0;)
  5863. {
  5864. if (objectToRemove == *e)
  5865. {
  5866. remove (static_cast <int> (e - data.elements.getData()), deleteObject);
  5867. break;
  5868. }
  5869. ++e;
  5870. }
  5871. }
  5872. /** Removes a range of objects from the array.
  5873. This will remove a set of objects, starting from the given index,
  5874. and move any subsequent elements down to close the gap.
  5875. If the range extends beyond the bounds of the array, it will
  5876. be safely clipped to the size of the array.
  5877. @param startIndex the index of the first object to remove
  5878. @param numberToRemove how many objects should be removed
  5879. @param deleteObjects whether to delete the objects that get removed
  5880. @see remove, removeObject
  5881. */
  5882. void removeRange (int startIndex,
  5883. const int numberToRemove,
  5884. const bool deleteObjects = true)
  5885. {
  5886. const ScopedLockType lock (getLock());
  5887. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5888. startIndex = jlimit (0, numUsed, startIndex);
  5889. if (endIndex > startIndex)
  5890. {
  5891. if (deleteObjects)
  5892. {
  5893. for (int i = startIndex; i < endIndex; ++i)
  5894. {
  5895. delete data.elements [i];
  5896. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  5897. }
  5898. }
  5899. const int rangeSize = endIndex - startIndex;
  5900. ObjectClass** e = data.elements + startIndex;
  5901. int numToShift = numUsed - endIndex;
  5902. numUsed -= rangeSize;
  5903. while (--numToShift >= 0)
  5904. {
  5905. *e = e [rangeSize];
  5906. ++e;
  5907. }
  5908. if ((numUsed << 1) < data.numAllocated)
  5909. minimiseStorageOverheads();
  5910. }
  5911. }
  5912. /** Removes the last n objects from the array.
  5913. @param howManyToRemove how many objects to remove from the end of the array
  5914. @param deleteObjects whether to also delete the objects that are removed
  5915. @see remove, removeObject, removeRange
  5916. */
  5917. void removeLast (int howManyToRemove = 1,
  5918. const bool deleteObjects = true)
  5919. {
  5920. const ScopedLockType lock (getLock());
  5921. if (howManyToRemove >= numUsed)
  5922. clear (deleteObjects);
  5923. else
  5924. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  5925. }
  5926. /** Swaps a pair of objects in the array.
  5927. If either of the indexes passed in is out-of-range, nothing will happen,
  5928. otherwise the two objects at these positions will be exchanged.
  5929. */
  5930. void swap (const int index1,
  5931. const int index2) throw()
  5932. {
  5933. const ScopedLockType lock (getLock());
  5934. if (isPositiveAndBelow (index1, numUsed)
  5935. && isPositiveAndBelow (index2, numUsed))
  5936. {
  5937. swapVariables (data.elements [index1],
  5938. data.elements [index2]);
  5939. }
  5940. }
  5941. /** Moves one of the objects to a different position.
  5942. This will move the object to a specified index, shuffling along
  5943. any intervening elements as required.
  5944. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5945. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5946. @param currentIndex the index of the object to be moved. If this isn't a
  5947. valid index, then nothing will be done
  5948. @param newIndex the index at which you'd like this object to end up. If this
  5949. is less than zero, it will be moved to the end of the array
  5950. */
  5951. void move (const int currentIndex,
  5952. int newIndex) throw()
  5953. {
  5954. if (currentIndex != newIndex)
  5955. {
  5956. const ScopedLockType lock (getLock());
  5957. if (isPositiveAndBelow (currentIndex, numUsed))
  5958. {
  5959. if (! isPositiveAndBelow (newIndex, numUsed))
  5960. newIndex = numUsed - 1;
  5961. ObjectClass* const value = data.elements [currentIndex];
  5962. if (newIndex > currentIndex)
  5963. {
  5964. memmove (data.elements + currentIndex,
  5965. data.elements + currentIndex + 1,
  5966. (newIndex - currentIndex) * sizeof (ObjectClass*));
  5967. }
  5968. else
  5969. {
  5970. memmove (data.elements + newIndex + 1,
  5971. data.elements + newIndex,
  5972. (currentIndex - newIndex) * sizeof (ObjectClass*));
  5973. }
  5974. data.elements [newIndex] = value;
  5975. }
  5976. }
  5977. }
  5978. /** This swaps the contents of this array with those of another array.
  5979. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5980. because it just swaps their internal pointers.
  5981. */
  5982. void swapWithArray (OwnedArray& otherArray) throw()
  5983. {
  5984. const ScopedLockType lock1 (getLock());
  5985. const ScopedLockType lock2 (otherArray.getLock());
  5986. data.swapWith (otherArray.data);
  5987. swapVariables (numUsed, otherArray.numUsed);
  5988. }
  5989. /** Reduces the amount of storage being used by the array.
  5990. Arrays typically allocate slightly more storage than they need, and after
  5991. removing elements, they may have quite a lot of unused space allocated.
  5992. This method will reduce the amount of allocated storage to a minimum.
  5993. */
  5994. void minimiseStorageOverheads() throw()
  5995. {
  5996. const ScopedLockType lock (getLock());
  5997. data.shrinkToNoMoreThan (numUsed);
  5998. }
  5999. /** Increases the array's internal storage to hold a minimum number of elements.
  6000. Calling this before adding a large known number of elements means that
  6001. the array won't have to keep dynamically resizing itself as the elements
  6002. are added, and it'll therefore be more efficient.
  6003. */
  6004. void ensureStorageAllocated (const int minNumElements) throw()
  6005. {
  6006. const ScopedLockType lock (getLock());
  6007. data.ensureAllocatedSize (minNumElements);
  6008. }
  6009. /** Sorts the elements in the array.
  6010. This will use a comparator object to sort the elements into order. The object
  6011. passed must have a method of the form:
  6012. @code
  6013. int compareElements (ElementType first, ElementType second);
  6014. @endcode
  6015. ..and this method must return:
  6016. - a value of < 0 if the first comes before the second
  6017. - a value of 0 if the two objects are equivalent
  6018. - a value of > 0 if the second comes before the first
  6019. To improve performance, the compareElements() method can be declared as static or const.
  6020. @param comparator the comparator to use for comparing elements.
  6021. @param retainOrderOfEquivalentItems if this is true, then items
  6022. which the comparator says are equivalent will be
  6023. kept in the order in which they currently appear
  6024. in the array. This is slower to perform, but may
  6025. be important in some cases. If it's false, a faster
  6026. algorithm is used, but equivalent elements may be
  6027. rearranged.
  6028. @see sortArray, indexOfSorted
  6029. */
  6030. template <class ElementComparator>
  6031. void sort (ElementComparator& comparator,
  6032. const bool retainOrderOfEquivalentItems = false) const throw()
  6033. {
  6034. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6035. // avoids getting warning messages about the parameter being unused
  6036. const ScopedLockType lock (getLock());
  6037. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6038. }
  6039. /** Returns the CriticalSection that locks this array.
  6040. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6041. an object of ScopedLockType as an RAII lock for it.
  6042. */
  6043. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  6044. /** Returns the type of scoped lock to use for locking this array */
  6045. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6046. private:
  6047. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  6048. int numUsed;
  6049. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  6050. };
  6051. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  6052. /*** End of inlined file: juce_OwnedArray.h ***/
  6053. #endif
  6054. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6055. /*** Start of inlined file: juce_PropertySet.h ***/
  6056. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6057. #define __JUCE_PROPERTYSET_JUCEHEADER__
  6058. /*** Start of inlined file: juce_StringPairArray.h ***/
  6059. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6060. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6061. /*** Start of inlined file: juce_StringArray.h ***/
  6062. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  6063. #define __JUCE_STRINGARRAY_JUCEHEADER__
  6064. /**
  6065. A special array for holding a list of strings.
  6066. @see String, StringPairArray
  6067. */
  6068. class JUCE_API StringArray
  6069. {
  6070. public:
  6071. /** Creates an empty string array */
  6072. StringArray() throw();
  6073. /** Creates a copy of another string array */
  6074. StringArray (const StringArray& other);
  6075. /** Creates an array containing a single string. */
  6076. explicit StringArray (const String& firstValue);
  6077. /** Creates a copy of an array of string literals.
  6078. @param strings an array of strings to add. Null pointers in the array will be
  6079. treated as empty strings
  6080. @param numberOfStrings how many items there are in the array
  6081. */
  6082. StringArray (const juce_wchar* const* strings, int numberOfStrings);
  6083. /** Creates a copy of an array of string literals.
  6084. @param strings an array of strings to add. Null pointers in the array will be
  6085. treated as empty strings
  6086. @param numberOfStrings how many items there are in the array
  6087. */
  6088. StringArray (const char* const* strings, int numberOfStrings);
  6089. /** Creates a copy of a null-terminated array of string literals.
  6090. Each item from the array passed-in is added, until it encounters a null pointer,
  6091. at which point it stops.
  6092. */
  6093. explicit StringArray (const juce_wchar* const* strings);
  6094. /** Creates a copy of a null-terminated array of string literals.
  6095. Each item from the array passed-in is added, until it encounters a null pointer,
  6096. at which point it stops.
  6097. */
  6098. explicit StringArray (const char* const* strings);
  6099. /** Destructor. */
  6100. ~StringArray();
  6101. /** Copies the contents of another string array into this one */
  6102. StringArray& operator= (const StringArray& other);
  6103. /** Compares two arrays.
  6104. Comparisons are case-sensitive.
  6105. @returns true only if the other array contains exactly the same strings in the same order
  6106. */
  6107. bool operator== (const StringArray& other) const throw();
  6108. /** Compares two arrays.
  6109. Comparisons are case-sensitive.
  6110. @returns false if the other array contains exactly the same strings in the same order
  6111. */
  6112. bool operator!= (const StringArray& other) const throw();
  6113. /** Returns the number of strings in the array */
  6114. inline int size() const throw() { return strings.size(); };
  6115. /** Returns one of the strings from the array.
  6116. If the index is out-of-range, an empty string is returned.
  6117. Obviously the reference returned shouldn't be stored for later use, as the
  6118. string it refers to may disappear when the array changes.
  6119. */
  6120. const String& operator[] (int index) const throw();
  6121. /** Returns a reference to one of the strings in the array.
  6122. This lets you modify a string in-place in the array, but you must be sure that
  6123. the index is in-range.
  6124. */
  6125. String& getReference (int index) throw();
  6126. /** Searches for a string in the array.
  6127. The comparison will be case-insensitive if the ignoreCase parameter is true.
  6128. @returns true if the string is found inside the array
  6129. */
  6130. bool contains (const String& stringToLookFor,
  6131. bool ignoreCase = false) const;
  6132. /** Searches for a string in the array.
  6133. The comparison will be case-insensitive if the ignoreCase parameter is true.
  6134. @param stringToLookFor the string to try to find
  6135. @param ignoreCase whether the comparison should be case-insensitive
  6136. @param startIndex the first index to start searching from
  6137. @returns the index of the first occurrence of the string in this array,
  6138. or -1 if it isn't found.
  6139. */
  6140. int indexOf (const String& stringToLookFor,
  6141. bool ignoreCase = false,
  6142. int startIndex = 0) const;
  6143. /** Appends a string at the end of the array. */
  6144. void add (const String& stringToAdd);
  6145. /** Inserts a string into the array.
  6146. This will insert a string into the array at the given index, moving
  6147. up the other elements to make room for it.
  6148. If the index is less than zero or greater than the size of the array,
  6149. the new string will be added to the end of the array.
  6150. */
  6151. void insert (int index, const String& stringToAdd);
  6152. /** Adds a string to the array as long as it's not already in there.
  6153. The search can optionally be case-insensitive.
  6154. */
  6155. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  6156. /** Replaces one of the strings in the array with another one.
  6157. If the index is higher than the array's size, the new string will be
  6158. added to the end of the array; if it's less than zero nothing happens.
  6159. */
  6160. void set (int index, const String& newString);
  6161. /** Appends some strings from another array to the end of this one.
  6162. @param other the array to add
  6163. @param startIndex the first element of the other array to add
  6164. @param numElementsToAdd the maximum number of elements to add (if this is
  6165. less than zero, they are all added)
  6166. */
  6167. void addArray (const StringArray& other,
  6168. int startIndex = 0,
  6169. int numElementsToAdd = -1);
  6170. /** Breaks up a string into tokens and adds them to this array.
  6171. This will tokenise the given string using whitespace characters as the
  6172. token delimiters, and will add these tokens to the end of the array.
  6173. @returns the number of tokens added
  6174. */
  6175. int addTokens (const String& stringToTokenise,
  6176. bool preserveQuotedStrings);
  6177. /** Breaks up a string into tokens and adds them to this array.
  6178. This will tokenise the given string (using the string passed in to define the
  6179. token delimiters), and will add these tokens to the end of the array.
  6180. @param stringToTokenise the string to tokenise
  6181. @param breakCharacters a string of characters, any of which will be considered
  6182. to be a token delimiter.
  6183. @param quoteCharacters if this string isn't empty, it defines a set of characters
  6184. which are treated as quotes. Any text occurring
  6185. between quotes is not broken up into tokens.
  6186. @returns the number of tokens added
  6187. */
  6188. int addTokens (const String& stringToTokenise,
  6189. const String& breakCharacters,
  6190. const String& quoteCharacters);
  6191. /** Breaks up a string into lines and adds them to this array.
  6192. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  6193. to the array. Line-break characters are omitted from the strings that are added to
  6194. the array.
  6195. */
  6196. int addLines (const String& stringToBreakUp);
  6197. /** Removes all elements from the array. */
  6198. void clear();
  6199. /** Removes a string from the array.
  6200. If the index is out-of-range, no action will be taken.
  6201. */
  6202. void remove (int index);
  6203. /** Finds a string in the array and removes it.
  6204. This will remove the first occurrence of the given string from the array. The
  6205. comparison may be case-insensitive depending on the ignoreCase parameter.
  6206. */
  6207. void removeString (const String& stringToRemove,
  6208. bool ignoreCase = false);
  6209. /** Removes a range of elements from the array.
  6210. This will remove a set of elements, starting from the given index,
  6211. and move subsequent elements down to close the gap.
  6212. If the range extends beyond the bounds of the array, it will
  6213. be safely clipped to the size of the array.
  6214. @param startIndex the index of the first element to remove
  6215. @param numberToRemove how many elements should be removed
  6216. */
  6217. void removeRange (int startIndex, int numberToRemove);
  6218. /** Removes any duplicated elements from the array.
  6219. If any string appears in the array more than once, only the first occurrence of
  6220. it will be retained.
  6221. @param ignoreCase whether to use a case-insensitive comparison
  6222. */
  6223. void removeDuplicates (bool ignoreCase);
  6224. /** Removes empty strings from the array.
  6225. @param removeWhitespaceStrings if true, strings that only contain whitespace
  6226. characters will also be removed
  6227. */
  6228. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  6229. /** Moves one of the strings to a different position.
  6230. This will move the string to a specified index, shuffling along
  6231. any intervening elements as required.
  6232. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  6233. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  6234. @param currentIndex the index of the value to be moved. If this isn't a
  6235. valid index, then nothing will be done
  6236. @param newIndex the index at which you'd like this value to end up. If this
  6237. is less than zero, the value will be moved to the end
  6238. of the array
  6239. */
  6240. void move (int currentIndex, int newIndex) throw();
  6241. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  6242. void trim();
  6243. /** Adds numbers to the strings in the array, to make each string unique.
  6244. This will add numbers to the ends of groups of similar strings.
  6245. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  6246. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  6247. @param appendNumberToFirstInstance whether the first of a group of similar strings
  6248. also has a number appended to it.
  6249. @param preNumberString when adding a number, this string is added before the number.
  6250. If you pass 0, a default string will be used, which adds
  6251. brackets around the number.
  6252. @param postNumberString this string is appended after any numbers that are added.
  6253. If you pass 0, a default string will be used, which adds
  6254. brackets around the number.
  6255. */
  6256. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  6257. bool appendNumberToFirstInstance,
  6258. const juce_wchar* preNumberString = 0,
  6259. const juce_wchar* postNumberString = 0);
  6260. /** Joins the strings in the array together into one string.
  6261. This will join a range of elements from the array into a string, separating
  6262. them with a given string.
  6263. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  6264. @param separatorString the string to insert between all the strings
  6265. @param startIndex the first element to join
  6266. @param numberOfElements how many elements to join together. If this is less
  6267. than zero, all available elements will be used.
  6268. */
  6269. const String joinIntoString (const String& separatorString,
  6270. int startIndex = 0,
  6271. int numberOfElements = -1) const;
  6272. /** Sorts the array into alphabetical order.
  6273. @param ignoreCase if true, the comparisons used will be case-sensitive.
  6274. */
  6275. void sort (bool ignoreCase);
  6276. /** Reduces the amount of storage being used by the array.
  6277. Arrays typically allocate slightly more storage than they need, and after
  6278. removing elements, they may have quite a lot of unused space allocated.
  6279. This method will reduce the amount of allocated storage to a minimum.
  6280. */
  6281. void minimiseStorageOverheads();
  6282. private:
  6283. Array <String> strings;
  6284. JUCE_LEAK_DETECTOR (StringArray);
  6285. };
  6286. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  6287. /*** End of inlined file: juce_StringArray.h ***/
  6288. /**
  6289. A container for holding a set of strings which are keyed by another string.
  6290. @see StringArray
  6291. */
  6292. class JUCE_API StringPairArray
  6293. {
  6294. public:
  6295. /** Creates an empty array */
  6296. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  6297. /** Creates a copy of another array */
  6298. StringPairArray (const StringPairArray& other);
  6299. /** Destructor. */
  6300. ~StringPairArray();
  6301. /** Copies the contents of another string array into this one */
  6302. StringPairArray& operator= (const StringPairArray& other);
  6303. /** Compares two arrays.
  6304. Comparisons are case-sensitive.
  6305. @returns true only if the other array contains exactly the same strings with the same keys
  6306. */
  6307. bool operator== (const StringPairArray& other) const;
  6308. /** Compares two arrays.
  6309. Comparisons are case-sensitive.
  6310. @returns false if the other array contains exactly the same strings with the same keys
  6311. */
  6312. bool operator!= (const StringPairArray& other) const;
  6313. /** Finds the value corresponding to a key string.
  6314. If no such key is found, this will just return an empty string. To check whether
  6315. a given key actually exists (because it might actually be paired with an empty string), use
  6316. the getAllKeys() method to obtain a list.
  6317. Obviously the reference returned shouldn't be stored for later use, as the
  6318. string it refers to may disappear when the array changes.
  6319. @see getValue
  6320. */
  6321. const String& operator[] (const String& key) const;
  6322. /** Finds the value corresponding to a key string.
  6323. If no such key is found, this will just return the value provided as a default.
  6324. @see operator[]
  6325. */
  6326. const String getValue (const String& key, const String& defaultReturnValue) const;
  6327. /** Returns a list of all keys in the array. */
  6328. const StringArray& getAllKeys() const throw() { return keys; }
  6329. /** Returns a list of all values in the array. */
  6330. const StringArray& getAllValues() const throw() { return values; }
  6331. /** Returns the number of strings in the array */
  6332. inline int size() const throw() { return keys.size(); };
  6333. /** Adds or amends a key/value pair.
  6334. If a value already exists with this key, its value will be overwritten,
  6335. otherwise the key/value pair will be added to the array.
  6336. */
  6337. void set (const String& key, const String& value);
  6338. /** Adds the items from another array to this one.
  6339. This is equivalent to using set() to add each of the pairs from the other array.
  6340. */
  6341. void addArray (const StringPairArray& other);
  6342. /** Removes all elements from the array. */
  6343. void clear();
  6344. /** Removes a string from the array based on its key.
  6345. If the key isn't found, nothing will happen.
  6346. */
  6347. void remove (const String& key);
  6348. /** Removes a string from the array based on its index.
  6349. If the index is out-of-range, no action will be taken.
  6350. */
  6351. void remove (int index);
  6352. /** Indicates whether to use a case-insensitive search when looking up a key string.
  6353. */
  6354. void setIgnoresCase (bool shouldIgnoreCase);
  6355. /** Returns a descriptive string containing the items.
  6356. This is handy for dumping the contents of an array.
  6357. */
  6358. const String getDescription() const;
  6359. /** Reduces the amount of storage being used by the array.
  6360. Arrays typically allocate slightly more storage than they need, and after
  6361. removing elements, they may have quite a lot of unused space allocated.
  6362. This method will reduce the amount of allocated storage to a minimum.
  6363. */
  6364. void minimiseStorageOverheads();
  6365. private:
  6366. StringArray keys, values;
  6367. bool ignoreCase;
  6368. JUCE_LEAK_DETECTOR (StringPairArray);
  6369. };
  6370. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6371. /*** End of inlined file: juce_StringPairArray.h ***/
  6372. /*** Start of inlined file: juce_XmlElement.h ***/
  6373. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  6374. #define __JUCE_XMLELEMENT_JUCEHEADER__
  6375. /*** Start of inlined file: juce_File.h ***/
  6376. #ifndef __JUCE_FILE_JUCEHEADER__
  6377. #define __JUCE_FILE_JUCEHEADER__
  6378. /*** Start of inlined file: juce_Time.h ***/
  6379. #ifndef __JUCE_TIME_JUCEHEADER__
  6380. #define __JUCE_TIME_JUCEHEADER__
  6381. /*** Start of inlined file: juce_RelativeTime.h ***/
  6382. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  6383. #define __JUCE_RELATIVETIME_JUCEHEADER__
  6384. /** A relative measure of time.
  6385. The time is stored as a number of seconds, at double-precision floating
  6386. point accuracy, and may be positive or negative.
  6387. If you need an absolute time, (i.e. a date + time), see the Time class.
  6388. */
  6389. class JUCE_API RelativeTime
  6390. {
  6391. public:
  6392. /** Creates a RelativeTime.
  6393. @param seconds the number of seconds, which may be +ve or -ve.
  6394. @see milliseconds, minutes, hours, days, weeks
  6395. */
  6396. explicit RelativeTime (double seconds = 0.0) throw();
  6397. /** Copies another relative time. */
  6398. RelativeTime (const RelativeTime& other) throw();
  6399. /** Copies another relative time. */
  6400. RelativeTime& operator= (const RelativeTime& other) throw();
  6401. /** Destructor. */
  6402. ~RelativeTime() throw();
  6403. /** Creates a new RelativeTime object representing a number of milliseconds.
  6404. @see minutes, hours, days, weeks
  6405. */
  6406. static const RelativeTime milliseconds (int milliseconds) throw();
  6407. /** Creates a new RelativeTime object representing a number of milliseconds.
  6408. @see minutes, hours, days, weeks
  6409. */
  6410. static const RelativeTime milliseconds (int64 milliseconds) throw();
  6411. /** Creates a new RelativeTime object representing a number of minutes.
  6412. @see milliseconds, hours, days, weeks
  6413. */
  6414. static const RelativeTime minutes (double numberOfMinutes) throw();
  6415. /** Creates a new RelativeTime object representing a number of hours.
  6416. @see milliseconds, minutes, days, weeks
  6417. */
  6418. static const RelativeTime hours (double numberOfHours) throw();
  6419. /** Creates a new RelativeTime object representing a number of days.
  6420. @see milliseconds, minutes, hours, weeks
  6421. */
  6422. static const RelativeTime days (double numberOfDays) throw();
  6423. /** Creates a new RelativeTime object representing a number of weeks.
  6424. @see milliseconds, minutes, hours, days
  6425. */
  6426. static const RelativeTime weeks (double numberOfWeeks) throw();
  6427. /** Returns the number of milliseconds this time represents.
  6428. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6429. */
  6430. int64 inMilliseconds() const throw();
  6431. /** Returns the number of seconds this time represents.
  6432. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  6433. */
  6434. double inSeconds() const throw() { return seconds; }
  6435. /** Returns the number of minutes this time represents.
  6436. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  6437. */
  6438. double inMinutes() const throw();
  6439. /** Returns the number of hours this time represents.
  6440. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  6441. */
  6442. double inHours() const throw();
  6443. /** Returns the number of days this time represents.
  6444. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  6445. */
  6446. double inDays() const throw();
  6447. /** Returns the number of weeks this time represents.
  6448. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  6449. */
  6450. double inWeeks() const throw();
  6451. /** Returns a readable textual description of the time.
  6452. The exact format of the string returned will depend on
  6453. the magnitude of the time - e.g.
  6454. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  6455. so that only the two most significant units are printed.
  6456. The returnValueForZeroTime value is the result that is returned if the
  6457. length is zero. Depending on your application you might want to use this
  6458. to return something more relevant like "empty" or "0 secs", etc.
  6459. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6460. */
  6461. const String getDescription (const String& returnValueForZeroTime = "0") const;
  6462. /** Adds another RelativeTime to this one. */
  6463. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  6464. /** Subtracts another RelativeTime from this one. */
  6465. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  6466. /** Adds a number of seconds to this time. */
  6467. const RelativeTime& operator+= (double secondsToAdd) throw();
  6468. /** Subtracts a number of seconds from this time. */
  6469. const RelativeTime& operator-= (double secondsToSubtract) throw();
  6470. private:
  6471. double seconds;
  6472. };
  6473. /** Compares two RelativeTimes. */
  6474. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw();
  6475. /** Compares two RelativeTimes. */
  6476. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw();
  6477. /** Compares two RelativeTimes. */
  6478. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw();
  6479. /** Compares two RelativeTimes. */
  6480. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw();
  6481. /** Compares two RelativeTimes. */
  6482. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw();
  6483. /** Compares two RelativeTimes. */
  6484. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw();
  6485. /** Adds two RelativeTimes together. */
  6486. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw();
  6487. /** Subtracts two RelativeTimes. */
  6488. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw();
  6489. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  6490. /*** End of inlined file: juce_RelativeTime.h ***/
  6491. /**
  6492. Holds an absolute date and time.
  6493. Internally, the time is stored at millisecond precision.
  6494. @see RelativeTime
  6495. */
  6496. class JUCE_API Time
  6497. {
  6498. public:
  6499. /** Creates a Time object.
  6500. This default constructor creates a time of 1st January 1970, (which is
  6501. represented internally as 0ms).
  6502. To create a time object representing the current time, use getCurrentTime().
  6503. @see getCurrentTime
  6504. */
  6505. Time() throw();
  6506. /** Creates a time based on a number of milliseconds.
  6507. The internal millisecond count is set to 0 (1st January 1970). To create a
  6508. time object set to the current time, use getCurrentTime().
  6509. @param millisecondsSinceEpoch the number of milliseconds since the unix
  6510. 'epoch' (midnight Jan 1st 1970).
  6511. @see getCurrentTime, currentTimeMillis
  6512. */
  6513. explicit Time (int64 millisecondsSinceEpoch) throw();
  6514. /** Creates a time from a set of date components.
  6515. The timezone is assumed to be whatever the system is using as its locale.
  6516. @param year the year, in 4-digit format, e.g. 2004
  6517. @param month the month, in the range 0 to 11
  6518. @param day the day of the month, in the range 1 to 31
  6519. @param hours hours in 24-hour clock format, 0 to 23
  6520. @param minutes minutes 0 to 59
  6521. @param seconds seconds 0 to 59
  6522. @param milliseconds milliseconds 0 to 999
  6523. @param useLocalTime if true, encode using the current machine's local time; if
  6524. false, it will always work in GMT.
  6525. */
  6526. Time (int year,
  6527. int month,
  6528. int day,
  6529. int hours,
  6530. int minutes,
  6531. int seconds = 0,
  6532. int milliseconds = 0,
  6533. bool useLocalTime = true) throw();
  6534. /** Creates a copy of another Time object. */
  6535. Time (const Time& other) throw();
  6536. /** Destructor. */
  6537. ~Time() throw();
  6538. /** Copies this time from another one. */
  6539. Time& operator= (const Time& other) throw();
  6540. /** Returns a Time object that is set to the current system time.
  6541. @see currentTimeMillis
  6542. */
  6543. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  6544. /** Returns the time as a number of milliseconds.
  6545. @returns the number of milliseconds this Time object represents, since
  6546. midnight jan 1st 1970.
  6547. @see getMilliseconds
  6548. */
  6549. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  6550. /** Returns the year.
  6551. A 4-digit format is used, e.g. 2004.
  6552. */
  6553. int getYear() const throw();
  6554. /** Returns the number of the month.
  6555. The value returned is in the range 0 to 11.
  6556. @see getMonthName
  6557. */
  6558. int getMonth() const throw();
  6559. /** Returns the name of the month.
  6560. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6561. it'll return the long form, e.g. "January"
  6562. @see getMonth
  6563. */
  6564. const String getMonthName (bool threeLetterVersion) const;
  6565. /** Returns the day of the month.
  6566. The value returned is in the range 1 to 31.
  6567. */
  6568. int getDayOfMonth() const throw();
  6569. /** Returns the number of the day of the week.
  6570. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  6571. */
  6572. int getDayOfWeek() const throw();
  6573. /** Returns the name of the weekday.
  6574. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6575. false, it'll return the full version, e.g. "Tuesday".
  6576. */
  6577. const String getWeekdayName (bool threeLetterVersion) const;
  6578. /** Returns the number of hours since midnight.
  6579. This is in 24-hour clock format, in the range 0 to 23.
  6580. @see getHoursInAmPmFormat, isAfternoon
  6581. */
  6582. int getHours() const throw();
  6583. /** Returns true if the time is in the afternoon.
  6584. So it returns true for "PM", false for "AM".
  6585. @see getHoursInAmPmFormat, getHours
  6586. */
  6587. bool isAfternoon() const throw();
  6588. /** Returns the hours in 12-hour clock format.
  6589. This will return a value 1 to 12 - use isAfternoon() to find out
  6590. whether this is in the afternoon or morning.
  6591. @see getHours, isAfternoon
  6592. */
  6593. int getHoursInAmPmFormat() const throw();
  6594. /** Returns the number of minutes, 0 to 59. */
  6595. int getMinutes() const throw();
  6596. /** Returns the number of seconds, 0 to 59. */
  6597. int getSeconds() const throw();
  6598. /** Returns the number of milliseconds, 0 to 999.
  6599. Unlike toMilliseconds(), this just returns the position within the
  6600. current second rather than the total number since the epoch.
  6601. @see toMilliseconds
  6602. */
  6603. int getMilliseconds() const throw();
  6604. /** Returns true if the local timezone uses a daylight saving correction. */
  6605. bool isDaylightSavingTime() const throw();
  6606. /** Returns a 3-character string to indicate the local timezone. */
  6607. const String getTimeZone() const throw();
  6608. /** Quick way of getting a string version of a date and time.
  6609. For a more powerful way of formatting the date and time, see the formatted() method.
  6610. @param includeDate whether to include the date in the string
  6611. @param includeTime whether to include the time in the string
  6612. @param includeSeconds if the time is being included, this provides an option not to include
  6613. the seconds in it
  6614. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  6615. hour notation.
  6616. @see formatted
  6617. */
  6618. const String toString (bool includeDate,
  6619. bool includeTime,
  6620. bool includeSeconds = true,
  6621. bool use24HourClock = false) const throw();
  6622. /** Converts this date/time to a string with a user-defined format.
  6623. This uses the C strftime() function to format this time as a string. To save you
  6624. looking it up, these are the escape codes that strftime uses (other codes might
  6625. work on some platforms and not others, but these are the common ones):
  6626. %a is replaced by the locale's abbreviated weekday name.
  6627. %A is replaced by the locale's full weekday name.
  6628. %b is replaced by the locale's abbreviated month name.
  6629. %B is replaced by the locale's full month name.
  6630. %c is replaced by the locale's appropriate date and time representation.
  6631. %d is replaced by the day of the month as a decimal number [01,31].
  6632. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  6633. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  6634. %j is replaced by the day of the year as a decimal number [001,366].
  6635. %m is replaced by the month as a decimal number [01,12].
  6636. %M is replaced by the minute as a decimal number [00,59].
  6637. %p is replaced by the locale's equivalent of either a.m. or p.m.
  6638. %S is replaced by the second as a decimal number [00,61].
  6639. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  6640. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  6641. %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.
  6642. %x is replaced by the locale's appropriate date representation.
  6643. %X is replaced by the locale's appropriate time representation.
  6644. %y is replaced by the year without century as a decimal number [00,99].
  6645. %Y is replaced by the year with century as a decimal number.
  6646. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  6647. %% is replaced by %.
  6648. @see toString
  6649. */
  6650. const String formatted (const String& format) const;
  6651. /** Adds a RelativeTime to this time. */
  6652. Time& operator+= (const RelativeTime& delta);
  6653. /** Subtracts a RelativeTime from this time. */
  6654. Time& operator-= (const RelativeTime& delta);
  6655. /** Tries to set the computer's clock.
  6656. @returns true if this succeeds, although depending on the system, the
  6657. application might not have sufficient privileges to do this.
  6658. */
  6659. bool setSystemTimeToThisTime() const;
  6660. /** Returns the name of a day of the week.
  6661. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  6662. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6663. false, it'll return the full version, e.g. "Tuesday".
  6664. */
  6665. static const String getWeekdayName (int dayNumber,
  6666. bool threeLetterVersion);
  6667. /** Returns the name of one of the months.
  6668. @param monthNumber the month, 0 to 11
  6669. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6670. it'll return the long form, e.g. "January"
  6671. */
  6672. static const String getMonthName (int monthNumber,
  6673. bool threeLetterVersion);
  6674. // Static methods for getting system timers directly..
  6675. /** Returns the current system time.
  6676. Returns the number of milliseconds since midnight jan 1st 1970.
  6677. Should be accurate to within a few millisecs, depending on platform,
  6678. hardware, etc.
  6679. */
  6680. static int64 currentTimeMillis() throw();
  6681. /** Returns the number of millisecs since a fixed event (usually system startup).
  6682. This returns a monotonically increasing value which it unaffected by changes to the
  6683. system clock. It should be accurate to within a few millisecs, depending on platform,
  6684. hardware, etc.
  6685. @see getApproximateMillisecondCounter
  6686. */
  6687. static uint32 getMillisecondCounter() throw();
  6688. /** Returns the number of millisecs since a fixed event (usually system startup).
  6689. This has the same function as getMillisecondCounter(), but returns a more accurate
  6690. value, using a higher-resolution timer if one is available.
  6691. @see getMillisecondCounter
  6692. */
  6693. static double getMillisecondCounterHiRes() throw();
  6694. /** Waits until the getMillisecondCounter() reaches a given value.
  6695. This will make the thread sleep as efficiently as it can while it's waiting.
  6696. */
  6697. static void waitForMillisecondCounter (uint32 targetTime) throw();
  6698. /** Less-accurate but faster version of getMillisecondCounter().
  6699. This will return the last value that getMillisecondCounter() returned, so doesn't
  6700. need to make a system call, but is less accurate - it shouldn't be more than
  6701. 100ms away from the correct time, though, so is still accurate enough for a
  6702. lot of purposes.
  6703. @see getMillisecondCounter
  6704. */
  6705. static uint32 getApproximateMillisecondCounter() throw();
  6706. // High-resolution timers..
  6707. /** Returns the current high-resolution counter's tick-count.
  6708. This is a similar idea to getMillisecondCounter(), but with a higher
  6709. resolution.
  6710. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  6711. secondsToHighResolutionTicks
  6712. */
  6713. static int64 getHighResolutionTicks() throw();
  6714. /** Returns the resolution of the high-resolution counter in ticks per second.
  6715. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  6716. secondsToHighResolutionTicks
  6717. */
  6718. static int64 getHighResolutionTicksPerSecond() throw();
  6719. /** Converts a number of high-resolution ticks into seconds.
  6720. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6721. secondsToHighResolutionTicks
  6722. */
  6723. static double highResolutionTicksToSeconds (int64 ticks) throw();
  6724. /** Converts a number seconds into high-resolution ticks.
  6725. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6726. highResolutionTicksToSeconds
  6727. */
  6728. static int64 secondsToHighResolutionTicks (double seconds) throw();
  6729. private:
  6730. int64 millisSinceEpoch;
  6731. };
  6732. /** Adds a RelativeTime to a Time. */
  6733. const Time operator+ (const Time& time, const RelativeTime& delta);
  6734. /** Adds a RelativeTime to a Time. */
  6735. const Time operator+ (const RelativeTime& delta, const Time& time);
  6736. /** Subtracts a RelativeTime from a Time. */
  6737. const Time operator- (const Time& time, const RelativeTime& delta);
  6738. /** Returns the relative time difference between two times. */
  6739. const RelativeTime operator- (const Time& time1, const Time& time2);
  6740. /** Compares two Time objects. */
  6741. bool operator== (const Time& time1, const Time& time2);
  6742. /** Compares two Time objects. */
  6743. bool operator!= (const Time& time1, const Time& time2);
  6744. /** Compares two Time objects. */
  6745. bool operator< (const Time& time1, const Time& time2);
  6746. /** Compares two Time objects. */
  6747. bool operator<= (const Time& time1, const Time& time2);
  6748. /** Compares two Time objects. */
  6749. bool operator> (const Time& time1, const Time& time2);
  6750. /** Compares two Time objects. */
  6751. bool operator>= (const Time& time1, const Time& time2);
  6752. #endif // __JUCE_TIME_JUCEHEADER__
  6753. /*** End of inlined file: juce_Time.h ***/
  6754. /*** Start of inlined file: juce_ScopedPointer.h ***/
  6755. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  6756. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  6757. /**
  6758. This class holds a pointer which is automatically deleted when this object goes
  6759. out of scope.
  6760. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  6761. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  6762. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  6763. created objects.
  6764. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  6765. to an object. If you use the assignment operator to assign a different object to a
  6766. ScopedPointer, the old one will be automatically deleted.
  6767. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  6768. object to which it points during its lifetime. This means that making a copy of a const
  6769. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  6770. old one.
  6771. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  6772. can use the release() method.
  6773. */
  6774. template <class ObjectType>
  6775. class ScopedPointer
  6776. {
  6777. public:
  6778. /** Creates a ScopedPointer containing a null pointer. */
  6779. inline ScopedPointer() throw() : object (0)
  6780. {
  6781. }
  6782. /** Creates a ScopedPointer that owns the specified object. */
  6783. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  6784. : object (objectToTakePossessionOf)
  6785. {
  6786. }
  6787. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  6788. Because a pointer can only belong to one ScopedPointer, this transfers
  6789. the pointer from the other object to this one, and the other object is reset to
  6790. be a null pointer.
  6791. */
  6792. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  6793. : object (objectToTransferFrom.object)
  6794. {
  6795. objectToTransferFrom.object = 0;
  6796. }
  6797. /** Destructor.
  6798. This will delete the object that this ScopedPointer currently refers to.
  6799. */
  6800. inline ~ScopedPointer() { delete object; }
  6801. /** Changes this ScopedPointer to point to a new object.
  6802. Because a pointer can only belong to one ScopedPointer, this transfers
  6803. the pointer from the other object to this one, and the other object is reset to
  6804. be a null pointer.
  6805. If this ScopedPointer already points to an object, that object
  6806. will first be deleted.
  6807. */
  6808. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  6809. {
  6810. if (this != objectToTransferFrom.getAddress())
  6811. {
  6812. // Two ScopedPointers should never be able to refer to the same object - if
  6813. // this happens, you must have done something dodgy!
  6814. jassert (object == 0 || object != objectToTransferFrom.object);
  6815. ObjectType* const oldObject = object;
  6816. object = objectToTransferFrom.object;
  6817. objectToTransferFrom.object = 0;
  6818. delete oldObject;
  6819. }
  6820. return *this;
  6821. }
  6822. /** Changes this ScopedPointer to point to a new object.
  6823. If this ScopedPointer already points to an object, that object
  6824. will first be deleted.
  6825. The pointer that you pass is may be null.
  6826. */
  6827. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  6828. {
  6829. if (object != newObjectToTakePossessionOf)
  6830. {
  6831. ObjectType* const oldObject = object;
  6832. object = newObjectToTakePossessionOf;
  6833. delete oldObject;
  6834. }
  6835. return *this;
  6836. }
  6837. /** Returns the object that this ScopedPointer refers to.
  6838. */
  6839. inline operator ObjectType*() const throw() { return object; }
  6840. /** Returns the object that this ScopedPointer refers to.
  6841. */
  6842. inline ObjectType& operator*() const throw() { return *object; }
  6843. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  6844. inline ObjectType* operator->() const throw() { return object; }
  6845. /** Removes the current object from this ScopedPointer without deleting it.
  6846. This will return the current object, and set the ScopedPointer to a null pointer.
  6847. */
  6848. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  6849. /** Swaps this object with that of another ScopedPointer.
  6850. The two objects simply exchange their pointers.
  6851. */
  6852. void swapWith (ScopedPointer <ObjectType>& other) throw()
  6853. {
  6854. // Two ScopedPointers should never be able to refer to the same object - if
  6855. // this happens, you must have done something dodgy!
  6856. jassert (object != other.object);
  6857. swapVariables (object, other.object);
  6858. }
  6859. private:
  6860. ObjectType* object;
  6861. // (Required as an alternative to the overloaded & operator).
  6862. const ScopedPointer* getAddress() const throw() { return this; }
  6863. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  6864. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  6865. would let you do so by implicitly casting the source to its raw object pointer).
  6866. A side effect of this is that you may hit a puzzling compiler error when you write something
  6867. like this:
  6868. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  6869. Even though the compiler would normally ignore the assignment here, it can't do so when the
  6870. copy constructor is private. It's very easy to fis though - just write it like this:
  6871. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  6872. It's good practice to always use the latter form when writing your object declarations anyway,
  6873. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  6874. smart enough to replace your construction + assignment with a single constructor.
  6875. */
  6876. ScopedPointer (const ScopedPointer&);
  6877. #endif
  6878. };
  6879. /** Compares a ScopedPointer with another pointer.
  6880. This can be handy for checking whether this is a null pointer.
  6881. */
  6882. template <class ObjectType>
  6883. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  6884. {
  6885. return static_cast <ObjectType*> (pointer1) == pointer2;
  6886. }
  6887. /** Compares a ScopedPointer with another pointer.
  6888. This can be handy for checking whether this is a null pointer.
  6889. */
  6890. template <class ObjectType>
  6891. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  6892. {
  6893. return static_cast <ObjectType*> (pointer1) != pointer2;
  6894. }
  6895. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  6896. /*** End of inlined file: juce_ScopedPointer.h ***/
  6897. class FileInputStream;
  6898. class FileOutputStream;
  6899. /**
  6900. Represents a local file or directory.
  6901. This class encapsulates the absolute pathname of a file or directory, and
  6902. has methods for finding out about the file and changing its properties.
  6903. To read or write to the file, there are methods for returning an input or
  6904. output stream.
  6905. @see FileInputStream, FileOutputStream
  6906. */
  6907. class JUCE_API File
  6908. {
  6909. public:
  6910. /** Creates an (invalid) file object.
  6911. The file is initially set to an empty path, so getFullPath() will return
  6912. an empty string, and comparing the file to File::nonexistent will return
  6913. true.
  6914. You can use its operator= method to point it at a proper file.
  6915. */
  6916. File() {}
  6917. /** Creates a file from an absolute path.
  6918. If the path supplied is a relative path, it is taken to be relative
  6919. to the current working directory (see File::getCurrentWorkingDirectory()),
  6920. but this isn't a recommended way of creating a file, because you
  6921. never know what the CWD is going to be.
  6922. On the Mac/Linux, the path can include "~" notation for referring to
  6923. user home directories.
  6924. */
  6925. File (const String& path);
  6926. /** Creates a copy of another file object. */
  6927. File (const File& other);
  6928. /** Destructor. */
  6929. ~File() {}
  6930. /** Sets the file based on an absolute pathname.
  6931. If the path supplied is a relative path, it is taken to be relative
  6932. to the current working directory (see File::getCurrentWorkingDirectory()),
  6933. but this isn't a recommended way of creating a file, because you
  6934. never know what the CWD is going to be.
  6935. On the Mac/Linux, the path can include "~" notation for referring to
  6936. user home directories.
  6937. */
  6938. File& operator= (const String& newFilePath);
  6939. /** Copies from another file object. */
  6940. File& operator= (const File& otherFile);
  6941. /** This static constant is used for referring to an 'invalid' file. */
  6942. static const File nonexistent;
  6943. /** Checks whether the file actually exists.
  6944. @returns true if the file exists, either as a file or a directory.
  6945. @see existsAsFile, isDirectory
  6946. */
  6947. bool exists() const;
  6948. /** Checks whether the file exists and is a file rather than a directory.
  6949. @returns true only if this is a real file, false if it's a directory
  6950. or doesn't exist
  6951. @see exists, isDirectory
  6952. */
  6953. bool existsAsFile() const;
  6954. /** Checks whether the file is a directory that exists.
  6955. @returns true only if the file is a directory which actually exists, so
  6956. false if it's a file or doesn't exist at all
  6957. @see exists, existsAsFile
  6958. */
  6959. bool isDirectory() const;
  6960. /** Returns the size of the file in bytes.
  6961. @returns the number of bytes in the file, or 0 if it doesn't exist.
  6962. */
  6963. int64 getSize() const;
  6964. /** Utility function to convert a file size in bytes to a neat string description.
  6965. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  6966. 2000000 would produce "2 MB", etc.
  6967. */
  6968. static const String descriptionOfSizeInBytes (int64 bytes);
  6969. /** Returns the complete, absolute path of this file.
  6970. This includes the filename and all its parent folders. On Windows it'll
  6971. also include the drive letter prefix; on Mac or Linux it'll be a complete
  6972. path starting from the root folder.
  6973. If you just want the file's name, you should use getFileName() or
  6974. getFileNameWithoutExtension().
  6975. @see getFileName, getRelativePathFrom
  6976. */
  6977. const String& getFullPathName() const throw() { return fullPath; }
  6978. /** Returns the last section of the pathname.
  6979. Returns just the final part of the path - e.g. if the whole path
  6980. is "/moose/fish/foo.txt" this will return "foo.txt".
  6981. For a directory, it returns the final part of the path - e.g. for the
  6982. directory "/moose/fish" it'll return "fish".
  6983. If the filename begins with a dot, it'll return the whole filename, e.g. for
  6984. "/moose/.fish", it'll return ".fish"
  6985. @see getFullPathName, getFileNameWithoutExtension
  6986. */
  6987. const String getFileName() const;
  6988. /** Creates a relative path that refers to a file relatively to a given directory.
  6989. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  6990. would return "../../foo.txt".
  6991. If it's not possible to navigate from one file to the other, an absolute
  6992. path is returned. If the paths are invalid, an empty string may also be
  6993. returned.
  6994. @param directoryToBeRelativeTo the directory which the resultant string will
  6995. be relative to. If this is actually a file rather than
  6996. a directory, its parent directory will be used instead.
  6997. If it doesn't exist, it's assumed to be a directory.
  6998. @see getChildFile, isAbsolutePath
  6999. */
  7000. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  7001. /** Returns the file's extension.
  7002. Returns the file extension of this file, also including the dot.
  7003. e.g. "/moose/fish/foo.txt" would return ".txt"
  7004. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  7005. */
  7006. const String getFileExtension() const;
  7007. /** Checks whether the file has a given extension.
  7008. @param extensionToTest the extension to look for - it doesn't matter whether or
  7009. not this string has a dot at the start, so ".wav" and "wav"
  7010. will have the same effect. The comparison used is
  7011. case-insensitve. To compare with multiple extensions, this
  7012. parameter can contain multiple strings, separated by semi-colons -
  7013. so, for example: hasFileExtension (".jpeg;png;gif") would return
  7014. true if the file has any of those three extensions.
  7015. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  7016. */
  7017. bool hasFileExtension (const String& extensionToTest) const;
  7018. /** Returns a version of this file with a different file extension.
  7019. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  7020. @param newExtension the new extension, either with or without a dot at the start (this
  7021. doesn't make any difference). To get remove a file's extension altogether,
  7022. pass an empty string into this function.
  7023. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  7024. */
  7025. const File withFileExtension (const String& newExtension) const;
  7026. /** Returns the last part of the filename, without its file extension.
  7027. e.g. for "/moose/fish/foo.txt" this will return "foo".
  7028. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  7029. */
  7030. const String getFileNameWithoutExtension() const;
  7031. /** Returns a 32-bit hash-code that identifies this file.
  7032. This is based on the filename. Obviously it's possible, although unlikely, that
  7033. two files will have the same hash-code.
  7034. */
  7035. int hashCode() const;
  7036. /** Returns a 64-bit hash-code that identifies this file.
  7037. This is based on the filename. Obviously it's possible, although unlikely, that
  7038. two files will have the same hash-code.
  7039. */
  7040. int64 hashCode64() const;
  7041. /** Returns a file based on a relative path.
  7042. This will find a child file or directory of the current object.
  7043. e.g.
  7044. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  7045. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  7046. If the string is actually an absolute path, it will be treated as such, e.g.
  7047. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  7048. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  7049. */
  7050. const File getChildFile (String relativePath) const;
  7051. /** Returns a file which is in the same directory as this one.
  7052. This is equivalent to getParentDirectory().getChildFile (name).
  7053. @see getChildFile, getParentDirectory
  7054. */
  7055. const File getSiblingFile (const String& siblingFileName) const;
  7056. /** Returns the directory that contains this file or directory.
  7057. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  7058. */
  7059. const File getParentDirectory() const;
  7060. /** Checks whether a file is somewhere inside a directory.
  7061. Returns true if this file is somewhere inside a subdirectory of the directory
  7062. that is passed in. Neither file actually has to exist, because the function
  7063. just checks the paths for similarities.
  7064. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  7065. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  7066. */
  7067. bool isAChildOf (const File& potentialParentDirectory) const;
  7068. /** Chooses a filename relative to this one that doesn't already exist.
  7069. If this file is a directory, this will return a child file of this
  7070. directory that doesn't exist, by adding numbers to a prefix and suffix until
  7071. it finds one that isn't already there.
  7072. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  7073. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  7074. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  7075. @param prefix the string to use for the filename before the number
  7076. @param suffix the string to add to the filename after the number
  7077. @param putNumbersInBrackets if true, this will create filenames in the
  7078. format "prefix(number)suffix", if false, it will leave the
  7079. brackets out.
  7080. */
  7081. const File getNonexistentChildFile (const String& prefix,
  7082. const String& suffix,
  7083. bool putNumbersInBrackets = true) const;
  7084. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  7085. If this file doesn't exist, this will just return itself, otherwise it
  7086. will return an appropriate sibling that doesn't exist, e.g. if a file
  7087. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  7088. @param putNumbersInBrackets whether to add brackets around the numbers that
  7089. get appended to the new filename.
  7090. */
  7091. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  7092. /** Compares the pathnames for two files. */
  7093. bool operator== (const File& otherFile) const;
  7094. /** Compares the pathnames for two files. */
  7095. bool operator!= (const File& otherFile) const;
  7096. /** Compares the pathnames for two files. */
  7097. bool operator< (const File& otherFile) const;
  7098. /** Compares the pathnames for two files. */
  7099. bool operator> (const File& otherFile) const;
  7100. /** Checks whether a file can be created or written to.
  7101. @returns true if it's possible to create and write to this file. If the file
  7102. doesn't already exist, this will check its parent directory to
  7103. see if writing is allowed.
  7104. @see setReadOnly
  7105. */
  7106. bool hasWriteAccess() const;
  7107. /** Changes the write-permission of a file or directory.
  7108. @param shouldBeReadOnly whether to add or remove write-permission
  7109. @param applyRecursively if the file is a directory and this is true, it will
  7110. recurse through all the subfolders changing the permissions
  7111. of all files
  7112. @returns true if it manages to change the file's permissions.
  7113. @see hasWriteAccess
  7114. */
  7115. bool setReadOnly (bool shouldBeReadOnly,
  7116. bool applyRecursively = false) const;
  7117. /** Returns true if this file is a hidden or system file.
  7118. The criteria for deciding whether a file is hidden are platform-dependent.
  7119. */
  7120. bool isHidden() const;
  7121. /** If this file is a link, this returns the file that it points to.
  7122. If this file isn't actually link, it'll just return itself.
  7123. */
  7124. const File getLinkedTarget() const;
  7125. /** Returns the last modification time of this file.
  7126. @returns the time, or an invalid time if the file doesn't exist.
  7127. @see setLastModificationTime, getLastAccessTime, getCreationTime
  7128. */
  7129. const Time getLastModificationTime() const;
  7130. /** Returns the last time this file was accessed.
  7131. @returns the time, or an invalid time if the file doesn't exist.
  7132. @see setLastAccessTime, getLastModificationTime, getCreationTime
  7133. */
  7134. const Time getLastAccessTime() const;
  7135. /** Returns the time that this file was created.
  7136. @returns the time, or an invalid time if the file doesn't exist.
  7137. @see getLastModificationTime, getLastAccessTime
  7138. */
  7139. const Time getCreationTime() const;
  7140. /** Changes the modification time for this file.
  7141. @param newTime the time to apply to the file
  7142. @returns true if it manages to change the file's time.
  7143. @see getLastModificationTime, setLastAccessTime, setCreationTime
  7144. */
  7145. bool setLastModificationTime (const Time& newTime) const;
  7146. /** Changes the last-access time for this file.
  7147. @param newTime the time to apply to the file
  7148. @returns true if it manages to change the file's time.
  7149. @see getLastAccessTime, setLastModificationTime, setCreationTime
  7150. */
  7151. bool setLastAccessTime (const Time& newTime) const;
  7152. /** Changes the creation date for this file.
  7153. @param newTime the time to apply to the file
  7154. @returns true if it manages to change the file's time.
  7155. @see getCreationTime, setLastModificationTime, setLastAccessTime
  7156. */
  7157. bool setCreationTime (const Time& newTime) const;
  7158. /** If possible, this will try to create a version string for the given file.
  7159. The OS may be able to look at the file and give a version for it - e.g. with
  7160. executables, bundles, dlls, etc. If no version is available, this will
  7161. return an empty string.
  7162. */
  7163. const String getVersion() const;
  7164. /** Creates an empty file if it doesn't already exist.
  7165. If the file that this object refers to doesn't exist, this will create a file
  7166. of zero size.
  7167. If it already exists or is a directory, this method will do nothing.
  7168. @returns true if the file has been created (or if it already existed).
  7169. @see createDirectory
  7170. */
  7171. bool create() const;
  7172. /** Creates a new directory for this filename.
  7173. This will try to create the file as a directory, and fill also create
  7174. any parent directories it needs in order to complete the operation.
  7175. @returns true if the directory has been created successfully, (or if it
  7176. already existed beforehand).
  7177. @see create
  7178. */
  7179. bool createDirectory() const;
  7180. /** Deletes a file.
  7181. If this file is actually a directory, it may not be deleted correctly if it
  7182. contains files. See deleteRecursively() as a better way of deleting directories.
  7183. @returns true if the file has been successfully deleted (or if it didn't exist to
  7184. begin with).
  7185. @see deleteRecursively
  7186. */
  7187. bool deleteFile() const;
  7188. /** Deletes a file or directory and all its subdirectories.
  7189. If this file is a directory, this will try to delete it and all its subfolders. If
  7190. it's just a file, it will just try to delete the file.
  7191. @returns true if the file and all its subfolders have been successfully deleted
  7192. (or if it didn't exist to begin with).
  7193. @see deleteFile
  7194. */
  7195. bool deleteRecursively() const;
  7196. /** Moves this file or folder to the trash.
  7197. @returns true if the operation succeeded. It could fail if the trash is full, or
  7198. if the file is write-protected, so you should check the return value
  7199. and act appropriately.
  7200. */
  7201. bool moveToTrash() const;
  7202. /** Moves or renames a file.
  7203. Tries to move a file to a different location.
  7204. If the target file already exists, this will attempt to delete it first, and
  7205. will fail if this can't be done.
  7206. Note that the destination file isn't the directory to put it in, it's the actual
  7207. filename that you want the new file to have.
  7208. @returns true if the operation succeeds
  7209. */
  7210. bool moveFileTo (const File& targetLocation) const;
  7211. /** Copies a file.
  7212. Tries to copy a file to a different location.
  7213. If the target file already exists, this will attempt to delete it first, and
  7214. will fail if this can't be done.
  7215. @returns true if the operation succeeds
  7216. */
  7217. bool copyFileTo (const File& targetLocation) const;
  7218. /** Copies a directory.
  7219. Tries to copy an entire directory, recursively.
  7220. If this file isn't a directory or if any target files can't be created, this
  7221. will return false.
  7222. @param newDirectory the directory that this one should be copied to. Note that this
  7223. is the name of the actual directory to create, not the directory
  7224. into which the new one should be placed, so there must be enough
  7225. write privileges to create it if it doesn't exist. Any files inside
  7226. it will be overwritten by similarly named ones that are copied.
  7227. */
  7228. bool copyDirectoryTo (const File& newDirectory) const;
  7229. /** Used in file searching, to specify whether to return files, directories, or both.
  7230. */
  7231. enum TypesOfFileToFind
  7232. {
  7233. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  7234. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  7235. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  7236. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  7237. };
  7238. /** Searches inside a directory for files matching a wildcard pattern.
  7239. Assuming that this file is a directory, this method will search it
  7240. for either files or subdirectories whose names match a filename pattern.
  7241. @param results an array to which File objects will be added for the
  7242. files that the search comes up with
  7243. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  7244. return files, directories, or both. If the ignoreHiddenFiles flag
  7245. is also added to this value, hidden files won't be returned
  7246. @param searchRecursively if true, all subdirectories will be recursed into to do
  7247. an exhaustive search
  7248. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  7249. @returns the number of results that have been found
  7250. @see getNumberOfChildFiles, DirectoryIterator
  7251. */
  7252. int findChildFiles (Array<File>& results,
  7253. int whatToLookFor,
  7254. bool searchRecursively,
  7255. const String& wildCardPattern = "*") const;
  7256. /** Searches inside a directory and counts how many files match a wildcard pattern.
  7257. Assuming that this file is a directory, this method will search it
  7258. for either files or subdirectories whose names match a filename pattern,
  7259. and will return the number of matches found.
  7260. This isn't a recursive call, and will only search this directory, not
  7261. its children.
  7262. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  7263. count files, directories, or both. If the ignoreHiddenFiles flag
  7264. is also added to this value, hidden files won't be counted
  7265. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  7266. @returns the number of matches found
  7267. @see findChildFiles, DirectoryIterator
  7268. */
  7269. int getNumberOfChildFiles (int whatToLookFor,
  7270. const String& wildCardPattern = "*") const;
  7271. /** Returns true if this file is a directory that contains one or more subdirectories.
  7272. @see isDirectory, findChildFiles
  7273. */
  7274. bool containsSubDirectories() const;
  7275. /** Creates a stream to read from this file.
  7276. @returns a stream that will read from this file (initially positioned at the
  7277. start of the file), or 0 if the file can't be opened for some reason
  7278. @see createOutputStream, loadFileAsData
  7279. */
  7280. FileInputStream* createInputStream() const;
  7281. /** Creates a stream to write to this file.
  7282. If the file exists, the stream that is returned will be positioned ready for
  7283. writing at the end of the file, so you might want to use deleteFile() first
  7284. to write to an empty file.
  7285. @returns a stream that will write to this file (initially positioned at the
  7286. end of the file), or 0 if the file can't be opened for some reason
  7287. @see createInputStream, appendData, appendText
  7288. */
  7289. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  7290. /** Loads a file's contents into memory as a block of binary data.
  7291. Of course, trying to load a very large file into memory will blow up, so
  7292. it's better to check first.
  7293. @param result the data block to which the file's contents should be appended - note
  7294. that if the memory block might already contain some data, you
  7295. might want to clear it first
  7296. @returns true if the file could all be read into memory
  7297. */
  7298. bool loadFileAsData (MemoryBlock& result) const;
  7299. /** Reads a file into memory as a string.
  7300. Attempts to load the entire file as a zero-terminated string.
  7301. This makes use of InputStream::readEntireStreamAsString, which should
  7302. automatically cope with unicode/acsii file formats.
  7303. */
  7304. const String loadFileAsString() const;
  7305. /** Appends a block of binary data to the end of the file.
  7306. This will try to write the given buffer to the end of the file.
  7307. @returns false if it can't write to the file for some reason
  7308. */
  7309. bool appendData (const void* dataToAppend,
  7310. int numberOfBytes) const;
  7311. /** Replaces this file's contents with a given block of data.
  7312. This will delete the file and replace it with the given data.
  7313. A nice feature of this method is that it's safe - instead of deleting
  7314. the file first and then re-writing it, it creates a new temporary file,
  7315. writes the data to that, and then moves the new file to replace the existing
  7316. file. This means that if the power gets pulled out or something crashes,
  7317. you're a lot less likely to end up with a corrupted or unfinished file..
  7318. Returns true if the operation succeeds, or false if it fails.
  7319. @see appendText
  7320. */
  7321. bool replaceWithData (const void* dataToWrite,
  7322. int numberOfBytes) const;
  7323. /** Appends a string to the end of the file.
  7324. This will try to append a text string to the file, as either 16-bit unicode
  7325. or 8-bit characters in the default system encoding.
  7326. It can also write the 'ff fe' unicode header bytes before the text to indicate
  7327. the endianness of the file.
  7328. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  7329. @see replaceWithText
  7330. */
  7331. bool appendText (const String& textToAppend,
  7332. bool asUnicode = false,
  7333. bool writeUnicodeHeaderBytes = false) const;
  7334. /** Replaces this file's contents with a given text string.
  7335. This will delete the file and replace it with the given text.
  7336. A nice feature of this method is that it's safe - instead of deleting
  7337. the file first and then re-writing it, it creates a new temporary file,
  7338. writes the text to that, and then moves the new file to replace the existing
  7339. file. This means that if the power gets pulled out or something crashes,
  7340. you're a lot less likely to end up with an empty file..
  7341. For an explanation of the parameters here, see the appendText() method.
  7342. Returns true if the operation succeeds, or false if it fails.
  7343. @see appendText
  7344. */
  7345. bool replaceWithText (const String& textToWrite,
  7346. bool asUnicode = false,
  7347. bool writeUnicodeHeaderBytes = false) const;
  7348. /** Attempts to scan the contents of this file and compare it to another file, returning
  7349. true if this is possible and they match byte-for-byte.
  7350. */
  7351. bool hasIdenticalContentTo (const File& other) const;
  7352. /** Creates a set of files to represent each file root.
  7353. e.g. on Windows this will create files for "c:\", "d:\" etc according
  7354. to which ones are available. On the Mac/Linux, this will probably
  7355. just add a single entry for "/".
  7356. */
  7357. static void findFileSystemRoots (Array<File>& results);
  7358. /** Finds the name of the drive on which this file lives.
  7359. @returns the volume label of the drive, or an empty string if this isn't possible
  7360. */
  7361. const String getVolumeLabel() const;
  7362. /** Returns the serial number of the volume on which this file lives.
  7363. @returns the serial number, or zero if there's a problem doing this
  7364. */
  7365. int getVolumeSerialNumber() const;
  7366. /** Returns the number of bytes free on the drive that this file lives on.
  7367. @returns the number of bytes free, or 0 if there's a problem finding this out
  7368. @see getVolumeTotalSize
  7369. */
  7370. int64 getBytesFreeOnVolume() const;
  7371. /** Returns the total size of the drive that contains this file.
  7372. @returns the total number of bytes that the volume can hold
  7373. @see getBytesFreeOnVolume
  7374. */
  7375. int64 getVolumeTotalSize() const;
  7376. /** Returns true if this file is on a CD or DVD drive. */
  7377. bool isOnCDRomDrive() const;
  7378. /** Returns true if this file is on a hard disk.
  7379. This will fail if it's a network drive, but will still be true for
  7380. removable hard-disks.
  7381. */
  7382. bool isOnHardDisk() const;
  7383. /** Returns true if this file is on a removable disk drive.
  7384. This might be a usb-drive, a CD-rom, or maybe a network drive.
  7385. */
  7386. bool isOnRemovableDrive() const;
  7387. /** Launches the file as a process.
  7388. - if the file is executable, this will run it.
  7389. - if it's a document of some kind, it will launch the document with its
  7390. default viewer application.
  7391. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  7392. @see revealToUser
  7393. */
  7394. bool startAsProcess (const String& parameters = String::empty) const;
  7395. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  7396. @see startAsProcess
  7397. */
  7398. void revealToUser() const;
  7399. /** A set of types of location that can be passed to the getSpecialLocation() method.
  7400. */
  7401. enum SpecialLocationType
  7402. {
  7403. /** The user's home folder. This is the same as using File ("~"). */
  7404. userHomeDirectory,
  7405. /** The user's default documents folder. On Windows, this might be the user's
  7406. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  7407. doesn't tend to have one of these, so it might just return their home folder.
  7408. */
  7409. userDocumentsDirectory,
  7410. /** The folder that contains the user's desktop objects. */
  7411. userDesktopDirectory,
  7412. /** The folder in which applications store their persistent user-specific settings.
  7413. On Windows, this might be "\Documents and Settings\username\Application Data".
  7414. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  7415. always create your own sub-folder to put them in, to avoid making a mess.
  7416. */
  7417. userApplicationDataDirectory,
  7418. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  7419. of the computer, rather than just the current user.
  7420. On the Mac it'll be "/Library", on Windows, it could be something like
  7421. "\Documents and Settings\All Users\Application Data".
  7422. Depending on the setup, this folder may be read-only.
  7423. */
  7424. commonApplicationDataDirectory,
  7425. /** The folder that should be used for temporary files.
  7426. Always delete them when you're finished, to keep the user's computer tidy!
  7427. */
  7428. tempDirectory,
  7429. /** Returns this application's executable file.
  7430. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  7431. host app.
  7432. On the mac this will return the unix binary, not the package folder - see
  7433. currentApplicationFile for that.
  7434. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  7435. file link, invokedExecutableFile will return the name of the link.
  7436. */
  7437. currentExecutableFile,
  7438. /** Returns this application's location.
  7439. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  7440. host app.
  7441. On the mac this will return the package folder (if it's in one), not the unix binary
  7442. that's inside it - compare with currentExecutableFile.
  7443. */
  7444. currentApplicationFile,
  7445. /** Returns the file that was invoked to launch this executable.
  7446. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  7447. will return the name of the link that was used, whereas currentExecutableFile will return
  7448. the actual location of the target executable.
  7449. */
  7450. invokedExecutableFile,
  7451. /** In a plugin, this will return the path of the host executable. */
  7452. hostApplicationPath,
  7453. /** The directory in which applications normally get installed.
  7454. So on windows, this would be something like "c:\program files", on the
  7455. Mac "/Applications", or "/usr" on linux.
  7456. */
  7457. globalApplicationsDirectory,
  7458. /** The most likely place where a user might store their music files.
  7459. */
  7460. userMusicDirectory,
  7461. /** The most likely place where a user might store their movie files.
  7462. */
  7463. userMoviesDirectory,
  7464. };
  7465. /** Finds the location of a special type of file or directory, such as a home folder or
  7466. documents folder.
  7467. @see SpecialLocationType
  7468. */
  7469. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  7470. /** Returns a temporary file in the system's temp directory.
  7471. This will try to return the name of a non-existent temp file.
  7472. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  7473. */
  7474. static const File createTempFile (const String& fileNameEnding);
  7475. /** Returns the current working directory.
  7476. @see setAsCurrentWorkingDirectory
  7477. */
  7478. static const File getCurrentWorkingDirectory();
  7479. /** Sets the current working directory to be this file.
  7480. For this to work the file must point to a valid directory.
  7481. @returns true if the current directory has been changed.
  7482. @see getCurrentWorkingDirectory
  7483. */
  7484. bool setAsCurrentWorkingDirectory() const;
  7485. /** The system-specific file separator character.
  7486. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  7487. */
  7488. static const juce_wchar separator;
  7489. /** The system-specific file separator character, as a string.
  7490. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  7491. */
  7492. static const String separatorString;
  7493. /** Removes illegal characters from a filename.
  7494. This will return a copy of the given string after removing characters
  7495. that are not allowed in a legal filename, and possibly shortening the
  7496. string if it's too long.
  7497. Because this will remove slashes, don't use it on an absolute pathname.
  7498. @see createLegalPathName
  7499. */
  7500. static const String createLegalFileName (const String& fileNameToFix);
  7501. /** Removes illegal characters from a pathname.
  7502. Similar to createLegalFileName(), but this won't remove slashes, so can
  7503. be used on a complete pathname.
  7504. @see createLegalFileName
  7505. */
  7506. static const String createLegalPathName (const String& pathNameToFix);
  7507. /** Indicates whether filenames are case-sensitive on the current operating system.
  7508. */
  7509. static bool areFileNamesCaseSensitive();
  7510. /** Returns true if the string seems to be a fully-specified absolute path.
  7511. */
  7512. static bool isAbsolutePath (const String& path);
  7513. /** Creates a file that simply contains this string, without doing the sanity-checking
  7514. that the normal constructors do.
  7515. Best to avoid this unless you really know what you're doing.
  7516. */
  7517. static const File createFileWithoutCheckingPath (const String& path);
  7518. /** Adds a separator character to the end of a path if it doesn't already have one. */
  7519. static const String addTrailingSeparator (const String& path);
  7520. private:
  7521. String fullPath;
  7522. // internal way of contructing a file without checking the path
  7523. friend class DirectoryIterator;
  7524. File (const String&, int);
  7525. const String getPathUpToLastSlash() const;
  7526. void createDirectoryInternal (const String& fileName) const;
  7527. bool copyInternal (const File& dest) const;
  7528. bool moveInternal (const File& dest) const;
  7529. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  7530. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  7531. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  7532. static const String parseAbsolutePath (const String& path);
  7533. JUCE_LEAK_DETECTOR (File);
  7534. };
  7535. #endif // __JUCE_FILE_JUCEHEADER__
  7536. /*** End of inlined file: juce_File.h ***/
  7537. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  7538. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7539. will be the name of a pointer to each child element.
  7540. E.g. @code
  7541. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7542. forEachXmlChildElement (*myParentXml, child)
  7543. {
  7544. if (child->hasTagName ("FOO"))
  7545. doSomethingWithXmlElement (child);
  7546. }
  7547. @endcode
  7548. @see forEachXmlChildElementWithTagName
  7549. */
  7550. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  7551. \
  7552. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  7553. childElementVariableName != 0; \
  7554. childElementVariableName = childElementVariableName->getNextElement())
  7555. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  7556. which have a specified tag.
  7557. This does the same job as the forEachXmlChildElement macro, but only for those
  7558. elements that have a particular tag name.
  7559. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7560. will be the name of a pointer to each child element. The requiredTagName is the
  7561. tag name to match.
  7562. E.g. @code
  7563. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7564. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  7565. {
  7566. // the child object is now guaranteed to be a <MYTAG> element..
  7567. doSomethingWithMYTAGElement (child);
  7568. }
  7569. @endcode
  7570. @see forEachXmlChildElement
  7571. */
  7572. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  7573. \
  7574. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  7575. childElementVariableName != 0; \
  7576. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  7577. /** Used to build a tree of elements representing an XML document.
  7578. An XML document can be parsed into a tree of XmlElements, each of which
  7579. represents an XML tag structure, and which may itself contain other
  7580. nested elements.
  7581. An XmlElement can also be converted back into a text document, and has
  7582. lots of useful methods for manipulating its attributes and sub-elements,
  7583. so XmlElements can actually be used as a handy general-purpose data
  7584. structure.
  7585. Here's an example of parsing some elements: @code
  7586. // check we're looking at the right kind of document..
  7587. if (myElement->hasTagName ("ANIMALS"))
  7588. {
  7589. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  7590. forEachXmlChildElement (*myElement, e)
  7591. {
  7592. if (e->hasTagName ("GIRAFFE"))
  7593. {
  7594. // found a giraffe, so use some of its attributes..
  7595. String giraffeName = e->getStringAttribute ("name");
  7596. int giraffeAge = e->getIntAttribute ("age");
  7597. bool isFriendly = e->getBoolAttribute ("friendly");
  7598. }
  7599. }
  7600. }
  7601. @endcode
  7602. And here's an example of how to create an XML document from scratch: @code
  7603. // create an outer node called "ANIMALS"
  7604. XmlElement animalsList ("ANIMALS");
  7605. for (int i = 0; i < numAnimals; ++i)
  7606. {
  7607. // create an inner element..
  7608. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7609. giraffe->setAttribute ("name", "nigel");
  7610. giraffe->setAttribute ("age", 10);
  7611. giraffe->setAttribute ("friendly", true);
  7612. // ..and add our new element to the parent node
  7613. animalsList.addChildElement (giraffe);
  7614. }
  7615. // now we can turn the whole thing into a text document..
  7616. String myXmlDoc = animalsList.createDocument (String::empty);
  7617. @endcode
  7618. @see XmlDocument
  7619. */
  7620. class JUCE_API XmlElement
  7621. {
  7622. public:
  7623. /** Creates an XmlElement with this tag name. */
  7624. explicit XmlElement (const String& tagName) throw();
  7625. /** Creates a (deep) copy of another element. */
  7626. XmlElement (const XmlElement& other);
  7627. /** Creates a (deep) copy of another element. */
  7628. XmlElement& operator= (const XmlElement& other);
  7629. /** Deleting an XmlElement will also delete all its child elements. */
  7630. ~XmlElement() throw();
  7631. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7632. The elements are only considered equivalent if they contain the same attiributes
  7633. with the same values, and have the same sub-nodes.
  7634. @param other the other element to compare to
  7635. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7636. same attributes in a different order will be
  7637. considered the same; if false, the attributes must
  7638. be in the same order as well
  7639. */
  7640. bool isEquivalentTo (const XmlElement* other,
  7641. bool ignoreOrderOfAttributes) const throw();
  7642. /** Returns an XML text document that represents this element.
  7643. The string returned can be parsed to recreate the same XmlElement that
  7644. was used to create it.
  7645. @param dtdToUse the DTD to add to the document
  7646. @param allOnOneLine if true, this means that the document will not contain any
  7647. linefeeds, so it'll be smaller but not very easy to read.
  7648. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7649. document
  7650. @param encodingType the character encoding format string to put into the xml
  7651. header
  7652. @param lineWrapLength the line length that will be used before items get placed on
  7653. a new line. This isn't an absolute maximum length, it just
  7654. determines how lists of attributes get broken up
  7655. @see writeToStream, writeToFile
  7656. */
  7657. const String createDocument (const String& dtdToUse,
  7658. bool allOnOneLine = false,
  7659. bool includeXmlHeader = true,
  7660. const String& encodingType = "UTF-8",
  7661. int lineWrapLength = 60) const;
  7662. /** Writes the document to a stream as UTF-8.
  7663. @param output the stream to write to
  7664. @param dtdToUse the DTD to add to the document
  7665. @param allOnOneLine if true, this means that the document will not contain any
  7666. linefeeds, so it'll be smaller but not very easy to read.
  7667. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7668. document
  7669. @param encodingType the character encoding format string to put into the xml
  7670. header
  7671. @param lineWrapLength the line length that will be used before items get placed on
  7672. a new line. This isn't an absolute maximum length, it just
  7673. determines how lists of attributes get broken up
  7674. @see writeToFile, createDocument
  7675. */
  7676. void writeToStream (OutputStream& output,
  7677. const String& dtdToUse,
  7678. bool allOnOneLine = false,
  7679. bool includeXmlHeader = true,
  7680. const String& encodingType = "UTF-8",
  7681. int lineWrapLength = 60) const;
  7682. /** Writes the element to a file as an XML document.
  7683. To improve safety in case something goes wrong while writing the file, this
  7684. will actually write the document to a new temporary file in the same
  7685. directory as the destination file, and if this succeeds, it will rename this
  7686. new file as the destination file (overwriting any existing file that was there).
  7687. @param destinationFile the file to write to. If this already exists, it will be
  7688. overwritten.
  7689. @param dtdToUse the DTD to add to the document
  7690. @param encodingType the character encoding format string to put into the xml
  7691. header
  7692. @param lineWrapLength the line length that will be used before items get placed on
  7693. a new line. This isn't an absolute maximum length, it just
  7694. determines how lists of attributes get broken up
  7695. @returns true if the file is written successfully; false if something goes wrong
  7696. in the process
  7697. @see createDocument
  7698. */
  7699. bool writeToFile (const File& destinationFile,
  7700. const String& dtdToUse,
  7701. const String& encodingType = "UTF-8",
  7702. int lineWrapLength = 60) const;
  7703. /** Returns this element's tag type name.
  7704. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7705. "MOOSE".
  7706. @see hasTagName
  7707. */
  7708. inline const String& getTagName() const throw() { return tagName; }
  7709. /** Tests whether this element has a particular tag name.
  7710. @param possibleTagName the tag name you're comparing it with
  7711. @see getTagName
  7712. */
  7713. bool hasTagName (const String& possibleTagName) const throw();
  7714. /** Returns the number of XML attributes this element contains.
  7715. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7716. return 2.
  7717. */
  7718. int getNumAttributes() const throw();
  7719. /** Returns the name of one of the elements attributes.
  7720. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7721. getAttributeName(1) would return "antlers".
  7722. @see getAttributeValue, getStringAttribute
  7723. */
  7724. const String& getAttributeName (int attributeIndex) const throw();
  7725. /** Returns the value of one of the elements attributes.
  7726. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7727. getAttributeName(1) would return "2".
  7728. @see getAttributeName, getStringAttribute
  7729. */
  7730. const String& getAttributeValue (int attributeIndex) const throw();
  7731. // Attribute-handling methods..
  7732. /** Checks whether the element contains an attribute with a certain name. */
  7733. bool hasAttribute (const String& attributeName) const throw();
  7734. /** Returns the value of a named attribute.
  7735. @param attributeName the name of the attribute to look up
  7736. */
  7737. const String& getStringAttribute (const String& attributeName) const throw();
  7738. /** Returns the value of a named attribute.
  7739. @param attributeName the name of the attribute to look up
  7740. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7741. with this name
  7742. */
  7743. const String getStringAttribute (const String& attributeName,
  7744. const String& defaultReturnValue) const;
  7745. /** Compares the value of a named attribute with a value passed-in.
  7746. @param attributeName the name of the attribute to look up
  7747. @param stringToCompareAgainst the value to compare it with
  7748. @param ignoreCase whether the comparison should be case-insensitive
  7749. @returns true if the value of the attribute is the same as the string passed-in;
  7750. false if it's different (or if no such attribute exists)
  7751. */
  7752. bool compareAttribute (const String& attributeName,
  7753. const String& stringToCompareAgainst,
  7754. bool ignoreCase = false) const throw();
  7755. /** Returns the value of a named attribute as an integer.
  7756. This will try to find the attribute and convert it to an integer (using
  7757. the String::getIntValue() method).
  7758. @param attributeName the name of the attribute to look up
  7759. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7760. with this name
  7761. @see setAttribute
  7762. */
  7763. int getIntAttribute (const String& attributeName,
  7764. int defaultReturnValue = 0) const;
  7765. /** Returns the value of a named attribute as floating-point.
  7766. This will try to find the attribute and convert it to an integer (using
  7767. the String::getDoubleValue() method).
  7768. @param attributeName the name of the attribute to look up
  7769. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7770. with this name
  7771. @see setAttribute
  7772. */
  7773. double getDoubleAttribute (const String& attributeName,
  7774. double defaultReturnValue = 0.0) const;
  7775. /** Returns the value of a named attribute as a boolean.
  7776. This will try to find the attribute and interpret it as a boolean. To do this,
  7777. it'll return true if the value is "1", "true", "y", etc, or false for other
  7778. values.
  7779. @param attributeName the name of the attribute to look up
  7780. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7781. with this name
  7782. */
  7783. bool getBoolAttribute (const String& attributeName,
  7784. bool defaultReturnValue = false) const;
  7785. /** Adds a named attribute to the element.
  7786. If the element already contains an attribute with this name, it's value will
  7787. be updated to the new value. If there's no such attribute yet, a new one will
  7788. be added.
  7789. Note that there are other setAttribute() methods that take integers,
  7790. doubles, etc. to make it easy to store numbers.
  7791. @param attributeName the name of the attribute to set
  7792. @param newValue the value to set it to
  7793. @see removeAttribute
  7794. */
  7795. void setAttribute (const String& attributeName,
  7796. const String& newValue);
  7797. /** Adds a named attribute to the element, setting it to an integer value.
  7798. If the element already contains an attribute with this name, it's value will
  7799. be updated to the new value. If there's no such attribute yet, a new one will
  7800. be added.
  7801. Note that there are other setAttribute() methods that take integers,
  7802. doubles, etc. to make it easy to store numbers.
  7803. @param attributeName the name of the attribute to set
  7804. @param newValue the value to set it to
  7805. */
  7806. void setAttribute (const String& attributeName,
  7807. int newValue);
  7808. /** Adds a named attribute to the element, setting it to a floating-point value.
  7809. If the element already contains an attribute with this name, it's value will
  7810. be updated to the new value. If there's no such attribute yet, a new one will
  7811. be added.
  7812. Note that there are other setAttribute() methods that take integers,
  7813. doubles, etc. to make it easy to store numbers.
  7814. @param attributeName the name of the attribute to set
  7815. @param newValue the value to set it to
  7816. */
  7817. void setAttribute (const String& attributeName,
  7818. double newValue);
  7819. /** Removes a named attribute from the element.
  7820. @param attributeName the name of the attribute to remove
  7821. @see removeAllAttributes
  7822. */
  7823. void removeAttribute (const String& attributeName) throw();
  7824. /** Removes all attributes from this element.
  7825. */
  7826. void removeAllAttributes() throw();
  7827. // Child element methods..
  7828. /** Returns the first of this element's sub-elements.
  7829. see getNextElement() for an example of how to iterate the sub-elements.
  7830. @see forEachXmlChildElement
  7831. */
  7832. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7833. /** Returns the next of this element's siblings.
  7834. This can be used for iterating an element's sub-elements, e.g.
  7835. @code
  7836. XmlElement* child = myXmlDocument->getFirstChildElement();
  7837. while (child != 0)
  7838. {
  7839. ...do stuff with this child..
  7840. child = child->getNextElement();
  7841. }
  7842. @endcode
  7843. Note that when iterating the child elements, some of them might be
  7844. text elements as well as XML tags - use isTextElement() to work this
  7845. out.
  7846. Also, it's much easier and neater to use this method indirectly via the
  7847. forEachXmlChildElement macro.
  7848. @returns the sibling element that follows this one, or zero if this is the last
  7849. element in its parent
  7850. @see getNextElement, isTextElement, forEachXmlChildElement
  7851. */
  7852. inline XmlElement* getNextElement() const throw() { return nextListItem; }
  7853. /** Returns the next of this element's siblings which has the specified tag
  7854. name.
  7855. This is like getNextElement(), but will scan through the list until it
  7856. finds an element with the given tag name.
  7857. @see getNextElement, forEachXmlChildElementWithTagName
  7858. */
  7859. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  7860. /** Returns the number of sub-elements in this element.
  7861. @see getChildElement
  7862. */
  7863. int getNumChildElements() const throw();
  7864. /** Returns the sub-element at a certain index.
  7865. It's not very efficient to iterate the sub-elements by index - see
  7866. getNextElement() for an example of how best to iterate.
  7867. @returns the n'th child of this element, or 0 if the index is out-of-range
  7868. @see getNextElement, isTextElement, getChildByName
  7869. */
  7870. XmlElement* getChildElement (int index) const throw();
  7871. /** Returns the first sub-element with a given tag-name.
  7872. @param tagNameToLookFor the tag name of the element you want to find
  7873. @returns the first element with this tag name, or 0 if none is found
  7874. @see getNextElement, isTextElement, getChildElement
  7875. */
  7876. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  7877. /** Appends an element to this element's list of children.
  7878. Child elements are deleted automatically when their parent is deleted, so
  7879. make sure the object that you pass in will not be deleted by anything else,
  7880. and make sure it's not already the child of another element.
  7881. @see getFirstChildElement, getNextElement, getNumChildElements,
  7882. getChildElement, removeChildElement
  7883. */
  7884. void addChildElement (XmlElement* newChildElement) throw();
  7885. /** Inserts an element into this element's list of children.
  7886. Child elements are deleted automatically when their parent is deleted, so
  7887. make sure the object that you pass in will not be deleted by anything else,
  7888. and make sure it's not already the child of another element.
  7889. @param newChildNode the element to add
  7890. @param indexToInsertAt the index at which to insert the new element - if this is
  7891. below zero, it will be added to the end of the list
  7892. @see addChildElement, insertChildElement
  7893. */
  7894. void insertChildElement (XmlElement* newChildNode,
  7895. int indexToInsertAt) throw();
  7896. /** Creates a new element with the given name and returns it, after adding it
  7897. as a child element.
  7898. This is a handy method that means that instead of writing this:
  7899. @code
  7900. XmlElement* newElement = new XmlElement ("foobar");
  7901. myParentElement->addChildElement (newElement);
  7902. @endcode
  7903. ..you could just write this:
  7904. @code
  7905. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  7906. @endcode
  7907. */
  7908. XmlElement* createNewChildElement (const String& tagName);
  7909. /** Replaces one of this element's children with another node.
  7910. If the current element passed-in isn't actually a child of this element,
  7911. this will return false and the new one won't be added. Otherwise, the
  7912. existing element will be deleted, replaced with the new one, and it
  7913. will return true.
  7914. */
  7915. bool replaceChildElement (XmlElement* currentChildElement,
  7916. XmlElement* newChildNode) throw();
  7917. /** Removes a child element.
  7918. @param childToRemove the child to look for and remove
  7919. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7920. just remove it
  7921. */
  7922. void removeChildElement (XmlElement* childToRemove,
  7923. bool shouldDeleteTheChild) throw();
  7924. /** Deletes all the child elements in the element.
  7925. @see removeChildElement, deleteAllChildElementsWithTagName
  7926. */
  7927. void deleteAllChildElements() throw();
  7928. /** Deletes all the child elements with a given tag name.
  7929. @see removeChildElement
  7930. */
  7931. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  7932. /** Returns true if the given element is a child of this one. */
  7933. bool containsChildElement (const XmlElement* possibleChild) const throw();
  7934. /** Recursively searches all sub-elements to find one that contains the specified
  7935. child element.
  7936. */
  7937. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  7938. /** Sorts the child elements using a comparator.
  7939. This will use a comparator object to sort the elements into order. The object
  7940. passed must have a method of the form:
  7941. @code
  7942. int compareElements (const XmlElement* first, const XmlElement* second);
  7943. @endcode
  7944. ..and this method must return:
  7945. - a value of < 0 if the first comes before the second
  7946. - a value of 0 if the two objects are equivalent
  7947. - a value of > 0 if the second comes before the first
  7948. To improve performance, the compareElements() method can be declared as static or const.
  7949. @param comparator the comparator to use for comparing elements.
  7950. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  7951. says are equivalent will be kept in the order in which they
  7952. currently appear in the array. This is slower to perform, but
  7953. may be important in some cases. If it's false, a faster algorithm
  7954. is used, but equivalent elements may be rearranged.
  7955. */
  7956. template <class ElementComparator>
  7957. void sortChildElements (ElementComparator& comparator,
  7958. bool retainOrderOfEquivalentItems = false)
  7959. {
  7960. const int num = getNumChildElements();
  7961. if (num > 1)
  7962. {
  7963. HeapBlock <XmlElement*> elems (num);
  7964. getChildElementsAsArray (elems);
  7965. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  7966. reorderChildElements (elems, num);
  7967. }
  7968. }
  7969. /** Returns true if this element is a section of text.
  7970. Elements can either be an XML tag element or a secton of text, so this
  7971. is used to find out what kind of element this one is.
  7972. @see getAllText, addTextElement, deleteAllTextElements
  7973. */
  7974. bool isTextElement() const throw();
  7975. /** Returns the text for a text element.
  7976. Note that if you have an element like this:
  7977. @code<xyz>hello</xyz>@endcode
  7978. then calling getText on the "xyz" element won't return "hello", because that is
  7979. actually stored in a special text sub-element inside the xyz element. To get the
  7980. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7981. use getAllSubText() to do this automatically.
  7982. Note that leading and trailing whitespace will be included in the string - to remove
  7983. if, just call String::trim() on the result.
  7984. @see isTextElement, getAllSubText, getChildElementAllSubText
  7985. */
  7986. const String& getText() const throw();
  7987. /** Sets the text in a text element.
  7988. Note that this is only a valid call if this element is a text element. If it's
  7989. not, then no action will be performed.
  7990. */
  7991. void setText (const String& newText);
  7992. /** Returns all the text from this element's child nodes.
  7993. This iterates all the child elements and when it finds text elements,
  7994. it concatenates their text into a big string which it returns.
  7995. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  7996. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  7997. Note that leading and trailing whitespace will be included in the string - to remove
  7998. if, just call String::trim() on the result.
  7999. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  8000. */
  8001. const String getAllSubText() const;
  8002. /** Returns all the sub-text of a named child element.
  8003. If there is a child element with the given tag name, this will return
  8004. all of its sub-text (by calling getAllSubText() on it). If there is
  8005. no such child element, this will return the default string passed-in.
  8006. @see getAllSubText
  8007. */
  8008. const String getChildElementAllSubText (const String& childTagName,
  8009. const String& defaultReturnValue) const;
  8010. /** Appends a section of text to this element.
  8011. @see isTextElement, getText, getAllSubText
  8012. */
  8013. void addTextElement (const String& text);
  8014. /** Removes all the text elements from this element.
  8015. @see isTextElement, getText, getAllSubText, addTextElement
  8016. */
  8017. void deleteAllTextElements() throw();
  8018. /** Creates a text element that can be added to a parent element.
  8019. */
  8020. static XmlElement* createTextElement (const String& text);
  8021. private:
  8022. struct XmlAttributeNode
  8023. {
  8024. XmlAttributeNode (const XmlAttributeNode& other) throw();
  8025. XmlAttributeNode (const String& name, const String& value) throw();
  8026. LinkedListPointer<XmlAttributeNode> nextListItem;
  8027. String name, value;
  8028. bool hasName (const String& name) const throw();
  8029. private:
  8030. XmlAttributeNode& operator= (const XmlAttributeNode&);
  8031. };
  8032. friend class XmlDocument;
  8033. friend class LinkedListPointer<XmlAttributeNode>;
  8034. friend class LinkedListPointer <XmlElement>;
  8035. friend class LinkedListPointer <XmlElement>::Appender;
  8036. LinkedListPointer <XmlElement> nextListItem;
  8037. LinkedListPointer <XmlElement> firstChildElement;
  8038. LinkedListPointer <XmlAttributeNode> attributes;
  8039. String tagName;
  8040. XmlElement (int) throw();
  8041. void copyChildrenAndAttributesFrom (const XmlElement& other);
  8042. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  8043. void getChildElementsAsArray (XmlElement**) const throw();
  8044. void reorderChildElements (XmlElement**, int) throw();
  8045. JUCE_LEAK_DETECTOR (XmlElement);
  8046. };
  8047. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  8048. /*** End of inlined file: juce_XmlElement.h ***/
  8049. /**
  8050. A set of named property values, which can be strings, integers, floating point, etc.
  8051. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  8052. to load and save types other than strings.
  8053. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  8054. messages and saves/loads the list from a file.
  8055. */
  8056. class JUCE_API PropertySet
  8057. {
  8058. public:
  8059. /** Creates an empty PropertySet.
  8060. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  8061. case-insensitive way
  8062. */
  8063. PropertySet (bool ignoreCaseOfKeyNames = false);
  8064. /** Creates a copy of another PropertySet.
  8065. */
  8066. PropertySet (const PropertySet& other);
  8067. /** Copies another PropertySet over this one.
  8068. */
  8069. PropertySet& operator= (const PropertySet& other);
  8070. /** Destructor. */
  8071. virtual ~PropertySet();
  8072. /** Returns one of the properties as a string.
  8073. If the value isn't found in this set, then this will look for it in a fallback
  8074. property set (if you've specified one with the setFallbackPropertySet() method),
  8075. and if it can't find one there, it'll return the default value passed-in.
  8076. @param keyName the name of the property to retrieve
  8077. @param defaultReturnValue a value to return if the named property doesn't actually exist
  8078. */
  8079. const String getValue (const String& keyName,
  8080. const String& defaultReturnValue = String::empty) const throw();
  8081. /** Returns one of the properties as an integer.
  8082. If the value isn't found in this set, then this will look for it in a fallback
  8083. property set (if you've specified one with the setFallbackPropertySet() method),
  8084. and if it can't find one there, it'll return the default value passed-in.
  8085. @param keyName the name of the property to retrieve
  8086. @param defaultReturnValue a value to return if the named property doesn't actually exist
  8087. */
  8088. int getIntValue (const String& keyName,
  8089. const int defaultReturnValue = 0) const throw();
  8090. /** Returns one of the properties as an double.
  8091. If the value isn't found in this set, then this will look for it in a fallback
  8092. property set (if you've specified one with the setFallbackPropertySet() method),
  8093. and if it can't find one there, it'll return the default value passed-in.
  8094. @param keyName the name of the property to retrieve
  8095. @param defaultReturnValue a value to return if the named property doesn't actually exist
  8096. */
  8097. double getDoubleValue (const String& keyName,
  8098. const double defaultReturnValue = 0.0) const throw();
  8099. /** Returns one of the properties as an boolean.
  8100. The result will be true if the string found for this key name can be parsed as a non-zero
  8101. integer.
  8102. If the value isn't found in this set, then this will look for it in a fallback
  8103. property set (if you've specified one with the setFallbackPropertySet() method),
  8104. and if it can't find one there, it'll return the default value passed-in.
  8105. @param keyName the name of the property to retrieve
  8106. @param defaultReturnValue a value to return if the named property doesn't actually exist
  8107. */
  8108. bool getBoolValue (const String& keyName,
  8109. const bool defaultReturnValue = false) const throw();
  8110. /** Returns one of the properties as an XML element.
  8111. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  8112. key isn't found, or if the entry contains an string that isn't valid XML.
  8113. If the value isn't found in this set, then this will look for it in a fallback
  8114. property set (if you've specified one with the setFallbackPropertySet() method),
  8115. and if it can't find one there, it'll return the default value passed-in.
  8116. @param keyName the name of the property to retrieve
  8117. */
  8118. XmlElement* getXmlValue (const String& keyName) const;
  8119. /** Sets a named property.
  8120. @param keyName the name of the property to set. (This mustn't be an empty string)
  8121. @param value the new value to set it to
  8122. */
  8123. void setValue (const String& keyName, const var& value);
  8124. /** Sets a named property to an XML element.
  8125. @param keyName the name of the property to set. (This mustn't be an empty string)
  8126. @param xml the new element to set it to. If this is zero, the value will be set to
  8127. an empty string
  8128. @see getXmlValue
  8129. */
  8130. void setValue (const String& keyName, const XmlElement* xml);
  8131. /** Deletes a property.
  8132. @param keyName the name of the property to delete. (This mustn't be an empty string)
  8133. */
  8134. void removeValue (const String& keyName);
  8135. /** Returns true if the properies include the given key. */
  8136. bool containsKey (const String& keyName) const throw();
  8137. /** Removes all values. */
  8138. void clear();
  8139. /** Returns the keys/value pair array containing all the properties. */
  8140. StringPairArray& getAllProperties() throw() { return properties; }
  8141. /** Returns the lock used when reading or writing to this set */
  8142. const CriticalSection& getLock() const throw() { return lock; }
  8143. /** Returns an XML element which encapsulates all the items in this property set.
  8144. The string parameter is the tag name that should be used for the node.
  8145. @see restoreFromXml
  8146. */
  8147. XmlElement* createXml (const String& nodeName) const;
  8148. /** Reloads a set of properties that were previously stored as XML.
  8149. The node passed in must have been created by the createXml() method.
  8150. @see createXml
  8151. */
  8152. void restoreFromXml (const XmlElement& xml);
  8153. /** Sets up a second PopertySet that will be used to look up any values that aren't
  8154. set in this one.
  8155. If you set this up to be a pointer to a second property set, then whenever one
  8156. of the getValue() methods fails to find an entry in this set, it will look up that
  8157. value in the fallback set, and if it finds it, it will return that.
  8158. Make sure that you don't delete the fallback set while it's still being used by
  8159. another set! To remove the fallback set, just call this method with a null pointer.
  8160. @see getFallbackPropertySet
  8161. */
  8162. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  8163. /** Returns the fallback property set.
  8164. @see setFallbackPropertySet
  8165. */
  8166. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  8167. protected:
  8168. /** Subclasses can override this to be told when one of the properies has been changed. */
  8169. virtual void propertyChanged();
  8170. private:
  8171. StringPairArray properties;
  8172. PropertySet* fallbackProperties;
  8173. CriticalSection lock;
  8174. bool ignoreCaseOfKeys;
  8175. JUCE_LEAK_DETECTOR (PropertySet);
  8176. };
  8177. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  8178. /*** End of inlined file: juce_PropertySet.h ***/
  8179. #endif
  8180. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8181. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  8182. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8183. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8184. /**
  8185. Holds a list of objects derived from ReferenceCountedObject.
  8186. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  8187. and takes care of incrementing and decrementing their ref counts when they
  8188. are added and removed from the array.
  8189. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  8190. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8191. @see Array, OwnedArray, StringArray
  8192. */
  8193. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8194. class ReferenceCountedArray
  8195. {
  8196. public:
  8197. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  8198. /** Creates an empty array.
  8199. @see ReferenceCountedObject, Array, OwnedArray
  8200. */
  8201. ReferenceCountedArray() throw()
  8202. : numUsed (0)
  8203. {
  8204. }
  8205. /** Creates a copy of another array */
  8206. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  8207. {
  8208. const ScopedLockType lock (other.getLock());
  8209. numUsed = other.numUsed;
  8210. data.setAllocatedSize (numUsed);
  8211. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  8212. for (int i = numUsed; --i >= 0;)
  8213. if (data.elements[i] != 0)
  8214. data.elements[i]->incReferenceCount();
  8215. }
  8216. /** Copies another array into this one.
  8217. Any existing objects in this array will first be released.
  8218. */
  8219. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  8220. {
  8221. if (this != &other)
  8222. {
  8223. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  8224. swapWithArray (otherCopy);
  8225. }
  8226. return *this;
  8227. }
  8228. /** Destructor.
  8229. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  8230. */
  8231. ~ReferenceCountedArray()
  8232. {
  8233. clear();
  8234. }
  8235. /** Removes all objects from the array.
  8236. Any objects in the array that are not referenced from elsewhere will be deleted.
  8237. */
  8238. void clear()
  8239. {
  8240. const ScopedLockType lock (getLock());
  8241. while (numUsed > 0)
  8242. if (data.elements [--numUsed] != 0)
  8243. data.elements [numUsed]->decReferenceCount();
  8244. jassert (numUsed == 0);
  8245. data.setAllocatedSize (0);
  8246. }
  8247. /** Returns the current number of objects in the array. */
  8248. inline int size() const throw()
  8249. {
  8250. return numUsed;
  8251. }
  8252. /** Returns a pointer to the object at this index in the array.
  8253. If the index is out-of-range, this will return a null pointer, (and
  8254. it could be null anyway, because it's ok for the array to hold null
  8255. pointers as well as objects).
  8256. @see getUnchecked
  8257. */
  8258. inline const ObjectClassPtr operator[] (const int index) const throw()
  8259. {
  8260. const ScopedLockType lock (getLock());
  8261. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  8262. : static_cast <ObjectClass*> (0);
  8263. }
  8264. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  8265. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  8266. it can be used when you're sure the index if always going to be legal.
  8267. */
  8268. inline const ObjectClassPtr getUnchecked (const int index) const throw()
  8269. {
  8270. const ScopedLockType lock (getLock());
  8271. jassert (isPositiveAndBelow (index, numUsed));
  8272. return data.elements [index];
  8273. }
  8274. /** Returns a pointer to the first object in the array.
  8275. This will return a null pointer if the array's empty.
  8276. @see getLast
  8277. */
  8278. inline const ObjectClassPtr getFirst() const throw()
  8279. {
  8280. const ScopedLockType lock (getLock());
  8281. return numUsed > 0 ? data.elements [0]
  8282. : static_cast <ObjectClass*> (0);
  8283. }
  8284. /** Returns a pointer to the last object in the array.
  8285. This will return a null pointer if the array's empty.
  8286. @see getFirst
  8287. */
  8288. inline const ObjectClassPtr getLast() const throw()
  8289. {
  8290. const ScopedLockType lock (getLock());
  8291. return numUsed > 0 ? data.elements [numUsed - 1]
  8292. : static_cast <ObjectClass*> (0);
  8293. }
  8294. /** Finds the index of the first occurrence of an object in the array.
  8295. @param objectToLookFor the object to look for
  8296. @returns the index at which the object was found, or -1 if it's not found
  8297. */
  8298. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  8299. {
  8300. const ScopedLockType lock (getLock());
  8301. ObjectClass** e = data.elements.getData();
  8302. ObjectClass** const end = e + numUsed;
  8303. while (e != end)
  8304. {
  8305. if (objectToLookFor == *e)
  8306. return static_cast <int> (e - data.elements.getData());
  8307. ++e;
  8308. }
  8309. return -1;
  8310. }
  8311. /** Returns true if the array contains a specified object.
  8312. @param objectToLookFor the object to look for
  8313. @returns true if the object is in the array
  8314. */
  8315. bool contains (const ObjectClass* const objectToLookFor) const throw()
  8316. {
  8317. const ScopedLockType lock (getLock());
  8318. ObjectClass** e = data.elements.getData();
  8319. ObjectClass** const end = e + numUsed;
  8320. while (e != end)
  8321. {
  8322. if (objectToLookFor == *e)
  8323. return true;
  8324. ++e;
  8325. }
  8326. return false;
  8327. }
  8328. /** Appends a new object to the end of the array.
  8329. This will increase the new object's reference count.
  8330. @param newObject the new object to add to the array
  8331. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  8332. */
  8333. void add (ObjectClass* const newObject) throw()
  8334. {
  8335. const ScopedLockType lock (getLock());
  8336. data.ensureAllocatedSize (numUsed + 1);
  8337. data.elements [numUsed++] = newObject;
  8338. if (newObject != 0)
  8339. newObject->incReferenceCount();
  8340. }
  8341. /** Inserts a new object into the array at the given index.
  8342. If the index is less than 0 or greater than the size of the array, the
  8343. element will be added to the end of the array.
  8344. Otherwise, it will be inserted into the array, moving all the later elements
  8345. along to make room.
  8346. This will increase the new object's reference count.
  8347. @param indexToInsertAt the index at which the new element should be inserted
  8348. @param newObject the new object to add to the array
  8349. @see add, addSorted, addIfNotAlreadyThere, set
  8350. */
  8351. void insert (int indexToInsertAt,
  8352. ObjectClass* const newObject) throw()
  8353. {
  8354. if (indexToInsertAt >= 0)
  8355. {
  8356. const ScopedLockType lock (getLock());
  8357. if (indexToInsertAt > numUsed)
  8358. indexToInsertAt = numUsed;
  8359. data.ensureAllocatedSize (numUsed + 1);
  8360. ObjectClass** const e = data.elements + indexToInsertAt;
  8361. const int numToMove = numUsed - indexToInsertAt;
  8362. if (numToMove > 0)
  8363. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  8364. *e = newObject;
  8365. if (newObject != 0)
  8366. newObject->incReferenceCount();
  8367. ++numUsed;
  8368. }
  8369. else
  8370. {
  8371. add (newObject);
  8372. }
  8373. }
  8374. /** Appends a new object at the end of the array as long as the array doesn't
  8375. already contain it.
  8376. If the array already contains a matching object, nothing will be done.
  8377. @param newObject the new object to add to the array
  8378. */
  8379. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  8380. {
  8381. const ScopedLockType lock (getLock());
  8382. if (! contains (newObject))
  8383. add (newObject);
  8384. }
  8385. /** Replaces an object in the array with a different one.
  8386. If the index is less than zero, this method does nothing.
  8387. If the index is beyond the end of the array, the new object is added to the end of the array.
  8388. The object being added has its reference count increased, and if it's replacing
  8389. another object, then that one has its reference count decreased, and may be deleted.
  8390. @param indexToChange the index whose value you want to change
  8391. @param newObject the new value to set for this index.
  8392. @see add, insert, remove
  8393. */
  8394. void set (const int indexToChange,
  8395. ObjectClass* const newObject)
  8396. {
  8397. if (indexToChange >= 0)
  8398. {
  8399. const ScopedLockType lock (getLock());
  8400. if (newObject != 0)
  8401. newObject->incReferenceCount();
  8402. if (indexToChange < numUsed)
  8403. {
  8404. if (data.elements [indexToChange] != 0)
  8405. data.elements [indexToChange]->decReferenceCount();
  8406. data.elements [indexToChange] = newObject;
  8407. }
  8408. else
  8409. {
  8410. data.ensureAllocatedSize (numUsed + 1);
  8411. data.elements [numUsed++] = newObject;
  8412. }
  8413. }
  8414. }
  8415. /** Adds elements from another array to the end of this array.
  8416. @param arrayToAddFrom the array from which to copy the elements
  8417. @param startIndex the first element of the other array to start copying from
  8418. @param numElementsToAdd how many elements to add from the other array. If this
  8419. value is negative or greater than the number of available elements,
  8420. all available elements will be copied.
  8421. @see add
  8422. */
  8423. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8424. int startIndex = 0,
  8425. int numElementsToAdd = -1) throw()
  8426. {
  8427. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  8428. {
  8429. const ScopedLockType lock2 (getLock());
  8430. if (startIndex < 0)
  8431. {
  8432. jassertfalse;
  8433. startIndex = 0;
  8434. }
  8435. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8436. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8437. if (numElementsToAdd > 0)
  8438. {
  8439. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  8440. while (--numElementsToAdd >= 0)
  8441. add (arrayToAddFrom.getUnchecked (startIndex++));
  8442. }
  8443. }
  8444. }
  8445. /** Inserts a new object into the array assuming that the array is sorted.
  8446. This will use a comparator to find the position at which the new object
  8447. should go. If the array isn't sorted, the behaviour of this
  8448. method will be unpredictable.
  8449. @param comparator the comparator object to use to compare the elements - see the
  8450. sort() method for details about this object's form
  8451. @param newObject the new object to insert to the array
  8452. @see add, sort
  8453. */
  8454. template <class ElementComparator>
  8455. void addSorted (ElementComparator& comparator,
  8456. ObjectClass* newObject) throw()
  8457. {
  8458. const ScopedLockType lock (getLock());
  8459. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  8460. }
  8461. /** Inserts or replaces an object in the array, assuming it is sorted.
  8462. This is similar to addSorted, but if a matching element already exists, then it will be
  8463. replaced by the new one, rather than the new one being added as well.
  8464. */
  8465. template <class ElementComparator>
  8466. void addOrReplaceSorted (ElementComparator& comparator,
  8467. ObjectClass* newObject) throw()
  8468. {
  8469. const ScopedLockType lock (getLock());
  8470. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  8471. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  8472. set (index - 1, newObject); // replace an existing object that matches
  8473. else
  8474. insert (index, newObject); // no match, so insert the new one
  8475. }
  8476. /** Removes an object from the array.
  8477. This will remove the object at a given index and move back all the
  8478. subsequent objects to close the gap.
  8479. If the index passed in is out-of-range, nothing will happen.
  8480. The object that is removed will have its reference count decreased,
  8481. and may be deleted if not referenced from elsewhere.
  8482. @param indexToRemove the index of the element to remove
  8483. @see removeObject, removeRange
  8484. */
  8485. void remove (const int indexToRemove)
  8486. {
  8487. const ScopedLockType lock (getLock());
  8488. if (isPositiveAndBelow (indexToRemove, numUsed))
  8489. {
  8490. ObjectClass** const e = data.elements + indexToRemove;
  8491. if (*e != 0)
  8492. (*e)->decReferenceCount();
  8493. --numUsed;
  8494. const int numberToShift = numUsed - indexToRemove;
  8495. if (numberToShift > 0)
  8496. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8497. if ((numUsed << 1) < data.numAllocated)
  8498. minimiseStorageOverheads();
  8499. }
  8500. }
  8501. /** Removes and returns an object from the array.
  8502. This will remove the object at a given index and return it, moving back all
  8503. the subsequent objects to close the gap. If the index passed in is out-of-range,
  8504. nothing will happen and a null pointer will be returned.
  8505. @param indexToRemove the index of the element to remove
  8506. @see remove, removeObject, removeRange
  8507. */
  8508. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  8509. {
  8510. ObjectClassPtr removedItem;
  8511. const ScopedLockType lock (getLock());
  8512. if (isPositiveAndBelow (indexToRemove, numUsed))
  8513. {
  8514. ObjectClass** const e = data.elements + indexToRemove;
  8515. if (*e != 0)
  8516. {
  8517. removedItem = *e;
  8518. (*e)->decReferenceCount();
  8519. }
  8520. --numUsed;
  8521. const int numberToShift = numUsed - indexToRemove;
  8522. if (numberToShift > 0)
  8523. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8524. if ((numUsed << 1) < data.numAllocated)
  8525. minimiseStorageOverheads();
  8526. }
  8527. return removedItem;
  8528. }
  8529. /** Removes the first occurrence of a specified object from the array.
  8530. If the item isn't found, no action is taken. If it is found, it is
  8531. removed and has its reference count decreased.
  8532. @param objectToRemove the object to try to remove
  8533. @see remove, removeRange
  8534. */
  8535. void removeObject (ObjectClass* const objectToRemove)
  8536. {
  8537. const ScopedLockType lock (getLock());
  8538. remove (indexOf (objectToRemove));
  8539. }
  8540. /** Removes a range of objects from the array.
  8541. This will remove a set of objects, starting from the given index,
  8542. and move any subsequent elements down to close the gap.
  8543. If the range extends beyond the bounds of the array, it will
  8544. be safely clipped to the size of the array.
  8545. The objects that are removed will have their reference counts decreased,
  8546. and may be deleted if not referenced from elsewhere.
  8547. @param startIndex the index of the first object to remove
  8548. @param numberToRemove how many objects should be removed
  8549. @see remove, removeObject
  8550. */
  8551. void removeRange (const int startIndex,
  8552. const int numberToRemove)
  8553. {
  8554. const ScopedLockType lock (getLock());
  8555. const int start = jlimit (0, numUsed, startIndex);
  8556. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8557. if (end > start)
  8558. {
  8559. int i;
  8560. for (i = start; i < end; ++i)
  8561. {
  8562. if (data.elements[i] != 0)
  8563. {
  8564. data.elements[i]->decReferenceCount();
  8565. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8566. }
  8567. }
  8568. const int rangeSize = end - start;
  8569. ObjectClass** e = data.elements + start;
  8570. i = numUsed - end;
  8571. numUsed -= rangeSize;
  8572. while (--i >= 0)
  8573. {
  8574. *e = e [rangeSize];
  8575. ++e;
  8576. }
  8577. if ((numUsed << 1) < data.numAllocated)
  8578. minimiseStorageOverheads();
  8579. }
  8580. }
  8581. /** Removes the last n objects from the array.
  8582. The objects that are removed will have their reference counts decreased,
  8583. and may be deleted if not referenced from elsewhere.
  8584. @param howManyToRemove how many objects to remove from the end of the array
  8585. @see remove, removeObject, removeRange
  8586. */
  8587. void removeLast (int howManyToRemove = 1)
  8588. {
  8589. const ScopedLockType lock (getLock());
  8590. if (howManyToRemove > numUsed)
  8591. howManyToRemove = numUsed;
  8592. while (--howManyToRemove >= 0)
  8593. remove (numUsed - 1);
  8594. }
  8595. /** Swaps a pair of objects in the array.
  8596. If either of the indexes passed in is out-of-range, nothing will happen,
  8597. otherwise the two objects at these positions will be exchanged.
  8598. */
  8599. void swap (const int index1,
  8600. const int index2) throw()
  8601. {
  8602. const ScopedLockType lock (getLock());
  8603. if (isPositiveAndBelow (index1, numUsed)
  8604. && isPositiveAndBelow (index2, numUsed))
  8605. {
  8606. swapVariables (data.elements [index1],
  8607. data.elements [index2]);
  8608. }
  8609. }
  8610. /** Moves one of the objects to a different position.
  8611. This will move the object to a specified index, shuffling along
  8612. any intervening elements as required.
  8613. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8614. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8615. @param currentIndex the index of the object to be moved. If this isn't a
  8616. valid index, then nothing will be done
  8617. @param newIndex the index at which you'd like this object to end up. If this
  8618. is less than zero, it will be moved to the end of the array
  8619. */
  8620. void move (const int currentIndex,
  8621. int newIndex) throw()
  8622. {
  8623. if (currentIndex != newIndex)
  8624. {
  8625. const ScopedLockType lock (getLock());
  8626. if (isPositiveAndBelow (currentIndex, numUsed))
  8627. {
  8628. if (! isPositiveAndBelow (newIndex, numUsed))
  8629. newIndex = numUsed - 1;
  8630. ObjectClass* const value = data.elements [currentIndex];
  8631. if (newIndex > currentIndex)
  8632. {
  8633. memmove (data.elements + currentIndex,
  8634. data.elements + currentIndex + 1,
  8635. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8636. }
  8637. else
  8638. {
  8639. memmove (data.elements + newIndex + 1,
  8640. data.elements + newIndex,
  8641. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8642. }
  8643. data.elements [newIndex] = value;
  8644. }
  8645. }
  8646. }
  8647. /** This swaps the contents of this array with those of another array.
  8648. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8649. because it just swaps their internal pointers.
  8650. */
  8651. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  8652. {
  8653. const ScopedLockType lock1 (getLock());
  8654. const ScopedLockType lock2 (otherArray.getLock());
  8655. data.swapWith (otherArray.data);
  8656. swapVariables (numUsed, otherArray.numUsed);
  8657. }
  8658. /** Compares this array to another one.
  8659. @returns true only if the other array contains the same objects in the same order
  8660. */
  8661. bool operator== (const ReferenceCountedArray& other) const throw()
  8662. {
  8663. const ScopedLockType lock2 (other.getLock());
  8664. const ScopedLockType lock1 (getLock());
  8665. if (numUsed != other.numUsed)
  8666. return false;
  8667. for (int i = numUsed; --i >= 0;)
  8668. if (data.elements [i] != other.data.elements [i])
  8669. return false;
  8670. return true;
  8671. }
  8672. /** Compares this array to another one.
  8673. @see operator==
  8674. */
  8675. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8676. {
  8677. return ! operator== (other);
  8678. }
  8679. /** Sorts the elements in the array.
  8680. This will use a comparator object to sort the elements into order. The object
  8681. passed must have a method of the form:
  8682. @code
  8683. int compareElements (ElementType first, ElementType second);
  8684. @endcode
  8685. ..and this method must return:
  8686. - a value of < 0 if the first comes before the second
  8687. - a value of 0 if the two objects are equivalent
  8688. - a value of > 0 if the second comes before the first
  8689. To improve performance, the compareElements() method can be declared as static or const.
  8690. @param comparator the comparator to use for comparing elements.
  8691. @param retainOrderOfEquivalentItems if this is true, then items
  8692. which the comparator says are equivalent will be
  8693. kept in the order in which they currently appear
  8694. in the array. This is slower to perform, but may
  8695. be important in some cases. If it's false, a faster
  8696. algorithm is used, but equivalent elements may be
  8697. rearranged.
  8698. @see sortArray
  8699. */
  8700. template <class ElementComparator>
  8701. void sort (ElementComparator& comparator,
  8702. const bool retainOrderOfEquivalentItems = false) const throw()
  8703. {
  8704. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8705. // avoids getting warning messages about the parameter being unused
  8706. const ScopedLockType lock (getLock());
  8707. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8708. }
  8709. /** Reduces the amount of storage being used by the array.
  8710. Arrays typically allocate slightly more storage than they need, and after
  8711. removing elements, they may have quite a lot of unused space allocated.
  8712. This method will reduce the amount of allocated storage to a minimum.
  8713. */
  8714. void minimiseStorageOverheads() throw()
  8715. {
  8716. const ScopedLockType lock (getLock());
  8717. data.shrinkToNoMoreThan (numUsed);
  8718. }
  8719. /** Returns the CriticalSection that locks this array.
  8720. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8721. an object of ScopedLockType as an RAII lock for it.
  8722. */
  8723. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8724. /** Returns the type of scoped lock to use for locking this array */
  8725. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8726. private:
  8727. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8728. int numUsed;
  8729. };
  8730. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8731. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  8732. #endif
  8733. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8734. /*** Start of inlined file: juce_SortedSet.h ***/
  8735. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8736. #define __JUCE_SORTEDSET_JUCEHEADER__
  8737. #if JUCE_MSVC
  8738. #pragma warning (push)
  8739. #pragma warning (disable: 4512)
  8740. #endif
  8741. /**
  8742. Holds a set of unique primitive objects, such as ints or doubles.
  8743. A set can only hold one item with a given value, so if for example it's a
  8744. set of integers, attempting to add the same integer twice will do nothing
  8745. the second time.
  8746. Internally, the list of items is kept sorted (which means that whatever
  8747. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8748. to determine the order), and searching the set for known values is very fast
  8749. because it uses a binary-chop method.
  8750. Note that if you're using a class or struct as the element type, it must be
  8751. capable of being copied or moved with a straightforward memcpy, rather than
  8752. needing construction and destruction code.
  8753. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8754. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8755. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8756. */
  8757. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8758. class SortedSet
  8759. {
  8760. public:
  8761. /** Creates an empty set. */
  8762. SortedSet() throw()
  8763. : numUsed (0)
  8764. {
  8765. }
  8766. /** Creates a copy of another set.
  8767. @param other the set to copy
  8768. */
  8769. SortedSet (const SortedSet& other) throw()
  8770. {
  8771. const ScopedLockType lock (other.getLock());
  8772. numUsed = other.numUsed;
  8773. data.setAllocatedSize (other.numUsed);
  8774. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8775. }
  8776. /** Destructor. */
  8777. ~SortedSet() throw()
  8778. {
  8779. }
  8780. /** Copies another set over this one.
  8781. @param other the set to copy
  8782. */
  8783. SortedSet& operator= (const SortedSet& other) throw()
  8784. {
  8785. if (this != &other)
  8786. {
  8787. const ScopedLockType lock1 (other.getLock());
  8788. const ScopedLockType lock2 (getLock());
  8789. data.ensureAllocatedSize (other.size());
  8790. numUsed = other.numUsed;
  8791. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8792. minimiseStorageOverheads();
  8793. }
  8794. return *this;
  8795. }
  8796. /** Compares this set to another one.
  8797. Two sets are considered equal if they both contain the same set of
  8798. elements.
  8799. @param other the other set to compare with
  8800. */
  8801. bool operator== (const SortedSet<ElementType>& other) const throw()
  8802. {
  8803. const ScopedLockType lock (getLock());
  8804. if (numUsed != other.numUsed)
  8805. return false;
  8806. for (int i = numUsed; --i >= 0;)
  8807. if (data.elements[i] != other.data.elements[i])
  8808. return false;
  8809. return true;
  8810. }
  8811. /** Compares this set to another one.
  8812. Two sets are considered equal if they both contain the same set of
  8813. elements.
  8814. @param other the other set to compare with
  8815. */
  8816. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8817. {
  8818. return ! operator== (other);
  8819. }
  8820. /** Removes all elements from the set.
  8821. This will remove all the elements, and free any storage that the set is
  8822. using. To clear it without freeing the storage, use the clearQuick()
  8823. method instead.
  8824. @see clearQuick
  8825. */
  8826. void clear() throw()
  8827. {
  8828. const ScopedLockType lock (getLock());
  8829. data.setAllocatedSize (0);
  8830. numUsed = 0;
  8831. }
  8832. /** Removes all elements from the set without freeing the array's allocated storage.
  8833. @see clear
  8834. */
  8835. void clearQuick() throw()
  8836. {
  8837. const ScopedLockType lock (getLock());
  8838. numUsed = 0;
  8839. }
  8840. /** Returns the current number of elements in the set.
  8841. */
  8842. inline int size() const throw()
  8843. {
  8844. return numUsed;
  8845. }
  8846. /** Returns one of the elements in the set.
  8847. If the index passed in is beyond the range of valid elements, this
  8848. will return zero.
  8849. If you're certain that the index will always be a valid element, you
  8850. can call getUnchecked() instead, which is faster.
  8851. @param index the index of the element being requested (0 is the first element in the set)
  8852. @see getUnchecked, getFirst, getLast
  8853. */
  8854. inline ElementType operator[] (const int index) const throw()
  8855. {
  8856. const ScopedLockType lock (getLock());
  8857. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  8858. : ElementType();
  8859. }
  8860. /** Returns one of the elements in the set, without checking the index passed in.
  8861. Unlike the operator[] method, this will try to return an element without
  8862. checking that the index is within the bounds of the set, so should only
  8863. be used when you're confident that it will always be a valid index.
  8864. @param index the index of the element being requested (0 is the first element in the set)
  8865. @see operator[], getFirst, getLast
  8866. */
  8867. inline ElementType getUnchecked (const int index) const throw()
  8868. {
  8869. const ScopedLockType lock (getLock());
  8870. jassert (isPositiveAndBelow (index, numUsed));
  8871. return data.elements [index];
  8872. }
  8873. /** Returns the first element in the set, or 0 if the set is empty.
  8874. @see operator[], getUnchecked, getLast
  8875. */
  8876. inline ElementType getFirst() const throw()
  8877. {
  8878. const ScopedLockType lock (getLock());
  8879. return numUsed > 0 ? data.elements [0] : ElementType();
  8880. }
  8881. /** Returns the last element in the set, or 0 if the set is empty.
  8882. @see operator[], getUnchecked, getFirst
  8883. */
  8884. inline ElementType getLast() const throw()
  8885. {
  8886. const ScopedLockType lock (getLock());
  8887. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  8888. }
  8889. /** Finds the index of the first element which matches the value passed in.
  8890. This will search the set for the given object, and return the index
  8891. of its first occurrence. If the object isn't found, the method will return -1.
  8892. @param elementToLookFor the value or object to look for
  8893. @returns the index of the object, or -1 if it's not found
  8894. */
  8895. int indexOf (const ElementType elementToLookFor) const throw()
  8896. {
  8897. const ScopedLockType lock (getLock());
  8898. int start = 0;
  8899. int end = numUsed;
  8900. for (;;)
  8901. {
  8902. if (start >= end)
  8903. {
  8904. return -1;
  8905. }
  8906. else if (elementToLookFor == data.elements [start])
  8907. {
  8908. return start;
  8909. }
  8910. else
  8911. {
  8912. const int halfway = (start + end) >> 1;
  8913. if (halfway == start)
  8914. return -1;
  8915. else if (elementToLookFor >= data.elements [halfway])
  8916. start = halfway;
  8917. else
  8918. end = halfway;
  8919. }
  8920. }
  8921. }
  8922. /** Returns true if the set contains at least one occurrence of an object.
  8923. @param elementToLookFor the value or object to look for
  8924. @returns true if the item is found
  8925. */
  8926. bool contains (const ElementType elementToLookFor) const throw()
  8927. {
  8928. const ScopedLockType lock (getLock());
  8929. int start = 0;
  8930. int end = numUsed;
  8931. for (;;)
  8932. {
  8933. if (start >= end)
  8934. {
  8935. return false;
  8936. }
  8937. else if (elementToLookFor == data.elements [start])
  8938. {
  8939. return true;
  8940. }
  8941. else
  8942. {
  8943. const int halfway = (start + end) >> 1;
  8944. if (halfway == start)
  8945. return false;
  8946. else if (elementToLookFor >= data.elements [halfway])
  8947. start = halfway;
  8948. else
  8949. end = halfway;
  8950. }
  8951. }
  8952. }
  8953. /** Adds a new element to the set, (as long as it's not already in there).
  8954. @param newElement the new object to add to the set
  8955. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8956. */
  8957. void add (const ElementType newElement) throw()
  8958. {
  8959. const ScopedLockType lock (getLock());
  8960. int start = 0;
  8961. int end = numUsed;
  8962. for (;;)
  8963. {
  8964. if (start >= end)
  8965. {
  8966. jassert (start <= end);
  8967. insertInternal (start, newElement);
  8968. break;
  8969. }
  8970. else if (newElement == data.elements [start])
  8971. {
  8972. break;
  8973. }
  8974. else
  8975. {
  8976. const int halfway = (start + end) >> 1;
  8977. if (halfway == start)
  8978. {
  8979. if (newElement >= data.elements [halfway])
  8980. insertInternal (start + 1, newElement);
  8981. else
  8982. insertInternal (start, newElement);
  8983. break;
  8984. }
  8985. else if (newElement >= data.elements [halfway])
  8986. start = halfway;
  8987. else
  8988. end = halfway;
  8989. }
  8990. }
  8991. }
  8992. /** Adds elements from an array to this set.
  8993. @param elementsToAdd the array of elements to add
  8994. @param numElementsToAdd how many elements are in this other array
  8995. @see add
  8996. */
  8997. void addArray (const ElementType* elementsToAdd,
  8998. int numElementsToAdd) throw()
  8999. {
  9000. const ScopedLockType lock (getLock());
  9001. while (--numElementsToAdd >= 0)
  9002. add (*elementsToAdd++);
  9003. }
  9004. /** Adds elements from another set to this one.
  9005. @param setToAddFrom the set from which to copy the elements
  9006. @param startIndex the first element of the other set to start copying from
  9007. @param numElementsToAdd how many elements to add from the other set. If this
  9008. value is negative or greater than the number of available elements,
  9009. all available elements will be copied.
  9010. @see add
  9011. */
  9012. template <class OtherSetType>
  9013. void addSet (const OtherSetType& setToAddFrom,
  9014. int startIndex = 0,
  9015. int numElementsToAdd = -1) throw()
  9016. {
  9017. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  9018. {
  9019. const ScopedLockType lock2 (getLock());
  9020. jassert (this != &setToAddFrom);
  9021. if (this != &setToAddFrom)
  9022. {
  9023. if (startIndex < 0)
  9024. {
  9025. jassertfalse;
  9026. startIndex = 0;
  9027. }
  9028. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  9029. numElementsToAdd = setToAddFrom.size() - startIndex;
  9030. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  9031. }
  9032. }
  9033. }
  9034. /** Removes an element from the set.
  9035. This will remove the element at a given index.
  9036. If the index passed in is out-of-range, nothing will happen.
  9037. @param indexToRemove the index of the element to remove
  9038. @returns the element that has been removed
  9039. @see removeValue, removeRange
  9040. */
  9041. ElementType remove (const int indexToRemove) throw()
  9042. {
  9043. const ScopedLockType lock (getLock());
  9044. if (isPositiveAndBelow (indexToRemove, numUsed))
  9045. {
  9046. --numUsed;
  9047. ElementType* const e = data.elements + indexToRemove;
  9048. ElementType const removed = *e;
  9049. const int numberToShift = numUsed - indexToRemove;
  9050. if (numberToShift > 0)
  9051. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  9052. if ((numUsed << 1) < data.numAllocated)
  9053. minimiseStorageOverheads();
  9054. return removed;
  9055. }
  9056. return 0;
  9057. }
  9058. /** Removes an item from the set.
  9059. This will remove the given element from the set, if it's there.
  9060. @param valueToRemove the object to try to remove
  9061. @see remove, removeRange
  9062. */
  9063. void removeValue (const ElementType valueToRemove) throw()
  9064. {
  9065. const ScopedLockType lock (getLock());
  9066. remove (indexOf (valueToRemove));
  9067. }
  9068. /** Removes any elements which are also in another set.
  9069. @param otherSet the other set in which to look for elements to remove
  9070. @see removeValuesNotIn, remove, removeValue, removeRange
  9071. */
  9072. template <class OtherSetType>
  9073. void removeValuesIn (const OtherSetType& otherSet) throw()
  9074. {
  9075. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  9076. const ScopedLockType lock2 (getLock());
  9077. if (this == &otherSet)
  9078. {
  9079. clear();
  9080. }
  9081. else
  9082. {
  9083. if (otherSet.size() > 0)
  9084. {
  9085. for (int i = numUsed; --i >= 0;)
  9086. if (otherSet.contains (data.elements [i]))
  9087. remove (i);
  9088. }
  9089. }
  9090. }
  9091. /** Removes any elements which are not found in another set.
  9092. Only elements which occur in this other set will be retained.
  9093. @param otherSet the set in which to look for elements NOT to remove
  9094. @see removeValuesIn, remove, removeValue, removeRange
  9095. */
  9096. template <class OtherSetType>
  9097. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  9098. {
  9099. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  9100. const ScopedLockType lock2 (getLock());
  9101. if (this != &otherSet)
  9102. {
  9103. if (otherSet.size() <= 0)
  9104. {
  9105. clear();
  9106. }
  9107. else
  9108. {
  9109. for (int i = numUsed; --i >= 0;)
  9110. if (! otherSet.contains (data.elements [i]))
  9111. remove (i);
  9112. }
  9113. }
  9114. }
  9115. /** Reduces the amount of storage being used by the set.
  9116. Sets typically allocate slightly more storage than they need, and after
  9117. removing elements, they may have quite a lot of unused space allocated.
  9118. This method will reduce the amount of allocated storage to a minimum.
  9119. */
  9120. void minimiseStorageOverheads() throw()
  9121. {
  9122. const ScopedLockType lock (getLock());
  9123. data.shrinkToNoMoreThan (numUsed);
  9124. }
  9125. /** Returns the CriticalSection that locks this array.
  9126. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  9127. an object of ScopedLockType as an RAII lock for it.
  9128. */
  9129. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  9130. /** Returns the type of scoped lock to use for locking this array */
  9131. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  9132. private:
  9133. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  9134. int numUsed;
  9135. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  9136. {
  9137. data.ensureAllocatedSize (numUsed + 1);
  9138. ElementType* const insertPos = data.elements + indexToInsertAt;
  9139. const int numberToMove = numUsed - indexToInsertAt;
  9140. if (numberToMove > 0)
  9141. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  9142. *insertPos = newElement;
  9143. ++numUsed;
  9144. }
  9145. };
  9146. #if JUCE_MSVC
  9147. #pragma warning (pop)
  9148. #endif
  9149. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  9150. /*** End of inlined file: juce_SortedSet.h ***/
  9151. #endif
  9152. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  9153. /*** Start of inlined file: juce_SparseSet.h ***/
  9154. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  9155. #define __JUCE_SPARSESET_JUCEHEADER__
  9156. /*** Start of inlined file: juce_Range.h ***/
  9157. #ifndef __JUCE_RANGE_JUCEHEADER__
  9158. #define __JUCE_RANGE_JUCEHEADER__
  9159. /** A general-purpose range object, that simply represents any linear range with
  9160. a start and end point.
  9161. The templated parameter is expected to be a primitive integer or floating point
  9162. type, though class types could also be used if they behave in a number-like way.
  9163. */
  9164. template <typename ValueType>
  9165. class Range
  9166. {
  9167. public:
  9168. /** Constructs an empty range. */
  9169. Range() throw()
  9170. : start (ValueType()), end (ValueType())
  9171. {
  9172. }
  9173. /** Constructs a range with given start and end values. */
  9174. Range (const ValueType start_, const ValueType end_) throw()
  9175. : start (start_), end (jmax (start_, end_))
  9176. {
  9177. }
  9178. /** Constructs a copy of another range. */
  9179. Range (const Range& other) throw()
  9180. : start (other.start), end (other.end)
  9181. {
  9182. }
  9183. /** Copies another range object. */
  9184. Range& operator= (const Range& other) throw()
  9185. {
  9186. start = other.start;
  9187. end = other.end;
  9188. return *this;
  9189. }
  9190. /** Destructor. */
  9191. ~Range() throw()
  9192. {
  9193. }
  9194. /** Returns the range that lies between two positions (in either order). */
  9195. static const Range between (const ValueType position1, const ValueType position2) throw()
  9196. {
  9197. return (position1 < position2) ? Range (position1, position2)
  9198. : Range (position2, position1);
  9199. }
  9200. /** Returns a range with the specified start position and a length of zero. */
  9201. static const Range emptyRange (const ValueType start) throw()
  9202. {
  9203. return Range (start, start);
  9204. }
  9205. /** Returns the start of the range. */
  9206. inline ValueType getStart() const throw() { return start; }
  9207. /** Returns the length of the range. */
  9208. inline ValueType getLength() const throw() { return end - start; }
  9209. /** Returns the end of the range. */
  9210. inline ValueType getEnd() const throw() { return end; }
  9211. /** Returns true if the range has a length of zero. */
  9212. inline bool isEmpty() const throw() { return start == end; }
  9213. /** Changes the start position of the range, leaving the end position unchanged.
  9214. If the new start position is higher than the current end of the range, the end point
  9215. will be pushed along to equal it, leaving an empty range at the new position.
  9216. */
  9217. void setStart (const ValueType newStart) throw()
  9218. {
  9219. start = newStart;
  9220. if (end < newStart)
  9221. end = newStart;
  9222. }
  9223. /** Returns a range with the same end as this one, but a different start.
  9224. If the new start position is higher than the current end of the range, the end point
  9225. will be pushed along to equal it, returning an empty range at the new position.
  9226. */
  9227. const Range withStart (const ValueType newStart) const throw()
  9228. {
  9229. return Range (newStart, jmax (newStart, end));
  9230. }
  9231. /** Returns a range with the same length as this one, but moved to have the given start position. */
  9232. const Range movedToStartAt (const ValueType newStart) const throw()
  9233. {
  9234. return Range (newStart, end + (newStart - start));
  9235. }
  9236. /** Changes the end position of the range, leaving the start unchanged.
  9237. If the new end position is below the current start of the range, the start point
  9238. will be pushed back to equal the new end point.
  9239. */
  9240. void setEnd (const ValueType newEnd) throw()
  9241. {
  9242. end = newEnd;
  9243. if (newEnd < start)
  9244. start = newEnd;
  9245. }
  9246. /** Returns a range with the same start position as this one, but a different end.
  9247. If the new end position is below the current start of the range, the start point
  9248. will be pushed back to equal the new end point.
  9249. */
  9250. const Range withEnd (const ValueType newEnd) const throw()
  9251. {
  9252. return Range (jmin (start, newEnd), newEnd);
  9253. }
  9254. /** Returns a range with the same length as this one, but moved to have the given start position. */
  9255. const Range movedToEndAt (const ValueType newEnd) const throw()
  9256. {
  9257. return Range (start + (newEnd - end), newEnd);
  9258. }
  9259. /** Changes the length of the range.
  9260. Lengths less than zero are treated as zero.
  9261. */
  9262. void setLength (const ValueType newLength) throw()
  9263. {
  9264. end = start + jmax (ValueType(), newLength);
  9265. }
  9266. /** Returns a range with the same start as this one, but a different length.
  9267. Lengths less than zero are treated as zero.
  9268. */
  9269. const Range withLength (const ValueType newLength) const throw()
  9270. {
  9271. return Range (start, start + newLength);
  9272. }
  9273. /** Adds an amount to the start and end of the range. */
  9274. inline const Range& operator+= (const ValueType amountToAdd) throw()
  9275. {
  9276. start += amountToAdd;
  9277. end += amountToAdd;
  9278. return *this;
  9279. }
  9280. /** Subtracts an amount from the start and end of the range. */
  9281. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  9282. {
  9283. start -= amountToSubtract;
  9284. end -= amountToSubtract;
  9285. return *this;
  9286. }
  9287. /** Returns a range that is equal to this one with an amount added to its
  9288. start and end.
  9289. */
  9290. const Range operator+ (const ValueType amountToAdd) const throw()
  9291. {
  9292. return Range (start + amountToAdd, end + amountToAdd);
  9293. }
  9294. /** Returns a range that is equal to this one with the specified amount
  9295. subtracted from its start and end. */
  9296. const Range operator- (const ValueType amountToSubtract) const throw()
  9297. {
  9298. return Range (start - amountToSubtract, end - amountToSubtract);
  9299. }
  9300. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  9301. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  9302. /** Returns true if the given position lies inside this range. */
  9303. bool contains (const ValueType position) const throw()
  9304. {
  9305. return start <= position && position < end;
  9306. }
  9307. /** Returns the nearest value to the one supplied, which lies within the range. */
  9308. ValueType clipValue (const ValueType value) const throw()
  9309. {
  9310. return jlimit (start, end, value);
  9311. }
  9312. /** Returns true if the given range lies entirely inside this range. */
  9313. bool contains (const Range& other) const throw()
  9314. {
  9315. return start <= other.start && end >= other.end;
  9316. }
  9317. /** Returns true if the given range intersects this one. */
  9318. bool intersects (const Range& other) const throw()
  9319. {
  9320. return other.start < end && start < other.end;
  9321. }
  9322. /** Returns the range that is the intersection of the two ranges, or an empty range
  9323. with an undefined start position if they don't overlap. */
  9324. const Range getIntersectionWith (const Range& other) const throw()
  9325. {
  9326. return Range (jmax (start, other.start),
  9327. jmin (end, other.end));
  9328. }
  9329. /** Returns the smallest range that contains both this one and the other one. */
  9330. const Range getUnionWith (const Range& other) const throw()
  9331. {
  9332. return Range (jmin (start, other.start),
  9333. jmax (end, other.end));
  9334. }
  9335. /** Returns a given range, after moving it forwards or backwards to fit it
  9336. within this range.
  9337. If the supplied range has a greater length than this one, the return value
  9338. will be this range.
  9339. Otherwise, if the supplied range is smaller than this one, the return value
  9340. will be the new range, shifted forwards or backwards so that it doesn't extend
  9341. beyond this one, but keeping its original length.
  9342. */
  9343. const Range constrainRange (const Range& rangeToConstrain) const throw()
  9344. {
  9345. const ValueType otherLen = rangeToConstrain.getLength();
  9346. return getLength() <= otherLen
  9347. ? *this
  9348. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  9349. }
  9350. private:
  9351. ValueType start, end;
  9352. };
  9353. #endif // __JUCE_RANGE_JUCEHEADER__
  9354. /*** End of inlined file: juce_Range.h ***/
  9355. /**
  9356. Holds a set of primitive values, storing them as a set of ranges.
  9357. This container acts like an array, but can efficiently hold large continguous
  9358. ranges of values. It's quite a specialised class, mostly useful for things
  9359. like keeping the set of selected rows in a listbox.
  9360. The type used as a template paramter must be an integer type, such as int, short,
  9361. int64, etc.
  9362. */
  9363. template <class Type>
  9364. class SparseSet
  9365. {
  9366. public:
  9367. /** Creates a new empty set. */
  9368. SparseSet()
  9369. {
  9370. }
  9371. /** Creates a copy of another SparseSet. */
  9372. SparseSet (const SparseSet<Type>& other)
  9373. : values (other.values)
  9374. {
  9375. }
  9376. /** Destructor. */
  9377. ~SparseSet()
  9378. {
  9379. }
  9380. /** Clears the set. */
  9381. void clear()
  9382. {
  9383. values.clear();
  9384. }
  9385. /** Checks whether the set is empty.
  9386. This is much quicker than using (size() == 0).
  9387. */
  9388. bool isEmpty() const throw()
  9389. {
  9390. return values.size() == 0;
  9391. }
  9392. /** Returns the number of values in the set.
  9393. Because of the way the data is stored, this method can take longer if there
  9394. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  9395. are any items.
  9396. */
  9397. Type size() const
  9398. {
  9399. Type total (0);
  9400. for (int i = 0; i < values.size(); i += 2)
  9401. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  9402. return total;
  9403. }
  9404. /** Returns one of the values in the set.
  9405. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  9406. @returns the value at this index, or 0 if it's out-of-range
  9407. */
  9408. Type operator[] (Type index) const
  9409. {
  9410. for (int i = 0; i < values.size(); i += 2)
  9411. {
  9412. const Type start (values.getUnchecked (i));
  9413. const Type len (values.getUnchecked (i + 1) - start);
  9414. if (index < len)
  9415. return start + index;
  9416. index -= len;
  9417. }
  9418. return Type (0);
  9419. }
  9420. /** Checks whether a particular value is in the set. */
  9421. bool contains (const Type valueToLookFor) const
  9422. {
  9423. for (int i = 0; i < values.size(); ++i)
  9424. if (valueToLookFor < values.getUnchecked(i))
  9425. return (i & 1) != 0;
  9426. return false;
  9427. }
  9428. /** Returns the number of contiguous blocks of values.
  9429. @see getRange
  9430. */
  9431. int getNumRanges() const throw()
  9432. {
  9433. return values.size() >> 1;
  9434. }
  9435. /** Returns one of the contiguous ranges of values stored.
  9436. @param rangeIndex the index of the range to look up, between 0
  9437. and (getNumRanges() - 1)
  9438. @see getTotalRange
  9439. */
  9440. const Range<Type> getRange (const int rangeIndex) const
  9441. {
  9442. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  9443. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  9444. values.getUnchecked ((rangeIndex << 1) + 1));
  9445. else
  9446. return Range<Type>();
  9447. }
  9448. /** Returns the range between the lowest and highest values in the set.
  9449. @see getRange
  9450. */
  9451. const Range<Type> getTotalRange() const
  9452. {
  9453. if (values.size() > 0)
  9454. {
  9455. jassert ((values.size() & 1) == 0);
  9456. return Range<Type> (values.getUnchecked (0),
  9457. values.getUnchecked (values.size() - 1));
  9458. }
  9459. return Range<Type>();
  9460. }
  9461. /** Adds a range of contiguous values to the set.
  9462. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  9463. */
  9464. void addRange (const Range<Type>& range)
  9465. {
  9466. jassert (range.getLength() >= 0);
  9467. if (range.getLength() > 0)
  9468. {
  9469. removeRange (range);
  9470. values.addUsingDefaultSort (range.getStart());
  9471. values.addUsingDefaultSort (range.getEnd());
  9472. simplify();
  9473. }
  9474. }
  9475. /** Removes a range of values from the set.
  9476. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  9477. */
  9478. void removeRange (const Range<Type>& rangeToRemove)
  9479. {
  9480. jassert (rangeToRemove.getLength() >= 0);
  9481. if (rangeToRemove.getLength() > 0
  9482. && values.size() > 0
  9483. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  9484. && values.getUnchecked(0) < rangeToRemove.getEnd())
  9485. {
  9486. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  9487. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  9488. const bool onAtEnd = contains (lastValue);
  9489. for (int i = values.size(); --i >= 0;)
  9490. {
  9491. if (values.getUnchecked(i) <= lastValue)
  9492. {
  9493. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  9494. {
  9495. values.remove (i);
  9496. if (--i < 0)
  9497. break;
  9498. }
  9499. break;
  9500. }
  9501. }
  9502. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  9503. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  9504. simplify();
  9505. }
  9506. }
  9507. /** Does an XOR of the values in a given range. */
  9508. void invertRange (const Range<Type>& range)
  9509. {
  9510. SparseSet newItems;
  9511. newItems.addRange (range);
  9512. int i;
  9513. for (i = getNumRanges(); --i >= 0;)
  9514. newItems.removeRange (getRange (i));
  9515. removeRange (range);
  9516. for (i = newItems.getNumRanges(); --i >= 0;)
  9517. addRange (newItems.getRange(i));
  9518. }
  9519. /** Checks whether any part of a given range overlaps any part of this set. */
  9520. bool overlapsRange (const Range<Type>& range)
  9521. {
  9522. if (range.getLength() > 0)
  9523. {
  9524. for (int i = getNumRanges(); --i >= 0;)
  9525. {
  9526. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  9527. return false;
  9528. if (values.getUnchecked (i << 1) < range.getEnd())
  9529. return true;
  9530. }
  9531. }
  9532. return false;
  9533. }
  9534. /** Checks whether the whole of a given range is contained within this one. */
  9535. bool containsRange (const Range<Type>& range)
  9536. {
  9537. if (range.getLength() > 0)
  9538. {
  9539. for (int i = getNumRanges(); --i >= 0;)
  9540. {
  9541. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  9542. return false;
  9543. if (values.getUnchecked (i << 1) <= range.getStart()
  9544. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  9545. return true;
  9546. }
  9547. }
  9548. return false;
  9549. }
  9550. bool operator== (const SparseSet<Type>& other) throw()
  9551. {
  9552. return values == other.values;
  9553. }
  9554. bool operator!= (const SparseSet<Type>& other) throw()
  9555. {
  9556. return values != other.values;
  9557. }
  9558. private:
  9559. // alternating start/end values of ranges of values that are present.
  9560. Array<Type, DummyCriticalSection> values;
  9561. void simplify()
  9562. {
  9563. jassert ((values.size() & 1) == 0);
  9564. for (int i = values.size(); --i > 0;)
  9565. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  9566. values.removeRange (--i, 2);
  9567. }
  9568. };
  9569. #endif // __JUCE_SPARSESET_JUCEHEADER__
  9570. /*** End of inlined file: juce_SparseSet.h ***/
  9571. #endif
  9572. #ifndef __JUCE_VALUE_JUCEHEADER__
  9573. /*** Start of inlined file: juce_Value.h ***/
  9574. #ifndef __JUCE_VALUE_JUCEHEADER__
  9575. #define __JUCE_VALUE_JUCEHEADER__
  9576. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  9577. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  9578. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  9579. /*** Start of inlined file: juce_CallbackMessage.h ***/
  9580. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  9581. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  9582. /*** Start of inlined file: juce_Message.h ***/
  9583. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  9584. #define __JUCE_MESSAGE_JUCEHEADER__
  9585. class MessageListener;
  9586. class MessageManager;
  9587. /** The base class for objects that can be delivered to a MessageListener.
  9588. The simplest Message object contains a few integer and pointer parameters
  9589. that the user can set, and this is enough for a lot of purposes. For passing more
  9590. complex data, subclasses of Message can also be used.
  9591. @see MessageListener, MessageManager, ActionListener, ChangeListener
  9592. */
  9593. class JUCE_API Message : public ReferenceCountedObject
  9594. {
  9595. public:
  9596. /** Creates an uninitialised message.
  9597. The class's variables will also be left uninitialised.
  9598. */
  9599. Message() throw();
  9600. /** Creates a message object, filling in the member variables.
  9601. The corresponding public member variables will be set from the parameters
  9602. passed in.
  9603. */
  9604. Message (int intParameter1,
  9605. int intParameter2,
  9606. int intParameter3,
  9607. void* pointerParameter) throw();
  9608. /** Destructor. */
  9609. virtual ~Message();
  9610. // These values can be used for carrying simple data that the application needs to
  9611. // pass around. For more complex messages, just create a subclass.
  9612. int intParameter1; /**< user-defined integer value. */
  9613. int intParameter2; /**< user-defined integer value. */
  9614. int intParameter3; /**< user-defined integer value. */
  9615. void* pointerParameter; /**< user-defined pointer value. */
  9616. /** A typedef for pointers to messages. */
  9617. typedef ReferenceCountedObjectPtr <Message> Ptr;
  9618. private:
  9619. friend class MessageListener;
  9620. friend class MessageManager;
  9621. MessageListener* messageRecipient;
  9622. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Message);
  9623. };
  9624. #endif // __JUCE_MESSAGE_JUCEHEADER__
  9625. /*** End of inlined file: juce_Message.h ***/
  9626. /**
  9627. A message that calls a custom function when it gets delivered.
  9628. You can use this class to fire off actions that you want to be performed later
  9629. on the message thread.
  9630. Unlike other Message objects, these don't get sent to a MessageListener, you
  9631. just call the post() method to send them, and when they arrive, your
  9632. messageCallback() method will automatically be invoked.
  9633. Always create an instance of a CallbackMessage on the heap, as it will be
  9634. deleted automatically after the message has been delivered.
  9635. @see MessageListener, MessageManager, ActionListener, ChangeListener
  9636. */
  9637. class JUCE_API CallbackMessage : public Message
  9638. {
  9639. public:
  9640. CallbackMessage() throw();
  9641. /** Destructor. */
  9642. ~CallbackMessage();
  9643. /** Called when the message is delivered.
  9644. You should implement this method and make it do whatever action you want
  9645. to perform.
  9646. Note that like all other messages, this object will be deleted immediately
  9647. after this method has been invoked.
  9648. */
  9649. virtual void messageCallback() = 0;
  9650. /** Instead of sending this message to a MessageListener, just call this method
  9651. to post it to the event queue.
  9652. After you've called this, this object will belong to the MessageManager,
  9653. which will delete it later. So make sure you don't delete the object yourself,
  9654. call post() more than once, or call post() on a stack-based obect!
  9655. */
  9656. void post();
  9657. private:
  9658. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackMessage);
  9659. };
  9660. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  9661. /*** End of inlined file: juce_CallbackMessage.h ***/
  9662. /**
  9663. Has a callback method that is triggered asynchronously.
  9664. This object allows an asynchronous callback function to be triggered, for
  9665. tasks such as coalescing multiple updates into a single callback later on.
  9666. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  9667. message thread calling handleAsyncUpdate() as soon as it can.
  9668. */
  9669. class JUCE_API AsyncUpdater
  9670. {
  9671. public:
  9672. /** Creates an AsyncUpdater object. */
  9673. AsyncUpdater();
  9674. /** Destructor.
  9675. If there are any pending callbacks when the object is deleted, these are lost.
  9676. */
  9677. virtual ~AsyncUpdater();
  9678. /** Causes the callback to be triggered at a later time.
  9679. This method returns immediately, having made sure that a callback
  9680. to the handleAsyncUpdate() method will occur as soon as possible.
  9681. If an update callback is already pending but hasn't happened yet, calls
  9682. to this method will be ignored.
  9683. It's thread-safe to call this method from any number of threads without
  9684. needing to worry about locking.
  9685. */
  9686. void triggerAsyncUpdate();
  9687. /** This will stop any pending updates from happening.
  9688. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  9689. callback happens, this will cancel the handleAsyncUpdate() callback.
  9690. Note that this method simply cancels the next callback - if a callback is already
  9691. in progress on a different thread, this won't block until it finishes, so there's
  9692. no guarantee that the callback isn't still running when you return from
  9693. */
  9694. void cancelPendingUpdate() throw();
  9695. /** If an update has been triggered and is pending, this will invoke it
  9696. synchronously.
  9697. Use this as a kind of "flush" operation - if an update is pending, the
  9698. handleAsyncUpdate() method will be called immediately; if no update is
  9699. pending, then nothing will be done.
  9700. Because this may invoke the callback, this method must only be called on
  9701. the main event thread.
  9702. */
  9703. void handleUpdateNowIfNeeded();
  9704. /** Returns true if there's an update callback in the pipeline. */
  9705. bool isUpdatePending() const throw();
  9706. /** Called back to do whatever your class needs to do.
  9707. This method is called by the message thread at the next convenient time
  9708. after the triggerAsyncUpdate() method has been called.
  9709. */
  9710. virtual void handleAsyncUpdate() = 0;
  9711. private:
  9712. ReferenceCountedObjectPtr<CallbackMessage> message;
  9713. Atomic<int>& getDeliveryFlag() const throw();
  9714. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  9715. };
  9716. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  9717. /*** End of inlined file: juce_AsyncUpdater.h ***/
  9718. /*** Start of inlined file: juce_ListenerList.h ***/
  9719. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  9720. #define __JUCE_LISTENERLIST_JUCEHEADER__
  9721. /**
  9722. Holds a set of objects and can invoke a member function callback on each object
  9723. in the set with a single call.
  9724. Use a ListenerList to manage a set of objects which need a callback, and you
  9725. can invoke a member function by simply calling call() or callChecked().
  9726. E.g.
  9727. @code
  9728. class MyListenerType
  9729. {
  9730. public:
  9731. void myCallbackMethod (int foo, bool bar);
  9732. };
  9733. ListenerList <MyListenerType> listeners;
  9734. listeners.add (someCallbackObjects...);
  9735. // This will invoke myCallbackMethod (1234, true) on each of the objects
  9736. // in the list...
  9737. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  9738. @endcode
  9739. If you add or remove listeners from the list during one of the callbacks - i.e. while
  9740. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  9741. will be mistakenly called after they've been removed, but it may mean that some of the
  9742. listeners could be called more than once, or not at all, depending on the list's order.
  9743. Sometimes, there's a chance that invoking one of the callbacks might result in the
  9744. list itself being deleted while it's still iterating - to survive this situation, you can
  9745. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  9746. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  9747. the list will check this after each callback to determine whether it should abort the
  9748. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  9749. which can be used to check when a Component has been deleted. See also
  9750. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  9751. */
  9752. template <class ListenerClass,
  9753. class ArrayType = Array <ListenerClass*> >
  9754. class ListenerList
  9755. {
  9756. // Horrible macros required to support VC6/7..
  9757. #ifndef DOXYGEN
  9758. #if JUCE_VC8_OR_EARLIER
  9759. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  9760. #define LL_PARAM(a) Q##a& param##a
  9761. #else
  9762. #define LL_TEMPLATE(a) typename P##a
  9763. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  9764. #endif
  9765. #endif
  9766. public:
  9767. /** Creates an empty list. */
  9768. ListenerList()
  9769. {
  9770. }
  9771. /** Destructor. */
  9772. ~ListenerList()
  9773. {
  9774. }
  9775. /** Adds a listener to the list.
  9776. A listener can only be added once, so if the listener is already in the list,
  9777. this method has no effect.
  9778. @see remove
  9779. */
  9780. void add (ListenerClass* const listenerToAdd)
  9781. {
  9782. // Listeners can't be null pointers!
  9783. jassert (listenerToAdd != 0);
  9784. if (listenerToAdd != 0)
  9785. listeners.addIfNotAlreadyThere (listenerToAdd);
  9786. }
  9787. /** Removes a listener from the list.
  9788. If the listener wasn't in the list, this has no effect.
  9789. */
  9790. void remove (ListenerClass* const listenerToRemove)
  9791. {
  9792. // Listeners can't be null pointers!
  9793. jassert (listenerToRemove != 0);
  9794. listeners.removeValue (listenerToRemove);
  9795. }
  9796. /** Returns the number of registered listeners. */
  9797. int size() const throw()
  9798. {
  9799. return listeners.size();
  9800. }
  9801. /** Returns true if any listeners are registered. */
  9802. bool isEmpty() const throw()
  9803. {
  9804. return listeners.size() == 0;
  9805. }
  9806. /** Clears the list. */
  9807. void clear()
  9808. {
  9809. listeners.clear();
  9810. }
  9811. /** Returns true if the specified listener has been added to the list. */
  9812. bool contains (ListenerClass* const listener) const throw()
  9813. {
  9814. return listeners.contains (listener);
  9815. }
  9816. /** Calls a member function on each listener in the list, with no parameters. */
  9817. void call (void (ListenerClass::*callbackFunction) ())
  9818. {
  9819. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  9820. }
  9821. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  9822. See the class description for info about writing a bail-out checker. */
  9823. template <class BailOutCheckerType>
  9824. void callChecked (const BailOutCheckerType& bailOutChecker,
  9825. void (ListenerClass::*callbackFunction) ())
  9826. {
  9827. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  9828. (iter.getListener()->*callbackFunction) ();
  9829. }
  9830. /** Calls a member function on each listener in the list, with 1 parameter. */
  9831. template <LL_TEMPLATE(1)>
  9832. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  9833. {
  9834. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  9835. (iter.getListener()->*callbackFunction) (param1);
  9836. }
  9837. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  9838. See the class description for info about writing a bail-out checker. */
  9839. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  9840. void callChecked (const BailOutCheckerType& bailOutChecker,
  9841. void (ListenerClass::*callbackFunction) (P1),
  9842. LL_PARAM(1))
  9843. {
  9844. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  9845. (iter.getListener()->*callbackFunction) (param1);
  9846. }
  9847. /** Calls a member function on each listener in the list, with 2 parameters. */
  9848. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9849. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  9850. LL_PARAM(1), LL_PARAM(2))
  9851. {
  9852. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  9853. (iter.getListener()->*callbackFunction) (param1, param2);
  9854. }
  9855. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  9856. See the class description for info about writing a bail-out checker. */
  9857. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9858. void callChecked (const BailOutCheckerType& bailOutChecker,
  9859. void (ListenerClass::*callbackFunction) (P1, P2),
  9860. LL_PARAM(1), LL_PARAM(2))
  9861. {
  9862. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  9863. (iter.getListener()->*callbackFunction) (param1, param2);
  9864. }
  9865. /** Calls a member function on each listener in the list, with 3 parameters. */
  9866. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9867. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9868. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9869. {
  9870. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  9871. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9872. }
  9873. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  9874. See the class description for info about writing a bail-out checker. */
  9875. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9876. void callChecked (const BailOutCheckerType& bailOutChecker,
  9877. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9878. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9879. {
  9880. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  9881. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9882. }
  9883. /** Calls a member function on each listener in the list, with 4 parameters. */
  9884. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9885. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9886. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9887. {
  9888. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  9889. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9890. }
  9891. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  9892. See the class description for info about writing a bail-out checker. */
  9893. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9894. void callChecked (const BailOutCheckerType& bailOutChecker,
  9895. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9896. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9897. {
  9898. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  9899. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9900. }
  9901. /** Calls a member function on each listener in the list, with 5 parameters. */
  9902. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9903. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9904. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9905. {
  9906. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  9907. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9908. }
  9909. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  9910. See the class description for info about writing a bail-out checker. */
  9911. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9912. void callChecked (const BailOutCheckerType& bailOutChecker,
  9913. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9914. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9915. {
  9916. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  9917. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9918. }
  9919. /** A dummy bail-out checker that always returns false.
  9920. See the ListenerList notes for more info about bail-out checkers.
  9921. */
  9922. class DummyBailOutChecker
  9923. {
  9924. public:
  9925. inline bool shouldBailOut() const throw() { return false; }
  9926. };
  9927. /** Iterates the listeners in a ListenerList. */
  9928. template <class BailOutCheckerType, class ListType>
  9929. class Iterator
  9930. {
  9931. public:
  9932. Iterator (const ListType& list_)
  9933. : list (list_), index (list_.size())
  9934. {}
  9935. ~Iterator() {}
  9936. bool next()
  9937. {
  9938. if (index <= 0)
  9939. return false;
  9940. const int listSize = list.size();
  9941. if (--index < listSize)
  9942. return true;
  9943. index = listSize - 1;
  9944. return index >= 0;
  9945. }
  9946. bool next (const BailOutCheckerType& bailOutChecker)
  9947. {
  9948. return (! bailOutChecker.shouldBailOut()) && next();
  9949. }
  9950. typename ListType::ListenerType* getListener() const throw()
  9951. {
  9952. return list.getListeners().getUnchecked (index);
  9953. }
  9954. private:
  9955. const ListType& list;
  9956. int index;
  9957. JUCE_DECLARE_NON_COPYABLE (Iterator);
  9958. };
  9959. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  9960. typedef ListenerClass ListenerType;
  9961. const ArrayType& getListeners() const throw() { return listeners; }
  9962. private:
  9963. ArrayType listeners;
  9964. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  9965. #undef LL_TEMPLATE
  9966. #undef LL_PARAM
  9967. };
  9968. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  9969. /*** End of inlined file: juce_ListenerList.h ***/
  9970. /**
  9971. Represents a shared variant value.
  9972. A Value object contains a reference to a var object, and can get and set its value.
  9973. Listeners can be attached to be told when the value is changed.
  9974. The Value class is a wrapper around a shared, reference-counted underlying data
  9975. object - this means that multiple Value objects can all refer to the same piece of
  9976. data, allowing all of them to be notified when any of them changes it.
  9977. When you create a Value with its default constructor, it acts as a wrapper around a
  9978. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  9979. you can map the Value onto any kind of underlying data.
  9980. */
  9981. class JUCE_API Value
  9982. {
  9983. public:
  9984. /** Creates an empty Value, containing a void var. */
  9985. Value();
  9986. /** Creates a Value that refers to the same value as another one.
  9987. Note that this doesn't make a copy of the other value - both this and the other
  9988. Value will share the same underlying value, so that when either one alters it, both
  9989. will see it change.
  9990. */
  9991. Value (const Value& other);
  9992. /** Creates a Value that is set to the specified value. */
  9993. explicit Value (const var& initialValue);
  9994. /** Destructor. */
  9995. ~Value();
  9996. /** Returns the current value. */
  9997. const var getValue() const;
  9998. /** Returns the current value. */
  9999. operator const var() const;
  10000. /** Returns the value as a string.
  10001. This is alternative to writing things like "myValue.getValue().toString()".
  10002. */
  10003. const String toString() const;
  10004. /** Sets the current value.
  10005. You can also use operator= to set the value.
  10006. If there are any listeners registered, they will be notified of the
  10007. change asynchronously.
  10008. */
  10009. void setValue (const var& newValue);
  10010. /** Sets the current value.
  10011. This is the same as calling setValue().
  10012. If there are any listeners registered, they will be notified of the
  10013. change asynchronously.
  10014. */
  10015. Value& operator= (const var& newValue);
  10016. /** Makes this object refer to the same underlying ValueSource as another one.
  10017. Once this object has been connected to another one, changing either one
  10018. will update the other.
  10019. Existing listeners will still be registered after you call this method, and
  10020. they'll continue to receive messages when the new value changes.
  10021. */
  10022. void referTo (const Value& valueToReferTo);
  10023. /** Returns true if this value and the other one are references to the same value.
  10024. */
  10025. bool refersToSameSourceAs (const Value& other) const;
  10026. /** Compares two values.
  10027. This is a compare-by-value comparison, so is effectively the same as
  10028. saying (this->getValue() == other.getValue()).
  10029. */
  10030. bool operator== (const Value& other) const;
  10031. /** Compares two values.
  10032. This is a compare-by-value comparison, so is effectively the same as
  10033. saying (this->getValue() != other.getValue()).
  10034. */
  10035. bool operator!= (const Value& other) const;
  10036. /** Receives callbacks when a Value object changes.
  10037. @see Value::addListener
  10038. */
  10039. class JUCE_API Listener
  10040. {
  10041. public:
  10042. Listener() {}
  10043. virtual ~Listener() {}
  10044. /** Called when a Value object is changed.
  10045. Note that the Value object passed as a parameter may not be exactly the same
  10046. object that you registered the listener with - it might be a copy that refers
  10047. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  10048. */
  10049. virtual void valueChanged (Value& value) = 0;
  10050. };
  10051. /** Adds a listener to receive callbacks when the value changes.
  10052. The listener is added to this specific Value object, and not to the shared
  10053. object that it refers to. When this object is deleted, all the listeners will
  10054. be lost, even if other references to the same Value still exist. So when you're
  10055. adding a listener, make sure that you add it to a ValueTree instance that will last
  10056. for as long as you need the listener. In general, you'd never want to add a listener
  10057. to a local stack-based ValueTree, but more likely to one that's a member variable.
  10058. @see removeListener
  10059. */
  10060. void addListener (Listener* listener);
  10061. /** Removes a listener that was previously added with addListener(). */
  10062. void removeListener (Listener* listener);
  10063. /**
  10064. Used internally by the Value class as the base class for its shared value objects.
  10065. The Value class is essentially a reference-counted pointer to a shared instance
  10066. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  10067. ValueSource classes to allow Value objects to represent your own custom data items.
  10068. */
  10069. class JUCE_API ValueSource : public ReferenceCountedObject,
  10070. public AsyncUpdater
  10071. {
  10072. public:
  10073. ValueSource();
  10074. virtual ~ValueSource();
  10075. /** Returns the current value of this object. */
  10076. virtual const var getValue() const = 0;
  10077. /** Changes the current value.
  10078. This must also trigger a change message if the value actually changes.
  10079. */
  10080. virtual void setValue (const var& newValue) = 0;
  10081. /** Delivers a change message to all the listeners that are registered with
  10082. this value.
  10083. If dispatchSynchronously is true, the method will call all the listeners
  10084. before returning; otherwise it'll dispatch a message and make the call later.
  10085. */
  10086. void sendChangeMessage (bool dispatchSynchronously);
  10087. protected:
  10088. friend class Value;
  10089. SortedSet <Value*> valuesWithListeners;
  10090. void handleAsyncUpdate();
  10091. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  10092. };
  10093. /** Creates a Value object that uses this valueSource object as its underlying data. */
  10094. explicit Value (ValueSource* valueSource);
  10095. /** Returns the ValueSource that this value is referring to. */
  10096. ValueSource& getValueSource() throw() { return *value; }
  10097. private:
  10098. friend class ValueSource;
  10099. ReferenceCountedObjectPtr <ValueSource> value;
  10100. ListenerList <Listener> listeners;
  10101. void callListeners();
  10102. // This is disallowed to avoid confusion about whether it should
  10103. // do a by-value or by-reference copy.
  10104. Value& operator= (const Value& other);
  10105. };
  10106. /** Writes a Value to an OutputStream as a UTF8 string. */
  10107. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  10108. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  10109. typedef Value::Listener ValueListener;
  10110. #endif // __JUCE_VALUE_JUCEHEADER__
  10111. /*** End of inlined file: juce_Value.h ***/
  10112. #endif
  10113. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  10114. /*** Start of inlined file: juce_ValueTree.h ***/
  10115. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  10116. #define __JUCE_VALUETREE_JUCEHEADER__
  10117. /*** Start of inlined file: juce_UndoManager.h ***/
  10118. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  10119. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  10120. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  10121. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  10122. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  10123. /*** Start of inlined file: juce_ChangeListener.h ***/
  10124. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  10125. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  10126. class ChangeBroadcaster;
  10127. /**
  10128. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  10129. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  10130. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  10131. ChangeListener is used to receive these callbacks.
  10132. Note that the major difference between an ActionListener and a ChangeListener
  10133. is that for a ChangeListener, multiple changes will be coalesced into fewer
  10134. callbacks, but ActionListeners perform one callback for every event posted.
  10135. @see ChangeBroadcaster, ActionListener
  10136. */
  10137. class JUCE_API ChangeListener
  10138. {
  10139. public:
  10140. /** Destructor. */
  10141. virtual ~ChangeListener() {}
  10142. /** Your subclass should implement this method to receive the callback.
  10143. @param source the ChangeBroadcaster that triggered the callback.
  10144. */
  10145. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  10146. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  10147. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  10148. private: virtual int changeListenerCallback (void*) { return 0; }
  10149. #endif
  10150. };
  10151. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  10152. /*** End of inlined file: juce_ChangeListener.h ***/
  10153. /**
  10154. Holds a list of ChangeListeners, and sends messages to them when instructed.
  10155. @see ChangeListener
  10156. */
  10157. class JUCE_API ChangeBroadcaster
  10158. {
  10159. public:
  10160. /** Creates an ChangeBroadcaster. */
  10161. ChangeBroadcaster() throw();
  10162. /** Destructor. */
  10163. virtual ~ChangeBroadcaster();
  10164. /** Registers a listener to receive change callbacks from this broadcaster.
  10165. Trying to add a listener that's already on the list will have no effect.
  10166. */
  10167. void addChangeListener (ChangeListener* listener);
  10168. /** Unregisters a listener from the list.
  10169. If the listener isn't on the list, this won't have any effect.
  10170. */
  10171. void removeChangeListener (ChangeListener* listener);
  10172. /** Removes all listeners from the list. */
  10173. void removeAllChangeListeners();
  10174. /** Causes an asynchronous change message to be sent to all the registered listeners.
  10175. The message will be delivered asynchronously by the main message thread, so this
  10176. method will return immediately. To call the listeners synchronously use
  10177. sendSynchronousChangeMessage().
  10178. */
  10179. void sendChangeMessage();
  10180. /** Sends a synchronous change message to all the registered listeners.
  10181. This will immediately call all the listeners that are registered. For thread-safety
  10182. reasons, you must only call this method on the main message thread.
  10183. @see dispatchPendingMessages
  10184. */
  10185. void sendSynchronousChangeMessage();
  10186. /** If a change message has been sent but not yet dispatched, this will call
  10187. sendSynchronousChangeMessage() to make the callback immediately.
  10188. For thread-safety reasons, you must only call this method on the main message thread.
  10189. */
  10190. void dispatchPendingMessages();
  10191. private:
  10192. class ChangeBroadcasterCallback : public AsyncUpdater
  10193. {
  10194. public:
  10195. ChangeBroadcasterCallback();
  10196. void handleAsyncUpdate();
  10197. ChangeBroadcaster* owner;
  10198. };
  10199. friend class ChangeBroadcasterCallback;
  10200. ChangeBroadcasterCallback callback;
  10201. ListenerList <ChangeListener> changeListeners;
  10202. void callListeners();
  10203. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  10204. };
  10205. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  10206. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  10207. /*** Start of inlined file: juce_UndoableAction.h ***/
  10208. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  10209. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  10210. /**
  10211. Used by the UndoManager class to store an action which can be done
  10212. and undone.
  10213. @see UndoManager
  10214. */
  10215. class JUCE_API UndoableAction
  10216. {
  10217. protected:
  10218. /** Creates an action. */
  10219. UndoableAction() throw() {}
  10220. public:
  10221. /** Destructor. */
  10222. virtual ~UndoableAction() {}
  10223. /** Overridden by a subclass to perform the action.
  10224. This method is called by the UndoManager, and shouldn't be used directly by
  10225. applications.
  10226. Be careful not to make any calls in a perform() method that could call
  10227. recursively back into the UndoManager::perform() method
  10228. @returns true if the action could be performed.
  10229. @see UndoManager::perform
  10230. */
  10231. virtual bool perform() = 0;
  10232. /** Overridden by a subclass to undo the action.
  10233. This method is called by the UndoManager, and shouldn't be used directly by
  10234. applications.
  10235. Be careful not to make any calls in an undo() method that could call
  10236. recursively back into the UndoManager::perform() method
  10237. @returns true if the action could be undone without any errors.
  10238. @see UndoManager::perform
  10239. */
  10240. virtual bool undo() = 0;
  10241. /** Returns a value to indicate how much memory this object takes up.
  10242. Because the UndoManager keeps a list of UndoableActions, this is used
  10243. to work out how much space each one will take up, so that the UndoManager
  10244. can work out how many to keep.
  10245. The default value returned here is 10 - units are arbitrary and
  10246. don't have to be accurate.
  10247. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  10248. UndoManager::setMaxNumberOfStoredUnits
  10249. */
  10250. virtual int getSizeInUnits() { return 10; }
  10251. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  10252. If possible, this method should create and return a single action that does the same job as
  10253. this one followed by the supplied action.
  10254. If it's not possible to merge the two actions, the method should return zero.
  10255. */
  10256. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  10257. };
  10258. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  10259. /*** End of inlined file: juce_UndoableAction.h ***/
  10260. /**
  10261. Manages a list of undo/redo commands.
  10262. An UndoManager object keeps a list of past actions and can use these actions
  10263. to move backwards and forwards through an undo history.
  10264. To use it, create subclasses of UndoableAction which perform all the
  10265. actions you need, then when you need to actually perform an action, create one
  10266. and pass it to the UndoManager's perform() method.
  10267. The manager also uses the concept of 'transactions' to group the actions
  10268. together - all actions performed between calls to beginNewTransaction() are
  10269. grouped together and are all undone/redone as a group.
  10270. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  10271. when actions are performed or undone.
  10272. @see UndoableAction
  10273. */
  10274. class JUCE_API UndoManager : public ChangeBroadcaster
  10275. {
  10276. public:
  10277. /** Creates an UndoManager.
  10278. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  10279. to indicate how much storage it takes up
  10280. (UndoableAction::getSizeInUnits()), so this
  10281. lets you specify the maximum total number of
  10282. units that the undomanager is allowed to
  10283. keep in memory before letting the older actions
  10284. drop off the end of the list.
  10285. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  10286. that will be kept, even if this involves exceeding
  10287. the amount of space specified in maxNumberOfUnitsToKeep
  10288. */
  10289. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  10290. int minimumTransactionsToKeep = 30);
  10291. /** Destructor. */
  10292. ~UndoManager();
  10293. /** Deletes all stored actions in the list. */
  10294. void clearUndoHistory();
  10295. /** Returns the current amount of space to use for storing UndoableAction objects.
  10296. @see setMaxNumberOfStoredUnits
  10297. */
  10298. int getNumberOfUnitsTakenUpByStoredCommands() const;
  10299. /** Sets the amount of space that can be used for storing UndoableAction objects.
  10300. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  10301. to indicate how much storage it takes up
  10302. (UndoableAction::getSizeInUnits()), so this
  10303. lets you specify the maximum total number of
  10304. units that the undomanager is allowed to
  10305. keep in memory before letting the older actions
  10306. drop off the end of the list.
  10307. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  10308. that will be kept, even if this involves exceeding
  10309. the amount of space specified in maxNumberOfUnitsToKeep
  10310. @see getNumberOfUnitsTakenUpByStoredCommands
  10311. */
  10312. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  10313. int minimumTransactionsToKeep);
  10314. /** Performs an action and adds it to the undo history list.
  10315. @param action the action to perform - this will be deleted by the UndoManager
  10316. when no longer needed
  10317. @param actionName if this string is non-empty, the current transaction will be
  10318. given this name; if it's empty, the current transaction name will
  10319. be left unchanged. See setCurrentTransactionName()
  10320. @returns true if the command succeeds - see UndoableAction::perform
  10321. @see beginNewTransaction
  10322. */
  10323. bool perform (UndoableAction* action,
  10324. const String& actionName = String::empty);
  10325. /** Starts a new group of actions that together will be treated as a single transaction.
  10326. All actions that are passed to the perform() method between calls to this
  10327. method are grouped together and undone/redone together by a single call to
  10328. undo() or redo().
  10329. @param actionName a description of the transaction that is about to be
  10330. performed
  10331. */
  10332. void beginNewTransaction (const String& actionName = String::empty);
  10333. /** Changes the name stored for the current transaction.
  10334. Each transaction is given a name when the beginNewTransaction() method is
  10335. called, but this can be used to change that name without starting a new
  10336. transaction.
  10337. */
  10338. void setCurrentTransactionName (const String& newName);
  10339. /** Returns true if there's at least one action in the list to undo.
  10340. @see getUndoDescription, undo, canRedo
  10341. */
  10342. bool canUndo() const;
  10343. /** Returns the description of the transaction that would be next to get undone.
  10344. The description returned is the one that was passed into beginNewTransaction
  10345. before the set of actions was performed.
  10346. @see undo
  10347. */
  10348. const String getUndoDescription() const;
  10349. /** Tries to roll-back the last transaction.
  10350. @returns true if the transaction can be undone, and false if it fails, or
  10351. if there aren't any transactions to undo
  10352. */
  10353. bool undo();
  10354. /** Tries to roll-back any actions that were added to the current transaction.
  10355. This will perform an undo() only if there are some actions in the undo list
  10356. that were added after the last call to beginNewTransaction().
  10357. This is useful because it lets you call beginNewTransaction(), then
  10358. perform an operation which may or may not actually perform some actions, and
  10359. then call this method to get rid of any actions that might have been done
  10360. without it rolling back the previous transaction if nothing was actually
  10361. done.
  10362. @returns true if any actions were undone.
  10363. */
  10364. bool undoCurrentTransactionOnly();
  10365. /** Returns a list of the UndoableAction objects that have been performed during the
  10366. transaction that is currently open.
  10367. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  10368. were to be called now.
  10369. The first item in the list is the earliest action performed.
  10370. */
  10371. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  10372. /** Returns the number of UndoableAction objects that have been performed during the
  10373. transaction that is currently open.
  10374. @see getActionsInCurrentTransaction
  10375. */
  10376. int getNumActionsInCurrentTransaction() const;
  10377. /** Returns true if there's at least one action in the list to redo.
  10378. @see getRedoDescription, redo, canUndo
  10379. */
  10380. bool canRedo() const;
  10381. /** Returns the description of the transaction that would be next to get redone.
  10382. The description returned is the one that was passed into beginNewTransaction
  10383. before the set of actions was performed.
  10384. @see redo
  10385. */
  10386. const String getRedoDescription() const;
  10387. /** Tries to redo the last transaction that was undone.
  10388. @returns true if the transaction can be redone, and false if it fails, or
  10389. if there aren't any transactions to redo
  10390. */
  10391. bool redo();
  10392. private:
  10393. OwnedArray <OwnedArray <UndoableAction> > transactions;
  10394. StringArray transactionNames;
  10395. String currentTransactionName;
  10396. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  10397. bool newTransaction, reentrancyCheck;
  10398. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  10399. };
  10400. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  10401. /*** End of inlined file: juce_UndoManager.h ***/
  10402. /**
  10403. A powerful tree structure that can be used to hold free-form data, and which can
  10404. handle its own undo and redo behaviour.
  10405. A ValueTree contains a list of named properties as var objects, and also holds
  10406. any number of sub-trees.
  10407. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  10408. they're simply a lightweight reference to a shared data container. Creating a copy
  10409. of another ValueTree simply creates a new reference to the same underlying object - to
  10410. make a separate, deep copy of a tree you should explicitly call createCopy().
  10411. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  10412. and much of the structure of a ValueTree is similar to an XmlElement tree.
  10413. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  10414. contain text elements, the conversion works well and makes a good serialisation
  10415. format. They can also be serialised to a binary format, which is very fast and compact.
  10416. All the methods that change data take an optional UndoManager, which will be used
  10417. to track any changes to the object. For this to work, you have to be careful to
  10418. consistently always use the same UndoManager for all operations to any node inside
  10419. the tree.
  10420. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  10421. one tree to another, be careful to always remove it first, before adding it. This
  10422. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  10423. assertions if you try to do anything dangerous, but there are still plenty of ways it
  10424. could go wrong.
  10425. Listeners can be added to a ValueTree to be told when properies change and when
  10426. nodes are added or removed.
  10427. @see var, XmlElement
  10428. */
  10429. class JUCE_API ValueTree
  10430. {
  10431. public:
  10432. /** Creates an empty, invalid ValueTree.
  10433. A ValueTree that is created with this constructor can't actually be used for anything,
  10434. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  10435. To create a real one, use the constructor that takes a string.
  10436. @see ValueTree::invalid
  10437. */
  10438. ValueTree() throw();
  10439. /** Creates an empty ValueTree with the given type name.
  10440. Like an XmlElement, each ValueTree node has a type, which you can access with
  10441. getType() and hasType().
  10442. */
  10443. explicit ValueTree (const Identifier& type);
  10444. /** Creates a reference to another ValueTree. */
  10445. ValueTree (const ValueTree& other);
  10446. /** Makes this object reference another node. */
  10447. ValueTree& operator= (const ValueTree& other);
  10448. /** Destructor. */
  10449. ~ValueTree();
  10450. /** Returns true if both this and the other tree node refer to the same underlying structure.
  10451. Note that this isn't a value comparison - two independently-created trees which
  10452. contain identical data are not considered equal.
  10453. */
  10454. bool operator== (const ValueTree& other) const throw();
  10455. /** Returns true if this and the other node refer to different underlying structures.
  10456. Note that this isn't a value comparison - two independently-created trees which
  10457. contain identical data are not considered equal.
  10458. */
  10459. bool operator!= (const ValueTree& other) const throw();
  10460. /** Performs a deep comparison between the properties and children of two trees.
  10461. If all the properties and children of the two trees are the same (recursively), this
  10462. returns true.
  10463. The normal operator==() only checks whether two trees refer to the same shared data
  10464. structure, so use this method if you need to do a proper value comparison.
  10465. */
  10466. bool isEquivalentTo (const ValueTree& other) const;
  10467. /** Returns true if this node refers to some valid data.
  10468. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  10469. call to getChild().
  10470. */
  10471. bool isValid() const { return object != 0; }
  10472. /** Returns a deep copy of this tree and all its sub-nodes. */
  10473. ValueTree createCopy() const;
  10474. /** Returns the type of this node.
  10475. The type is specified when the ValueTree is created.
  10476. @see hasType
  10477. */
  10478. const Identifier getType() const;
  10479. /** Returns true if the node has this type.
  10480. The comparison is case-sensitive.
  10481. */
  10482. bool hasType (const Identifier& typeName) const;
  10483. /** Returns the value of a named property.
  10484. If no such property has been set, this will return a void variant.
  10485. You can also use operator[] to get a property.
  10486. @see var, setProperty, hasProperty
  10487. */
  10488. const var& getProperty (const Identifier& name) const;
  10489. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  10490. If no such property has been set, this will return the value of defaultReturnValue.
  10491. You can also use operator[] and getProperty to get a property.
  10492. @see var, getProperty, setProperty, hasProperty
  10493. */
  10494. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10495. /** Returns the value of a named property.
  10496. If no such property has been set, this will return a void variant. This is the same as
  10497. calling getProperty().
  10498. @see getProperty
  10499. */
  10500. const var& operator[] (const Identifier& name) const;
  10501. /** Changes a named property of the node.
  10502. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10503. so that this change can be undone.
  10504. @see var, getProperty, removeProperty
  10505. */
  10506. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  10507. /** Returns true if the node contains a named property. */
  10508. bool hasProperty (const Identifier& name) const;
  10509. /** Removes a property from the node.
  10510. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10511. so that this change can be undone.
  10512. */
  10513. void removeProperty (const Identifier& name, UndoManager* undoManager);
  10514. /** Removes all properties from the node.
  10515. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10516. so that this change can be undone.
  10517. */
  10518. void removeAllProperties (UndoManager* undoManager);
  10519. /** Returns the total number of properties that the node contains.
  10520. @see getProperty.
  10521. */
  10522. int getNumProperties() const;
  10523. /** Returns the identifier of the property with a given index.
  10524. @see getNumProperties
  10525. */
  10526. const Identifier getPropertyName (int index) const;
  10527. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  10528. The Value object will maintain a reference to this tree, and will use the undo manager when
  10529. it needs to change the value. Attaching a Value::Listener to the value object will provide
  10530. callbacks whenever the property changes.
  10531. */
  10532. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  10533. /** Returns the number of child nodes belonging to this one.
  10534. @see getChild
  10535. */
  10536. int getNumChildren() const;
  10537. /** Returns one of this node's child nodes.
  10538. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  10539. whether a node is valid).
  10540. */
  10541. ValueTree getChild (int index) const;
  10542. /** Returns the first child node with the speficied type name.
  10543. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10544. whether a node is valid).
  10545. @see getOrCreateChildWithName
  10546. */
  10547. ValueTree getChildWithName (const Identifier& type) const;
  10548. /** Returns the first child node with the speficied type name, creating and adding
  10549. a child with this name if there wasn't already one there.
  10550. The only time this will return an invalid object is when the object that you're calling
  10551. the method on is itself invalid.
  10552. @see getChildWithName
  10553. */
  10554. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10555. /** Looks for the first child node that has the speficied property value.
  10556. This will scan the child nodes in order, until it finds one that has property that matches
  10557. the specified value.
  10558. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10559. whether a node is valid).
  10560. */
  10561. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10562. /** Adds a child to this node.
  10563. Make sure that the child is removed from any former parent node before calling this, or
  10564. you'll hit an assertion.
  10565. If the index is < 0 or greater than the current number of child nodes, the new node will
  10566. be added at the end of the list.
  10567. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10568. so that this change can be undone.
  10569. */
  10570. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  10571. /** Removes the specified child from this node's child-list.
  10572. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10573. so that this change can be undone.
  10574. */
  10575. void removeChild (const ValueTree& child, UndoManager* undoManager);
  10576. /** Removes a child from this node's child-list.
  10577. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10578. so that this change can be undone.
  10579. */
  10580. void removeChild (int childIndex, UndoManager* undoManager);
  10581. /** Removes all child-nodes from this node.
  10582. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10583. so that this change can be undone.
  10584. */
  10585. void removeAllChildren (UndoManager* undoManager);
  10586. /** Moves one of the children to a different index.
  10587. This will move the child to a specified index, shuffling along any intervening
  10588. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  10589. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10590. @param currentIndex the index of the item to be moved. If this isn't a
  10591. valid index, then nothing will be done
  10592. @param newIndex the index at which you'd like this item to end up. If this
  10593. is less than zero, the value will be moved to the end
  10594. of the list
  10595. @param undoManager the optional UndoManager to use to store this transaction
  10596. */
  10597. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  10598. /** Returns true if this node is anywhere below the specified parent node.
  10599. This returns true if the node is a child-of-a-child, as well as a direct child.
  10600. */
  10601. bool isAChildOf (const ValueTree& possibleParent) const;
  10602. /** Returns the index of a child item in this parent.
  10603. If the child isn't found, this returns -1.
  10604. */
  10605. int indexOf (const ValueTree& child) const;
  10606. /** Returns the parent node that contains this one.
  10607. If the node has no parent, this will return an invalid node. (See isValid() to find out
  10608. whether a node is valid).
  10609. */
  10610. ValueTree getParent() const;
  10611. /** Returns one of this node's siblings in its parent's child list.
  10612. The delta specifies how far to move through the list, so a value of 1 would return the node
  10613. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  10614. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  10615. */
  10616. ValueTree getSibling (int delta) const;
  10617. /** Creates an XmlElement that holds a complete image of this node and all its children.
  10618. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  10619. be used to recreate a similar node by calling fromXml()
  10620. @see fromXml
  10621. */
  10622. XmlElement* createXml() const;
  10623. /** Tries to recreate a node from its XML representation.
  10624. This isn't designed to cope with random XML data - for a sensible result, it should only
  10625. be fed XML that was created by the createXml() method.
  10626. */
  10627. static ValueTree fromXml (const XmlElement& xml);
  10628. /** Stores this tree (and all its children) in a binary format.
  10629. Once written, the data can be read back with readFromStream().
  10630. It's much faster to load/save your tree in binary form than as XML, but
  10631. obviously isn't human-readable.
  10632. */
  10633. void writeToStream (OutputStream& output);
  10634. /** Reloads a tree from a stream that was written with writeToStream(). */
  10635. static ValueTree readFromStream (InputStream& input);
  10636. /** Reloads a tree from a data block that was written with writeToStream(). */
  10637. static ValueTree readFromData (const void* data, size_t numBytes);
  10638. /** Listener class for events that happen to a ValueTree.
  10639. To get events from a ValueTree, make your class implement this interface, and use
  10640. ValueTree::addListener() and ValueTree::removeListener() to register it.
  10641. */
  10642. class JUCE_API Listener
  10643. {
  10644. public:
  10645. /** Destructor. */
  10646. virtual ~Listener() {}
  10647. /** This method is called when a property of this node (or of one of its sub-nodes) has
  10648. changed.
  10649. The tree parameter indicates which tree has had its property changed, and the property
  10650. parameter indicates the property.
  10651. Note that when you register a listener to a tree, it will receive this callback for
  10652. property changes in that tree, and also for any of its children, (recursively, at any depth).
  10653. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10654. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10655. */
  10656. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  10657. const Identifier& property) = 0;
  10658. /** This method is called when a child sub-tree is added or removed.
  10659. The tree parameter indicates the tree whose child was added or removed.
  10660. Note that when you register a listener to a tree, it will receive this callback for
  10661. child changes in that tree, and also in any of its children, (recursively, at any depth).
  10662. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10663. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10664. */
  10665. virtual void valueTreeChildrenChanged (ValueTree& treeWhoseChildHasChanged) = 0;
  10666. /** This method is called when a tree has been added or removed from a parent node.
  10667. This callback happens when the tree to which the listener was registered is added or
  10668. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  10669. the listener is registered, and not to any of its children.
  10670. */
  10671. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  10672. };
  10673. /** Adds a listener to receive callbacks when this node is changed.
  10674. The listener is added to this specific ValueTree object, and not to the shared
  10675. object that it refers to. When this object is deleted, all the listeners will
  10676. be lost, even if other references to the same ValueTree still exist. And if you
  10677. use the operator= to make this refer to a different ValueTree, any listeners will
  10678. begin listening to changes to the new tree instead of the old one.
  10679. When you're adding a listener, make sure that you add it to a ValueTree instance that
  10680. will last for as long as you need the listener. In general, you'd never want to add a
  10681. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  10682. @see removeListener
  10683. */
  10684. void addListener (Listener* listener);
  10685. /** Removes a listener that was previously added with addListener(). */
  10686. void removeListener (Listener* listener);
  10687. /** This method uses a comparator object to sort the tree's children into order.
  10688. The object provided must have a method of the form:
  10689. @code
  10690. int compareElements (const ValueTree& first, const ValueTree& second);
  10691. @endcode
  10692. ..and this method must return:
  10693. - a value of < 0 if the first comes before the second
  10694. - a value of 0 if the two objects are equivalent
  10695. - a value of > 0 if the second comes before the first
  10696. To improve performance, the compareElements() method can be declared as static or const.
  10697. @param comparator the comparator to use for comparing elements.
  10698. @param undoManager optional UndoManager for storing the changes
  10699. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  10700. equivalent will be kept in the order in which they currently appear in the array.
  10701. This is slower to perform, but may be important in some cases. If it's false, a
  10702. faster algorithm is used, but equivalent elements may be rearranged.
  10703. */
  10704. template <typename ElementComparator>
  10705. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  10706. {
  10707. if (object != 0)
  10708. {
  10709. ReferenceCountedArray <SharedObject> sortedList (object->children);
  10710. ComparatorAdapter <ElementComparator> adapter (comparator);
  10711. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  10712. object->reorderChildren (sortedList, undoManager);
  10713. }
  10714. }
  10715. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  10716. This invalid object is equivalent to ValueTree created with its default constructor.
  10717. */
  10718. static const ValueTree invalid;
  10719. private:
  10720. class SetPropertyAction;
  10721. friend class SetPropertyAction;
  10722. class AddOrRemoveChildAction;
  10723. friend class AddOrRemoveChildAction;
  10724. class MoveChildAction;
  10725. friend class MoveChildAction;
  10726. class JUCE_API SharedObject : public ReferenceCountedObject
  10727. {
  10728. public:
  10729. explicit SharedObject (const Identifier& type);
  10730. SharedObject (const SharedObject& other);
  10731. ~SharedObject();
  10732. const Identifier type;
  10733. NamedValueSet properties;
  10734. ReferenceCountedArray <SharedObject> children;
  10735. SortedSet <ValueTree*> valueTreesWithListeners;
  10736. SharedObject* parent;
  10737. void sendPropertyChangeMessage (const Identifier& property);
  10738. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  10739. void sendChildChangeMessage();
  10740. void sendChildChangeMessage (ValueTree& tree);
  10741. void sendParentChangeMessage();
  10742. const var& getProperty (const Identifier& name) const;
  10743. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10744. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  10745. bool hasProperty (const Identifier& name) const;
  10746. void removeProperty (const Identifier& name, UndoManager*);
  10747. void removeAllProperties (UndoManager*);
  10748. bool isAChildOf (const SharedObject* possibleParent) const;
  10749. int indexOf (const ValueTree& child) const;
  10750. ValueTree getChildWithName (const Identifier& type) const;
  10751. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10752. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10753. void addChild (SharedObject* child, int index, UndoManager*);
  10754. void removeChild (int childIndex, UndoManager*);
  10755. void removeAllChildren (UndoManager*);
  10756. void moveChild (int currentIndex, int newIndex, UndoManager*);
  10757. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  10758. bool isEquivalentTo (const SharedObject& other) const;
  10759. XmlElement* createXml() const;
  10760. private:
  10761. SharedObject& operator= (const SharedObject&);
  10762. JUCE_LEAK_DETECTOR (SharedObject);
  10763. };
  10764. template <typename ElementComparator>
  10765. class ComparatorAdapter
  10766. {
  10767. public:
  10768. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  10769. int compareElements (SharedObject* const first, SharedObject* const second)
  10770. {
  10771. return comparator.compareElements (ValueTree (first), ValueTree (second));
  10772. }
  10773. private:
  10774. ElementComparator& comparator;
  10775. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  10776. };
  10777. friend class SharedObject;
  10778. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  10779. SharedObjectPtr object;
  10780. ListenerList <Listener> listeners;
  10781. #if JUCE_MSVC && ! DOXYGEN
  10782. public: // (workaround for VC6)
  10783. #endif
  10784. explicit ValueTree (SharedObject*);
  10785. };
  10786. #endif // __JUCE_VALUETREE_JUCEHEADER__
  10787. /*** End of inlined file: juce_ValueTree.h ***/
  10788. #endif
  10789. #ifndef __JUCE_VARIANT_JUCEHEADER__
  10790. #endif
  10791. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10792. /*** Start of inlined file: juce_FileLogger.h ***/
  10793. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10794. #define __JUCE_FILELOGGER_JUCEHEADER__
  10795. /**
  10796. A simple implemenation of a Logger that writes to a file.
  10797. @see Logger
  10798. */
  10799. class JUCE_API FileLogger : public Logger
  10800. {
  10801. public:
  10802. /** Creates a FileLogger for a given file.
  10803. @param fileToWriteTo the file that to use - new messages will be appended
  10804. to the file. If the file doesn't exist, it will be created,
  10805. along with any parent directories that are needed.
  10806. @param welcomeMessage when opened, the logger will write a header to the log, along
  10807. with the current date and time, and this welcome message
  10808. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  10809. but is larger than this number of bytes, then the start of the
  10810. file will be truncated to keep the size down. This prevents a log
  10811. file getting ridiculously large over time. The file will be truncated
  10812. at a new-line boundary. If this value is less than zero, no size limit
  10813. will be imposed; if it's zero, the file will always be deleted. Note that
  10814. the size is only checked once when this object is created - any logging
  10815. that is done later will be appended without any checking
  10816. */
  10817. FileLogger (const File& fileToWriteTo,
  10818. const String& welcomeMessage,
  10819. const int maxInitialFileSizeBytes = 128 * 1024);
  10820. /** Destructor. */
  10821. ~FileLogger();
  10822. void logMessage (const String& message);
  10823. const File getLogFile() const { return logFile; }
  10824. /** Helper function to create a log file in the correct place for this platform.
  10825. On Windows this will return a logger with a path such as:
  10826. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  10827. On the Mac it'll create something like:
  10828. ~/Library/Logs/[logFileName]
  10829. The method might return 0 if the file can't be created for some reason.
  10830. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  10831. it's best to use the something like the name of your application here.
  10832. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  10833. call it "log.txt" because if it goes in a directory with logs
  10834. from other applications (as it will do on the Mac) then no-one
  10835. will know which one is yours!
  10836. @param welcomeMessage a message that will be written to the log when it's opened.
  10837. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  10838. */
  10839. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  10840. const String& logFileName,
  10841. const String& welcomeMessage,
  10842. const int maxInitialFileSizeBytes = 128 * 1024);
  10843. private:
  10844. File logFile;
  10845. CriticalSection logLock;
  10846. void trimFileSize (int maxFileSizeBytes) const;
  10847. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  10848. };
  10849. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  10850. /*** End of inlined file: juce_FileLogger.h ***/
  10851. #endif
  10852. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10853. /*** Start of inlined file: juce_Initialisation.h ***/
  10854. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10855. #define __JUCE_INITIALISATION_JUCEHEADER__
  10856. /** Initialises Juce's GUI classes.
  10857. If you're embedding Juce into an application that uses its own event-loop rather
  10858. than using the START_JUCE_APPLICATION macro, call this function before making any
  10859. Juce calls, to make sure things are initialised correctly.
  10860. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10861. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10862. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  10863. */
  10864. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  10865. /** Clears up any static data being used by Juce's GUI classes.
  10866. If you're embedding Juce into an application that uses its own event-loop rather
  10867. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  10868. code to clean up any juce objects that might be lying around.
  10869. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  10870. */
  10871. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  10872. /** Initialises the core parts of Juce.
  10873. If you're embedding Juce into either a command-line program, call this function
  10874. at the start of your main() function to make sure that Juce is initialised correctly.
  10875. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10876. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10877. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  10878. */
  10879. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI();
  10880. /** Clears up any static data being used by Juce's non-gui core classes.
  10881. If you're embedding Juce into either a command-line program, call this function
  10882. at the end of your main() function if you want to make sure any Juce objects are
  10883. cleaned up correctly.
  10884. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  10885. */
  10886. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI();
  10887. /** A utility object that helps you initialise and shutdown Juce correctly
  10888. using an RAII pattern.
  10889. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  10890. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  10891. make sure that these functions are matched correctly.
  10892. This class is particularly handy to use at the beginning of a console app's
  10893. main() function, because it'll take care of shutting down whenever you return
  10894. from the main() call.
  10895. @see ScopedJuceInitialiser_GUI
  10896. */
  10897. class ScopedJuceInitialiser_NonGUI
  10898. {
  10899. public:
  10900. /** The constructor simply calls initialiseJuce_NonGUI(). */
  10901. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  10902. /** The destructor simply calls shutdownJuce_NonGUI(). */
  10903. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  10904. };
  10905. /** A utility object that helps you initialise and shutdown Juce correctly
  10906. using an RAII pattern.
  10907. When an instance of this class is created, it calls initialiseJuce_GUI(),
  10908. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  10909. make sure that these functions are matched correctly.
  10910. This class is particularly handy to use at the beginning of a console app's
  10911. main() function, because it'll take care of shutting down whenever you return
  10912. from the main() call.
  10913. @see ScopedJuceInitialiser_NonGUI
  10914. */
  10915. class ScopedJuceInitialiser_GUI
  10916. {
  10917. public:
  10918. /** The constructor simply calls initialiseJuce_GUI(). */
  10919. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  10920. /** The destructor simply calls shutdownJuce_GUI(). */
  10921. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  10922. };
  10923. /*
  10924. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  10925. AppSubClass is the name of a class derived from JUCEApplication.
  10926. See the JUCEApplication class documentation (juce_Application.h) for more details.
  10927. */
  10928. #if defined (JUCE_GCC) || defined (__MWERKS__)
  10929. #define START_JUCE_APPLICATION(AppClass) \
  10930. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  10931. int main (int argc, char* argv[]) \
  10932. { \
  10933. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  10934. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  10935. }
  10936. #elif JUCE_WINDOWS
  10937. #ifdef _CONSOLE
  10938. #define START_JUCE_APPLICATION(AppClass) \
  10939. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  10940. int main (int, char* argv[]) \
  10941. { \
  10942. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  10943. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  10944. }
  10945. #elif ! defined (_AFXDLL)
  10946. #ifdef _WINDOWS_
  10947. #define START_JUCE_APPLICATION(AppClass) \
  10948. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  10949. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  10950. { \
  10951. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  10952. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  10953. }
  10954. #else
  10955. #define START_JUCE_APPLICATION(AppClass) \
  10956. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  10957. int __stdcall WinMain (int, int, const char*, int) \
  10958. { \
  10959. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  10960. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  10961. }
  10962. #endif
  10963. #endif
  10964. #endif
  10965. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  10966. /*** End of inlined file: juce_Initialisation.h ***/
  10967. #endif
  10968. #ifndef __JUCE_LOGGER_JUCEHEADER__
  10969. #endif
  10970. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10971. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  10972. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10973. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10974. /** A timer for measuring performance of code and dumping the results to a file.
  10975. e.g. @code
  10976. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  10977. for (;;)
  10978. {
  10979. pc.start();
  10980. doSomethingFishy();
  10981. pc.stop();
  10982. }
  10983. @endcode
  10984. In this example, the time of each period between calling start/stop will be
  10985. measured and averaged over 50 runs, and the results printed to a file
  10986. every 50 times round the loop.
  10987. */
  10988. class JUCE_API PerformanceCounter
  10989. {
  10990. public:
  10991. /** Creates a PerformanceCounter object.
  10992. @param counterName the name used when printing out the statistics
  10993. @param runsPerPrintout the number of start/stop iterations before calling
  10994. printStatistics()
  10995. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  10996. the results are just written to the debugger output
  10997. */
  10998. PerformanceCounter (const String& counterName,
  10999. int runsPerPrintout = 100,
  11000. const File& loggingFile = File::nonexistent);
  11001. /** Destructor. */
  11002. ~PerformanceCounter();
  11003. /** Starts timing.
  11004. @see stop
  11005. */
  11006. void start();
  11007. /** Stops timing and prints out the results.
  11008. The number of iterations before doing a printout of the
  11009. results is set in the constructor.
  11010. @see start
  11011. */
  11012. void stop();
  11013. /** Dumps the current metrics to the debugger output and to a file.
  11014. As well as using Logger::outputDebugString to print the results,
  11015. this will write then to the file specified in the constructor (if
  11016. this was valid).
  11017. */
  11018. void printStatistics();
  11019. private:
  11020. String name;
  11021. int numRuns, runsPerPrint;
  11022. double totalTime;
  11023. int64 started;
  11024. File outputFile;
  11025. };
  11026. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  11027. /*** End of inlined file: juce_PerformanceCounter.h ***/
  11028. #endif
  11029. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  11030. #endif
  11031. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  11032. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  11033. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  11034. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  11035. /**
  11036. A collection of miscellaneous platform-specific utilities.
  11037. */
  11038. class JUCE_API PlatformUtilities
  11039. {
  11040. public:
  11041. /** Plays the operating system's default alert 'beep' sound. */
  11042. static void beep();
  11043. /** Tries to launch the system's default reader for a given file or URL. */
  11044. static bool openDocument (const String& documentURL, const String& parameters);
  11045. /** Tries to launch the system's default email app to let the user create an email.
  11046. */
  11047. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  11048. const String& emailSubject,
  11049. const String& bodyText,
  11050. const StringArray& filesToAttach);
  11051. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  11052. /** MAC ONLY - Turns a Core CF String into a juce one. */
  11053. static const String cfStringToJuceString (CFStringRef cfString);
  11054. /** MAC ONLY - Turns a juce string into a Core CF one. */
  11055. static CFStringRef juceStringToCFString (const String& s);
  11056. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  11057. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  11058. /** MAC ONLY - Turns an FSRef into a juce string path. */
  11059. static const String makePathFromFSRef (FSRef* file);
  11060. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  11061. their precomposed equivalents.
  11062. */
  11063. static const String convertToPrecomposedUnicode (const String& s);
  11064. /** MAC ONLY - Gets the type of a file from the file's resources. */
  11065. static OSType getTypeOfFile (const String& filename);
  11066. /** MAC ONLY - Returns true if this file is actually a bundle. */
  11067. static bool isBundle (const String& filename);
  11068. /** MAC ONLY - Adds an item to the dock */
  11069. static void addItemToDock (const File& file);
  11070. /** MAC ONLY - Returns the current OS version number.
  11071. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  11072. */
  11073. static int getOSXMinorVersionNumber();
  11074. #endif
  11075. #if JUCE_WINDOWS || DOXYGEN
  11076. // Some registry helper functions:
  11077. /** WIN32 ONLY - Returns a string from the registry.
  11078. The path is a string for the entire path of a value in the registry,
  11079. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  11080. */
  11081. static const String getRegistryValue (const String& regValuePath,
  11082. const String& defaultValue = String::empty);
  11083. /** WIN32 ONLY - Sets a registry value as a string.
  11084. This will take care of creating any groups needed to get to the given
  11085. registry value.
  11086. */
  11087. static void setRegistryValue (const String& regValuePath,
  11088. const String& value);
  11089. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  11090. static bool registryValueExists (const String& regValuePath);
  11091. /** WIN32 ONLY - Deletes a registry value. */
  11092. static void deleteRegistryValue (const String& regValuePath);
  11093. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  11094. static void deleteRegistryKey (const String& regKeyPath);
  11095. /** WIN32 ONLY - Creates a file association in the registry.
  11096. This lets you set the exe that should be launched by a given file extension.
  11097. @param fileExtension the file extension to associate, including the
  11098. initial dot, e.g. ".txt"
  11099. @param symbolicDescription a space-free short token to identify the file type
  11100. @param fullDescription a human-readable description of the file type
  11101. @param targetExecutable the executable that should be launched
  11102. @param iconResourceNumber the icon that gets displayed for the file type will be
  11103. found by looking up this resource number in the
  11104. executable. Pass 0 here to not use an icon
  11105. */
  11106. static void registerFileAssociation (const String& fileExtension,
  11107. const String& symbolicDescription,
  11108. const String& fullDescription,
  11109. const File& targetExecutable,
  11110. int iconResourceNumber);
  11111. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  11112. In a normal Juce application this will be set to the module handle
  11113. of the application executable.
  11114. If you're writing a DLL using Juce and plan to use any Juce messaging or
  11115. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  11116. to set the correct module handle in your DllMain() function, because
  11117. the win32 system relies on the correct instance handle when opening windows.
  11118. */
  11119. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  11120. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  11121. @see getCurrentModuleInstanceHandle()
  11122. */
  11123. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  11124. /** WIN32 ONLY - Gets the command-line params as a string.
  11125. This is needed to avoid unicode problems with the argc type params.
  11126. */
  11127. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  11128. #endif
  11129. /** Clears the floating point unit's flags.
  11130. Only has an effect under win32, currently.
  11131. */
  11132. static void fpuReset();
  11133. #if JUCE_LINUX || JUCE_WINDOWS
  11134. /** Loads a dynamically-linked library into the process's address space.
  11135. @param pathOrFilename the platform-dependent name and search path
  11136. @returns a handle which can be used by getProcedureEntryPoint(), or
  11137. zero if it fails.
  11138. @see freeDynamicLibrary, getProcedureEntryPoint
  11139. */
  11140. static void* loadDynamicLibrary (const String& pathOrFilename);
  11141. /** Frees a dynamically-linked library.
  11142. @param libraryHandle a handle created by loadDynamicLibrary
  11143. @see loadDynamicLibrary, getProcedureEntryPoint
  11144. */
  11145. static void freeDynamicLibrary (void* libraryHandle);
  11146. /** Finds a procedure call in a dynamically-linked library.
  11147. @param libraryHandle a library handle returned by loadDynamicLibrary
  11148. @param procedureName the name of the procedure call to try to load
  11149. @returns a pointer to the function if found, or 0 if it fails
  11150. @see loadDynamicLibrary
  11151. */
  11152. static void* getProcedureEntryPoint (void* libraryHandle,
  11153. const String& procedureName);
  11154. #endif
  11155. private:
  11156. PlatformUtilities();
  11157. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  11158. };
  11159. #if JUCE_MAC || JUCE_IOS
  11160. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  11161. using RAII.
  11162. */
  11163. class ScopedAutoReleasePool
  11164. {
  11165. public:
  11166. ScopedAutoReleasePool();
  11167. ~ScopedAutoReleasePool();
  11168. private:
  11169. void* pool;
  11170. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  11171. };
  11172. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool pool;
  11173. #else
  11174. #define JUCE_AUTORELEASEPOOL
  11175. #endif
  11176. #if JUCE_LINUX
  11177. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  11178. using an RAII approach.
  11179. */
  11180. class ScopedXLock
  11181. {
  11182. public:
  11183. /** Creating a ScopedXLock object locks the X display.
  11184. This uses XLockDisplay() to grab the display that Juce is using.
  11185. */
  11186. ScopedXLock();
  11187. /** Deleting a ScopedXLock object unlocks the X display.
  11188. This calls XUnlockDisplay() to release the lock.
  11189. */
  11190. ~ScopedXLock();
  11191. };
  11192. #endif
  11193. #if JUCE_MAC
  11194. /**
  11195. A wrapper class for picking up events from an Apple IR remote control device.
  11196. To use it, just create a subclass of this class, implementing the buttonPressed()
  11197. callback, then call start() and stop() to start or stop receiving events.
  11198. */
  11199. class JUCE_API AppleRemoteDevice
  11200. {
  11201. public:
  11202. AppleRemoteDevice();
  11203. virtual ~AppleRemoteDevice();
  11204. /** The set of buttons that may be pressed.
  11205. @see buttonPressed
  11206. */
  11207. enum ButtonType
  11208. {
  11209. menuButton = 0, /**< The menu button (if it's held for a short time). */
  11210. playButton, /**< The play button. */
  11211. plusButton, /**< The plus or volume-up button. */
  11212. minusButton, /**< The minus or volume-down button. */
  11213. rightButton, /**< The right button (if it's held for a short time). */
  11214. leftButton, /**< The left button (if it's held for a short time). */
  11215. rightButton_Long, /**< The right button (if it's held for a long time). */
  11216. leftButton_Long, /**< The menu button (if it's held for a long time). */
  11217. menuButton_Long, /**< The menu button (if it's held for a long time). */
  11218. playButtonSleepMode,
  11219. switched
  11220. };
  11221. /** Override this method to receive the callback about a button press.
  11222. The callback will happen on the application's message thread.
  11223. Some buttons trigger matching up and down events, in which the isDown parameter
  11224. will be true and then false. Others only send a single event when the
  11225. button is pressed.
  11226. */
  11227. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  11228. /** Starts the device running and responding to events.
  11229. Returns true if it managed to open the device.
  11230. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  11231. and will not be available to any other part of the system. If
  11232. false, it will be shared with other apps.
  11233. @see stop
  11234. */
  11235. bool start (bool inExclusiveMode);
  11236. /** Stops the device running.
  11237. @see start
  11238. */
  11239. void stop();
  11240. /** Returns true if the device has been started successfully.
  11241. */
  11242. bool isActive() const;
  11243. /** Returns the ID number of the remote, if it has sent one.
  11244. */
  11245. int getRemoteId() const { return remoteId; }
  11246. /** @internal */
  11247. void handleCallbackInternal();
  11248. private:
  11249. void* device;
  11250. void* queue;
  11251. int remoteId;
  11252. bool open (bool openInExclusiveMode);
  11253. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  11254. };
  11255. #endif
  11256. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  11257. /*** End of inlined file: juce_PlatformUtilities.h ***/
  11258. #endif
  11259. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  11260. #endif
  11261. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  11262. /*** Start of inlined file: juce_Singleton.h ***/
  11263. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  11264. #define __JUCE_SINGLETON_JUCEHEADER__
  11265. /*** Start of inlined file: juce_ScopedLock.h ***/
  11266. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  11267. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  11268. /**
  11269. Automatically locks and unlocks a CriticalSection object.
  11270. Use one of these as a local variable to control access to a CriticalSection.
  11271. e.g. @code
  11272. CriticalSection myCriticalSection;
  11273. for (;;)
  11274. {
  11275. const ScopedLock myScopedLock (myCriticalSection);
  11276. // myCriticalSection is now locked
  11277. ...do some stuff...
  11278. // myCriticalSection gets unlocked here.
  11279. }
  11280. @endcode
  11281. @see CriticalSection, ScopedUnlock
  11282. */
  11283. class JUCE_API ScopedLock
  11284. {
  11285. public:
  11286. /** Creates a ScopedLock.
  11287. As soon as it is created, this will lock the CriticalSection, and
  11288. when the ScopedLock object is deleted, the CriticalSection will
  11289. be unlocked.
  11290. Make sure this object is created and deleted by the same thread,
  11291. otherwise there are no guarantees what will happen! Best just to use it
  11292. as a local stack object, rather than creating one with the new() operator.
  11293. */
  11294. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  11295. /** Destructor.
  11296. The CriticalSection will be unlocked when the destructor is called.
  11297. Make sure this object is created and deleted by the same thread,
  11298. otherwise there are no guarantees what will happen!
  11299. */
  11300. inline ~ScopedLock() throw() { lock_.exit(); }
  11301. private:
  11302. const CriticalSection& lock_;
  11303. JUCE_DECLARE_NON_COPYABLE (ScopedLock);
  11304. };
  11305. /**
  11306. Automatically unlocks and re-locks a CriticalSection object.
  11307. This is the reverse of a ScopedLock object - instead of locking the critical
  11308. section for the lifetime of this object, it unlocks it.
  11309. Make sure you don't try to unlock critical sections that aren't actually locked!
  11310. e.g. @code
  11311. CriticalSection myCriticalSection;
  11312. for (;;)
  11313. {
  11314. const ScopedLock myScopedLock (myCriticalSection);
  11315. // myCriticalSection is now locked
  11316. ... do some stuff with it locked ..
  11317. while (xyz)
  11318. {
  11319. ... do some stuff with it locked ..
  11320. const ScopedUnlock unlocker (myCriticalSection);
  11321. // myCriticalSection is now unlocked for the remainder of this block,
  11322. // and re-locked at the end.
  11323. ...do some stuff with it unlocked ...
  11324. }
  11325. // myCriticalSection gets unlocked here.
  11326. }
  11327. @endcode
  11328. @see CriticalSection, ScopedLock
  11329. */
  11330. class ScopedUnlock
  11331. {
  11332. public:
  11333. /** Creates a ScopedUnlock.
  11334. As soon as it is created, this will unlock the CriticalSection, and
  11335. when the ScopedLock object is deleted, the CriticalSection will
  11336. be re-locked.
  11337. Make sure this object is created and deleted by the same thread,
  11338. otherwise there are no guarantees what will happen! Best just to use it
  11339. as a local stack object, rather than creating one with the new() operator.
  11340. */
  11341. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  11342. /** Destructor.
  11343. The CriticalSection will be unlocked when the destructor is called.
  11344. Make sure this object is created and deleted by the same thread,
  11345. otherwise there are no guarantees what will happen!
  11346. */
  11347. inline ~ScopedUnlock() throw() { lock_.enter(); }
  11348. private:
  11349. const CriticalSection& lock_;
  11350. JUCE_DECLARE_NON_COPYABLE (ScopedUnlock);
  11351. };
  11352. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  11353. /*** End of inlined file: juce_ScopedLock.h ***/
  11354. /**
  11355. Macro to declare member variables and methods for a singleton class.
  11356. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  11357. to the class's definition.
  11358. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  11359. implementation code.
  11360. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  11361. destructor, in case it is deleted by other means than deleteInstance()
  11362. Clients can then call the static method MyClass::getInstance() to get a pointer
  11363. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  11364. no instance currently exists.
  11365. e.g. @code
  11366. class MySingleton
  11367. {
  11368. public:
  11369. MySingleton()
  11370. {
  11371. }
  11372. ~MySingleton()
  11373. {
  11374. // this ensures that no dangling pointers are left when the
  11375. // singleton is deleted.
  11376. clearSingletonInstance();
  11377. }
  11378. juce_DeclareSingleton (MySingleton, false)
  11379. };
  11380. juce_ImplementSingleton (MySingleton)
  11381. // example of usage:
  11382. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  11383. ...
  11384. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  11385. @endcode
  11386. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  11387. than once during the process's lifetime - i.e. after you've created and deleted the
  11388. object, getInstance() will refuse to create another one. This can be useful to stop
  11389. objects being accidentally re-created during your app's shutdown code.
  11390. If you know that your object will only be created and deleted by a single thread, you
  11391. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  11392. of this one.
  11393. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  11394. */
  11395. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  11396. \
  11397. static classname* _singletonInstance; \
  11398. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  11399. \
  11400. static classname* JUCE_CALLTYPE getInstance() \
  11401. { \
  11402. if (_singletonInstance == 0) \
  11403. {\
  11404. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  11405. \
  11406. if (_singletonInstance == 0) \
  11407. { \
  11408. static bool alreadyInside = false; \
  11409. static bool createdOnceAlready = false; \
  11410. \
  11411. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  11412. jassert (! problem); \
  11413. if (! problem) \
  11414. { \
  11415. createdOnceAlready = true; \
  11416. alreadyInside = true; \
  11417. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  11418. alreadyInside = false; \
  11419. \
  11420. _singletonInstance = newObject; \
  11421. } \
  11422. } \
  11423. } \
  11424. \
  11425. return _singletonInstance; \
  11426. } \
  11427. \
  11428. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() throw() \
  11429. { \
  11430. return _singletonInstance; \
  11431. } \
  11432. \
  11433. static void JUCE_CALLTYPE deleteInstance() \
  11434. { \
  11435. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  11436. if (_singletonInstance != 0) \
  11437. { \
  11438. classname* const old = _singletonInstance; \
  11439. _singletonInstance = 0; \
  11440. delete old; \
  11441. } \
  11442. } \
  11443. \
  11444. void clearSingletonInstance() throw() \
  11445. { \
  11446. if (_singletonInstance == this) \
  11447. _singletonInstance = 0; \
  11448. }
  11449. /** This is a counterpart to the juce_DeclareSingleton macro.
  11450. After adding the juce_DeclareSingleton to the class definition, this macro has
  11451. to be used in the cpp file.
  11452. */
  11453. #define juce_ImplementSingleton(classname) \
  11454. \
  11455. classname* classname::_singletonInstance = 0; \
  11456. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  11457. /**
  11458. Macro to declare member variables and methods for a singleton class.
  11459. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  11460. section to make access to it thread-safe. If you know that your object will
  11461. only ever be created or deleted by a single thread, then this is a
  11462. more efficient version to use.
  11463. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  11464. than once during the process's lifetime - i.e. after you've created and deleted the
  11465. object, getInstance() will refuse to create another one. This can be useful to stop
  11466. objects being accidentally re-created during your app's shutdown code.
  11467. See the documentation for juce_DeclareSingleton for more information about
  11468. how to use it, the only difference being that you have to use
  11469. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11470. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  11471. */
  11472. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  11473. \
  11474. static classname* _singletonInstance; \
  11475. \
  11476. static classname* getInstance() \
  11477. { \
  11478. if (_singletonInstance == 0) \
  11479. { \
  11480. static bool alreadyInside = false; \
  11481. static bool createdOnceAlready = false; \
  11482. \
  11483. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  11484. jassert (! problem); \
  11485. if (! problem) \
  11486. { \
  11487. createdOnceAlready = true; \
  11488. alreadyInside = true; \
  11489. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  11490. alreadyInside = false; \
  11491. \
  11492. _singletonInstance = newObject; \
  11493. } \
  11494. } \
  11495. \
  11496. return _singletonInstance; \
  11497. } \
  11498. \
  11499. static inline classname* getInstanceWithoutCreating() throw() \
  11500. { \
  11501. return _singletonInstance; \
  11502. } \
  11503. \
  11504. static void deleteInstance() \
  11505. { \
  11506. if (_singletonInstance != 0) \
  11507. { \
  11508. classname* const old = _singletonInstance; \
  11509. _singletonInstance = 0; \
  11510. delete old; \
  11511. } \
  11512. } \
  11513. \
  11514. void clearSingletonInstance() throw() \
  11515. { \
  11516. if (_singletonInstance == this) \
  11517. _singletonInstance = 0; \
  11518. }
  11519. /**
  11520. Macro to declare member variables and methods for a singleton class.
  11521. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  11522. for recursion or repeated instantiation. It's intended for use as a lightweight
  11523. version of a singleton, where you're using it in very straightforward
  11524. circumstances and don't need the extra checking.
  11525. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  11526. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  11527. See the documentation for juce_DeclareSingleton for more information about
  11528. how to use it, the only difference being that you have to use
  11529. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11530. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  11531. */
  11532. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  11533. \
  11534. static classname* _singletonInstance; \
  11535. \
  11536. static classname* getInstance() \
  11537. { \
  11538. if (_singletonInstance == 0) \
  11539. _singletonInstance = new classname(); \
  11540. \
  11541. return _singletonInstance; \
  11542. } \
  11543. \
  11544. static inline classname* getInstanceWithoutCreating() throw() \
  11545. { \
  11546. return _singletonInstance; \
  11547. } \
  11548. \
  11549. static void deleteInstance() \
  11550. { \
  11551. if (_singletonInstance != 0) \
  11552. { \
  11553. classname* const old = _singletonInstance; \
  11554. _singletonInstance = 0; \
  11555. delete old; \
  11556. } \
  11557. } \
  11558. \
  11559. void clearSingletonInstance() throw() \
  11560. { \
  11561. if (_singletonInstance == this) \
  11562. _singletonInstance = 0; \
  11563. }
  11564. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  11565. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  11566. to the class definition, this macro has to be used somewhere in the cpp file.
  11567. */
  11568. #define juce_ImplementSingleton_SingleThreaded(classname) \
  11569. \
  11570. classname* classname::_singletonInstance = 0;
  11571. #endif // __JUCE_SINGLETON_JUCEHEADER__
  11572. /*** End of inlined file: juce_Singleton.h ***/
  11573. #endif
  11574. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  11575. #endif
  11576. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11577. /*** Start of inlined file: juce_SystemStats.h ***/
  11578. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11579. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  11580. /**
  11581. Contains methods for finding out about the current hardware and OS configuration.
  11582. */
  11583. class JUCE_API SystemStats
  11584. {
  11585. public:
  11586. /** Returns the current version of JUCE,
  11587. (just in case you didn't already know at compile-time.)
  11588. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  11589. */
  11590. static const String getJUCEVersion();
  11591. /** The set of possible results of the getOperatingSystemType() method.
  11592. */
  11593. enum OperatingSystemType
  11594. {
  11595. UnknownOS = 0,
  11596. MacOSX = 0x1000,
  11597. Linux = 0x2000,
  11598. Win95 = 0x4001,
  11599. Win98 = 0x4002,
  11600. WinNT351 = 0x4103,
  11601. WinNT40 = 0x4104,
  11602. Win2000 = 0x4105,
  11603. WinXP = 0x4106,
  11604. WinVista = 0x4107,
  11605. Windows7 = 0x4108,
  11606. Windows = 0x4000, /**< To test whether any version of Windows is running,
  11607. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  11608. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  11609. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  11610. };
  11611. /** Returns the type of operating system we're running on.
  11612. @returns one of the values from the OperatingSystemType enum.
  11613. @see getOperatingSystemName
  11614. */
  11615. static OperatingSystemType getOperatingSystemType();
  11616. /** Returns the name of the type of operating system we're running on.
  11617. @returns a string describing the OS type.
  11618. @see getOperatingSystemType
  11619. */
  11620. static const String getOperatingSystemName();
  11621. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  11622. */
  11623. static bool isOperatingSystem64Bit();
  11624. /** Returns the current user's name, if available.
  11625. @see getFullUserName()
  11626. */
  11627. static const String getLogonName();
  11628. /** Returns the current user's full name, if available.
  11629. On some OSes, this may just return the same value as getLogonName().
  11630. @see getLogonName()
  11631. */
  11632. static const String getFullUserName();
  11633. // CPU and memory information..
  11634. /** Returns the approximate CPU speed.
  11635. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  11636. what year you're reading this...)
  11637. */
  11638. static int getCpuSpeedInMegaherz();
  11639. /** Returns a string to indicate the CPU vendor.
  11640. Might not be known on some systems.
  11641. */
  11642. static const String getCpuVendor();
  11643. /** Checks whether Intel MMX instructions are available. */
  11644. static bool hasMMX() throw() { return cpuFlags.hasMMX; }
  11645. /** Checks whether Intel SSE instructions are available. */
  11646. static bool hasSSE() throw() { return cpuFlags.hasSSE; }
  11647. /** Checks whether Intel SSE2 instructions are available. */
  11648. static bool hasSSE2() throw() { return cpuFlags.hasSSE2; }
  11649. /** Checks whether AMD 3DNOW instructions are available. */
  11650. static bool has3DNow() throw() { return cpuFlags.has3DNow; }
  11651. /** Returns the number of CPUs. */
  11652. static int getNumCpus() throw() { return cpuFlags.numCpus; }
  11653. /** Finds out how much RAM is in the machine.
  11654. @returns the approximate number of megabytes of memory, or zero if
  11655. something goes wrong when finding out.
  11656. */
  11657. static int getMemorySizeInMegabytes();
  11658. /** Returns the system page-size.
  11659. This is only used by programmers with beards.
  11660. */
  11661. static int getPageSize();
  11662. // not-for-public-use platform-specific method gets called at startup to initialise things.
  11663. static void initialiseStats();
  11664. private:
  11665. struct CPUFlags
  11666. {
  11667. int numCpus;
  11668. bool hasMMX : 1;
  11669. bool hasSSE : 1;
  11670. bool hasSSE2 : 1;
  11671. bool has3DNow : 1;
  11672. };
  11673. static CPUFlags cpuFlags;
  11674. SystemStats();
  11675. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  11676. };
  11677. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  11678. /*** End of inlined file: juce_SystemStats.h ***/
  11679. #endif
  11680. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  11681. #endif
  11682. #ifndef __JUCE_TIME_JUCEHEADER__
  11683. #endif
  11684. #ifndef __JUCE_UUID_JUCEHEADER__
  11685. /*** Start of inlined file: juce_Uuid.h ***/
  11686. #ifndef __JUCE_UUID_JUCEHEADER__
  11687. #define __JUCE_UUID_JUCEHEADER__
  11688. /**
  11689. A universally unique 128-bit identifier.
  11690. This class generates very random unique numbers based on the system time
  11691. and MAC addresses if any are available. It's extremely unlikely that two identical
  11692. UUIDs would ever be created by chance.
  11693. The class includes methods for saving the ID as a string or as raw binary data.
  11694. */
  11695. class JUCE_API Uuid
  11696. {
  11697. public:
  11698. /** Creates a new unique ID. */
  11699. Uuid();
  11700. /** Destructor. */
  11701. ~Uuid() throw();
  11702. /** Creates a copy of another UUID. */
  11703. Uuid (const Uuid& other);
  11704. /** Copies another UUID. */
  11705. Uuid& operator= (const Uuid& other);
  11706. /** Returns true if the ID is zero. */
  11707. bool isNull() const throw();
  11708. /** Compares two UUIDs. */
  11709. bool operator== (const Uuid& other) const;
  11710. /** Compares two UUIDs. */
  11711. bool operator!= (const Uuid& other) const;
  11712. /** Returns a stringified version of this UUID.
  11713. A Uuid object can later be reconstructed from this string using operator= or
  11714. the constructor that takes a string parameter.
  11715. @returns a 32 character hex string.
  11716. */
  11717. const String toString() const;
  11718. /** Creates an ID from an encoded string version.
  11719. @see toString
  11720. */
  11721. Uuid (const String& uuidString);
  11722. /** Copies from a stringified UUID.
  11723. The string passed in should be one that was created with the toString() method.
  11724. */
  11725. Uuid& operator= (const String& uuidString);
  11726. /** Returns a pointer to the internal binary representation of the ID.
  11727. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  11728. the constructor or operator= method that takes an array of uint8s.
  11729. */
  11730. const uint8* getRawData() const throw() { return value.asBytes; }
  11731. /** Creates a UUID from a 16-byte array.
  11732. @see getRawData
  11733. */
  11734. Uuid (const uint8* rawData);
  11735. /** Sets this UUID from 16-bytes of raw data. */
  11736. Uuid& operator= (const uint8* rawData);
  11737. private:
  11738. #ifndef DOXYGEN
  11739. union
  11740. {
  11741. uint8 asBytes [16];
  11742. int asInt[4];
  11743. int64 asInt64[2];
  11744. } value;
  11745. #endif
  11746. JUCE_LEAK_DETECTOR (Uuid);
  11747. };
  11748. #endif // __JUCE_UUID_JUCEHEADER__
  11749. /*** End of inlined file: juce_Uuid.h ***/
  11750. #endif
  11751. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11752. /*** Start of inlined file: juce_BlowFish.h ***/
  11753. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11754. #define __JUCE_BLOWFISH_JUCEHEADER__
  11755. /**
  11756. BlowFish encryption class.
  11757. */
  11758. class JUCE_API BlowFish
  11759. {
  11760. public:
  11761. /** Creates an object that can encode/decode based on the specified key.
  11762. The key data can be up to 72 bytes long.
  11763. */
  11764. BlowFish (const void* keyData, int keyBytes);
  11765. /** Creates a copy of another blowfish object. */
  11766. BlowFish (const BlowFish& other);
  11767. /** Copies another blowfish object. */
  11768. BlowFish& operator= (const BlowFish& other);
  11769. /** Destructor. */
  11770. ~BlowFish();
  11771. /** Encrypts a pair of 32-bit integers. */
  11772. void encrypt (uint32& data1, uint32& data2) const throw();
  11773. /** Decrypts a pair of 32-bit integers. */
  11774. void decrypt (uint32& data1, uint32& data2) const throw();
  11775. private:
  11776. uint32 p[18];
  11777. HeapBlock <uint32> s[4];
  11778. uint32 F (uint32 x) const throw();
  11779. JUCE_LEAK_DETECTOR (BlowFish);
  11780. };
  11781. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  11782. /*** End of inlined file: juce_BlowFish.h ***/
  11783. #endif
  11784. #ifndef __JUCE_MD5_JUCEHEADER__
  11785. /*** Start of inlined file: juce_MD5.h ***/
  11786. #ifndef __JUCE_MD5_JUCEHEADER__
  11787. #define __JUCE_MD5_JUCEHEADER__
  11788. /**
  11789. MD5 checksum class.
  11790. Create one of these with a block of source data or a string, and it calculates the
  11791. MD5 checksum of that data.
  11792. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  11793. */
  11794. class JUCE_API MD5
  11795. {
  11796. public:
  11797. /** Creates a null MD5 object. */
  11798. MD5();
  11799. /** Creates a copy of another MD5. */
  11800. MD5 (const MD5& other);
  11801. /** Copies another MD5. */
  11802. MD5& operator= (const MD5& other);
  11803. /** Creates a checksum for a block of binary data. */
  11804. explicit MD5 (const MemoryBlock& data);
  11805. /** Creates a checksum for a block of binary data. */
  11806. MD5 (const void* data, size_t numBytes);
  11807. /** Creates a checksum for a string.
  11808. Note that this operates on the string as a block of unicode characters, so the
  11809. result you get will differ from the value you'd get if the string was treated
  11810. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  11811. of this method with a checksum created by a different framework, which may have
  11812. used a different encoding.
  11813. */
  11814. explicit MD5 (const String& text);
  11815. /** Creates a checksum for the input from a stream.
  11816. This will read up to the given number of bytes from the stream, and produce the
  11817. checksum of that. If the number of bytes to read is negative, it'll read
  11818. until the stream is exhausted.
  11819. */
  11820. MD5 (InputStream& input, int64 numBytesToRead = -1);
  11821. /** Creates a checksum for a file. */
  11822. explicit MD5 (const File& file);
  11823. /** Destructor. */
  11824. ~MD5();
  11825. /** Returns the checksum as a 16-byte block of data. */
  11826. const MemoryBlock getRawChecksumData() const;
  11827. /** Returns the checksum as a 32-digit hex string. */
  11828. const String toHexString() const;
  11829. /** Compares this to another MD5. */
  11830. bool operator== (const MD5& other) const;
  11831. /** Compares this to another MD5. */
  11832. bool operator!= (const MD5& other) const;
  11833. private:
  11834. uint8 result [16];
  11835. struct ProcessContext
  11836. {
  11837. uint8 buffer [64];
  11838. uint32 state [4];
  11839. uint32 count [2];
  11840. ProcessContext();
  11841. void processBlock (const void* data, size_t dataSize);
  11842. void transform (const void* buffer);
  11843. void finish (void* result);
  11844. };
  11845. void processStream (InputStream& input, int64 numBytesToRead);
  11846. JUCE_LEAK_DETECTOR (MD5);
  11847. };
  11848. #endif // __JUCE_MD5_JUCEHEADER__
  11849. /*** End of inlined file: juce_MD5.h ***/
  11850. #endif
  11851. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11852. /*** Start of inlined file: juce_Primes.h ***/
  11853. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11854. #define __JUCE_PRIMES_JUCEHEADER__
  11855. /*** Start of inlined file: juce_BigInteger.h ***/
  11856. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  11857. #define __JUCE_BIGINTEGER_JUCEHEADER__
  11858. class MemoryBlock;
  11859. /**
  11860. An arbitrarily large integer class.
  11861. A BigInteger can be used in a similar way to a normal integer, but has no size
  11862. limit (except for memory and performance constraints).
  11863. Negative values are possible, but the value isn't stored as 2s-complement, so
  11864. be careful if you use negative values and look at the values of individual bits.
  11865. */
  11866. class JUCE_API BigInteger
  11867. {
  11868. public:
  11869. /** Creates an empty BigInteger */
  11870. BigInteger();
  11871. /** Creates a BigInteger containing an integer value in its low bits.
  11872. The low 32 bits of the number are initialised with this value.
  11873. */
  11874. BigInteger (uint32 value);
  11875. /** Creates a BigInteger containing an integer value in its low bits.
  11876. The low 32 bits of the number are initialised with the absolute value
  11877. passed in, and its sign is set to reflect the sign of the number.
  11878. */
  11879. BigInteger (int32 value);
  11880. /** Creates a BigInteger containing an integer value in its low bits.
  11881. The low 64 bits of the number are initialised with the absolute value
  11882. passed in, and its sign is set to reflect the sign of the number.
  11883. */
  11884. BigInteger (int64 value);
  11885. /** Creates a copy of another BigInteger. */
  11886. BigInteger (const BigInteger& other);
  11887. /** Destructor. */
  11888. ~BigInteger();
  11889. /** Copies another BigInteger onto this one. */
  11890. BigInteger& operator= (const BigInteger& other);
  11891. /** Swaps the internal contents of this with another object. */
  11892. void swapWith (BigInteger& other) throw();
  11893. /** Returns the value of a specified bit in the number.
  11894. If the index is out-of-range, the result will be false.
  11895. */
  11896. bool operator[] (int bit) const throw();
  11897. /** Returns true if no bits are set. */
  11898. bool isZero() const throw();
  11899. /** Returns true if the value is 1. */
  11900. bool isOne() const throw();
  11901. /** Attempts to get the lowest bits of the value as an integer.
  11902. If the value is bigger than the integer limits, this will return only the lower bits.
  11903. */
  11904. int toInteger() const throw();
  11905. /** Resets the value to 0. */
  11906. void clear();
  11907. /** Clears a particular bit in the number. */
  11908. void clearBit (int bitNumber) throw();
  11909. /** Sets a specified bit to 1. */
  11910. void setBit (int bitNumber);
  11911. /** Sets or clears a specified bit. */
  11912. void setBit (int bitNumber, bool shouldBeSet);
  11913. /** Sets a range of bits to be either on or off.
  11914. @param startBit the first bit to change
  11915. @param numBits the number of bits to change
  11916. @param shouldBeSet whether to turn these bits on or off
  11917. */
  11918. void setRange (int startBit, int numBits, bool shouldBeSet);
  11919. /** Inserts a bit an a given position, shifting up any bits above it. */
  11920. void insertBit (int bitNumber, bool shouldBeSet);
  11921. /** Returns a range of bits as a new BigInteger.
  11922. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  11923. @see getBitRangeAsInt
  11924. */
  11925. const BigInteger getBitRange (int startBit, int numBits) const;
  11926. /** Returns a range of bits as an integer value.
  11927. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  11928. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  11929. getBitRange().
  11930. */
  11931. int getBitRangeAsInt (int startBit, int numBits) const throw();
  11932. /** Sets a range of bits to an integer value.
  11933. Copies the given integer onto a range of bits, starting at startBit,
  11934. and using up to numBits of the available bits.
  11935. */
  11936. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  11937. /** Shifts a section of bits left or right.
  11938. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  11939. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  11940. */
  11941. void shiftBits (int howManyBitsLeft, int startBit);
  11942. /** Returns the total number of set bits in the value. */
  11943. int countNumberOfSetBits() const throw();
  11944. /** Looks for the index of the next set bit after a given starting point.
  11945. This searches from startIndex (inclusive) upwards for the first set bit,
  11946. and returns its index. If no set bits are found, it returns -1.
  11947. */
  11948. int findNextSetBit (int startIndex = 0) const throw();
  11949. /** Looks for the index of the next clear bit after a given starting point.
  11950. This searches from startIndex (inclusive) upwards for the first clear bit,
  11951. and returns its index.
  11952. */
  11953. int findNextClearBit (int startIndex = 0) const throw();
  11954. /** Returns the index of the highest set bit in the number.
  11955. If the value is zero, this will return -1.
  11956. */
  11957. int getHighestBit() const throw();
  11958. // All the standard arithmetic ops...
  11959. BigInteger& operator+= (const BigInteger& other);
  11960. BigInteger& operator-= (const BigInteger& other);
  11961. BigInteger& operator*= (const BigInteger& other);
  11962. BigInteger& operator/= (const BigInteger& other);
  11963. BigInteger& operator|= (const BigInteger& other);
  11964. BigInteger& operator&= (const BigInteger& other);
  11965. BigInteger& operator^= (const BigInteger& other);
  11966. BigInteger& operator%= (const BigInteger& other);
  11967. BigInteger& operator<<= (int numBitsToShift);
  11968. BigInteger& operator>>= (int numBitsToShift);
  11969. BigInteger& operator++();
  11970. BigInteger& operator--();
  11971. const BigInteger operator++ (int);
  11972. const BigInteger operator-- (int);
  11973. const BigInteger operator-() const;
  11974. const BigInteger operator+ (const BigInteger& other) const;
  11975. const BigInteger operator- (const BigInteger& other) const;
  11976. const BigInteger operator* (const BigInteger& other) const;
  11977. const BigInteger operator/ (const BigInteger& other) const;
  11978. const BigInteger operator| (const BigInteger& other) const;
  11979. const BigInteger operator& (const BigInteger& other) const;
  11980. const BigInteger operator^ (const BigInteger& other) const;
  11981. const BigInteger operator% (const BigInteger& other) const;
  11982. const BigInteger operator<< (int numBitsToShift) const;
  11983. const BigInteger operator>> (int numBitsToShift) const;
  11984. bool operator== (const BigInteger& other) const throw();
  11985. bool operator!= (const BigInteger& other) const throw();
  11986. bool operator< (const BigInteger& other) const throw();
  11987. bool operator<= (const BigInteger& other) const throw();
  11988. bool operator> (const BigInteger& other) const throw();
  11989. bool operator>= (const BigInteger& other) const throw();
  11990. /** Does a signed comparison of two BigIntegers.
  11991. Return values are:
  11992. - 0 if the numbers are the same
  11993. - < 0 if this number is smaller than the other
  11994. - > 0 if this number is bigger than the other
  11995. */
  11996. int compare (const BigInteger& other) const throw();
  11997. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  11998. Return values are:
  11999. - 0 if the numbers are the same
  12000. - < 0 if this number is smaller than the other
  12001. - > 0 if this number is bigger than the other
  12002. */
  12003. int compareAbsolute (const BigInteger& other) const throw();
  12004. /** Divides this value by another one and returns the remainder.
  12005. This number is divided by other, leaving the quotient in this number,
  12006. with the remainder being copied to the other BigInteger passed in.
  12007. */
  12008. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  12009. /** Returns the largest value that will divide both this value and the one passed-in.
  12010. */
  12011. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  12012. /** Performs a combined exponent and modulo operation.
  12013. This BigInteger's value becomes (this ^ exponent) % modulus.
  12014. */
  12015. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  12016. /** Performs an inverse modulo on the value.
  12017. i.e. the result is (this ^ -1) mod (modulus).
  12018. */
  12019. void inverseModulo (const BigInteger& modulus);
  12020. /** Returns true if the value is less than zero.
  12021. @see setNegative, negate
  12022. */
  12023. bool isNegative() const throw();
  12024. /** Changes the sign of the number to be positive or negative.
  12025. @see isNegative, negate
  12026. */
  12027. void setNegative (bool shouldBeNegative) throw();
  12028. /** Inverts the sign of the number.
  12029. @see isNegative, setNegative
  12030. */
  12031. void negate() throw();
  12032. /** Converts the number to a string.
  12033. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  12034. If minimumNumCharacters is greater than 0, the returned string will be
  12035. padded with leading zeros to reach at least that length.
  12036. */
  12037. const String toString (int base, int minimumNumCharacters = 1) const;
  12038. /** Reads the numeric value from a string.
  12039. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  12040. Any invalid characters will be ignored.
  12041. */
  12042. void parseString (const String& text, int base);
  12043. /** Turns the number into a block of binary data.
  12044. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  12045. of the number, and so on.
  12046. @see loadFromMemoryBlock
  12047. */
  12048. const MemoryBlock toMemoryBlock() const;
  12049. /** Converts a block of raw data into a number.
  12050. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  12051. of the number, and so on.
  12052. @see toMemoryBlock
  12053. */
  12054. void loadFromMemoryBlock (const MemoryBlock& data);
  12055. private:
  12056. HeapBlock <uint32> values;
  12057. int numValues, highestBit;
  12058. bool negative;
  12059. void ensureSize (int numVals);
  12060. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  12061. static inline int bitToIndex (const int bit) throw() { return bit >> 5; }
  12062. static inline uint32 bitToMask (const int bit) throw() { return 1 << (bit & 31); }
  12063. JUCE_LEAK_DETECTOR (BigInteger);
  12064. };
  12065. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  12066. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  12067. #ifndef DOXYGEN
  12068. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  12069. typedef BigInteger BitArray;
  12070. #endif
  12071. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  12072. /*** End of inlined file: juce_BigInteger.h ***/
  12073. /**
  12074. Prime number creation class.
  12075. This class contains static methods for generating and testing prime numbers.
  12076. @see BigInteger
  12077. */
  12078. class JUCE_API Primes
  12079. {
  12080. public:
  12081. /** Creates a random prime number with a given bit-length.
  12082. The certainty parameter specifies how many iterations to use when testing
  12083. for primality. A safe value might be anything over about 20-30.
  12084. The randomSeeds parameter lets you optionally pass it a set of values with
  12085. which to seed the random number generation, improving the security of the
  12086. keys generated.
  12087. */
  12088. static const BigInteger createProbablePrime (int bitLength,
  12089. int certainty,
  12090. const int* randomSeeds = 0,
  12091. int numRandomSeeds = 0);
  12092. /** Tests a number to see if it's prime.
  12093. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  12094. whether the number is prime.
  12095. The certainty parameter specifies how many iterations to use when testing - a
  12096. safe value might be anything over about 20-30.
  12097. */
  12098. static bool isProbablyPrime (const BigInteger& number, int certainty);
  12099. private:
  12100. Primes();
  12101. JUCE_DECLARE_NON_COPYABLE (Primes);
  12102. };
  12103. #endif // __JUCE_PRIMES_JUCEHEADER__
  12104. /*** End of inlined file: juce_Primes.h ***/
  12105. #endif
  12106. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  12107. /*** Start of inlined file: juce_RSAKey.h ***/
  12108. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  12109. #define __JUCE_RSAKEY_JUCEHEADER__
  12110. /**
  12111. RSA public/private key-pair encryption class.
  12112. An object of this type makes up one half of a public/private RSA key pair. Use the
  12113. createKeyPair() method to create a matching pair for encoding/decoding.
  12114. */
  12115. class JUCE_API RSAKey
  12116. {
  12117. public:
  12118. /** Creates a null key object.
  12119. Initialise a pair of objects for use with the createKeyPair() method.
  12120. */
  12121. RSAKey();
  12122. /** Loads a key from an encoded string representation.
  12123. This reloads a key from a string created by the toString() method.
  12124. */
  12125. explicit RSAKey (const String& stringRepresentation);
  12126. /** Destructor. */
  12127. ~RSAKey();
  12128. bool operator== (const RSAKey& other) const throw();
  12129. bool operator!= (const RSAKey& other) const throw();
  12130. /** Turns the key into a string representation.
  12131. This can be reloaded using the constructor that takes a string.
  12132. */
  12133. const String toString() const;
  12134. /** Encodes or decodes a value.
  12135. Call this on the public key object to encode some data, then use the matching
  12136. private key object to decode it.
  12137. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  12138. initialised correctly.
  12139. NOTE: This method dumbly applies this key to this data. If you encode some data
  12140. and then try to decode it with a key that doesn't match, this method will still
  12141. happily do its job and return true, but the result won't be what you were expecting.
  12142. It's your responsibility to check that the result is what you wanted.
  12143. */
  12144. bool applyToValue (BigInteger& value) const;
  12145. /** Creates a public/private key-pair.
  12146. Each key will perform one-way encryption that can only be reversed by
  12147. using the other key.
  12148. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  12149. sizes are more secure, but this method will take longer to execute.
  12150. The randomSeeds parameter lets you optionally pass it a set of values with
  12151. which to seed the random number generation, improving the security of the
  12152. keys generated. If you supply these, make sure you provide more than 2 values,
  12153. and the more your provide, the better the security.
  12154. */
  12155. static void createKeyPair (RSAKey& publicKey,
  12156. RSAKey& privateKey,
  12157. int numBits,
  12158. const int* randomSeeds = 0,
  12159. int numRandomSeeds = 0);
  12160. protected:
  12161. BigInteger part1, part2;
  12162. private:
  12163. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  12164. JUCE_LEAK_DETECTOR (RSAKey);
  12165. };
  12166. #endif // __JUCE_RSAKEY_JUCEHEADER__
  12167. /*** End of inlined file: juce_RSAKey.h ***/
  12168. #endif
  12169. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  12170. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  12171. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  12172. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  12173. /**
  12174. Searches through a the files in a directory, returning each file that is found.
  12175. A DirectoryIterator will search through a directory and its subdirectories using
  12176. a wildcard filepattern match.
  12177. If you may be finding a large number of files, this is better than
  12178. using File::findChildFiles() because it doesn't block while it finds them
  12179. all, and this is more memory-efficient.
  12180. It can also guess how far it's got using a wildly inaccurate algorithm.
  12181. */
  12182. class JUCE_API DirectoryIterator
  12183. {
  12184. public:
  12185. /** Creates a DirectoryIterator for a given directory.
  12186. After creating one of these, call its next() method to get the
  12187. first file - e.g. @code
  12188. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  12189. while (iter.next())
  12190. {
  12191. File theFileItFound (iter.getFile());
  12192. ... etc
  12193. }
  12194. @endcode
  12195. @param directory the directory to search in
  12196. @param isRecursive whether all the subdirectories should also be searched
  12197. @param wildCard the file pattern to match
  12198. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  12199. whether to look for files, directories, or both.
  12200. */
  12201. DirectoryIterator (const File& directory,
  12202. bool isRecursive,
  12203. const String& wildCard = "*",
  12204. int whatToLookFor = File::findFiles);
  12205. /** Destructor. */
  12206. ~DirectoryIterator();
  12207. /** Moves the iterator along to the next file.
  12208. @returns true if a file was found (you can then use getFile() to see what it was) - or
  12209. false if there are no more matching files.
  12210. */
  12211. bool next();
  12212. /** Moves the iterator along to the next file, and returns various properties of that file.
  12213. If you need to find out details about the file, it's more efficient to call this method than
  12214. to call the normal next() method and then find out the details afterwards.
  12215. All the parameters are optional, so pass null pointers for any items that you're not
  12216. interested in.
  12217. @returns true if a file was found (you can then use getFile() to see what it was) - or
  12218. false if there are no more matching files. If it returns false, then none of the
  12219. parameters will be filled-in.
  12220. */
  12221. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  12222. Time* modTime, Time* creationTime, bool* isReadOnly);
  12223. /** Returns the file that the iterator is currently pointing at.
  12224. The result of this call is only valid after a call to next() has returned true.
  12225. */
  12226. const File getFile() const;
  12227. /** Returns a guess of how far through the search the iterator has got.
  12228. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  12229. very accurate.
  12230. */
  12231. float getEstimatedProgress() const;
  12232. private:
  12233. class NativeIterator
  12234. {
  12235. public:
  12236. NativeIterator (const File& directory, const String& wildCard);
  12237. ~NativeIterator();
  12238. bool next (String& filenameFound,
  12239. bool* isDirectory, bool* isHidden, int64* fileSize,
  12240. Time* modTime, Time* creationTime, bool* isReadOnly);
  12241. class Pimpl;
  12242. private:
  12243. friend class DirectoryIterator;
  12244. friend class ScopedPointer<Pimpl>;
  12245. ScopedPointer<Pimpl> pimpl;
  12246. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  12247. };
  12248. friend class ScopedPointer<NativeIterator::Pimpl>;
  12249. NativeIterator fileFinder;
  12250. String wildCard, path;
  12251. int index;
  12252. mutable int totalNumFiles;
  12253. const int whatToLookFor;
  12254. const bool isRecursive;
  12255. bool hasBeenAdvanced;
  12256. ScopedPointer <DirectoryIterator> subIterator;
  12257. File currentFile;
  12258. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  12259. };
  12260. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  12261. /*** End of inlined file: juce_DirectoryIterator.h ***/
  12262. #endif
  12263. #ifndef __JUCE_FILE_JUCEHEADER__
  12264. #endif
  12265. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  12266. /*** Start of inlined file: juce_FileInputStream.h ***/
  12267. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  12268. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  12269. /**
  12270. An input stream that reads from a local file.
  12271. @see InputStream, FileOutputStream, File::createInputStream
  12272. */
  12273. class JUCE_API FileInputStream : public InputStream
  12274. {
  12275. public:
  12276. /** Creates a FileInputStream.
  12277. @param fileToRead the file to read from - if the file can't be accessed for some
  12278. reason, then the stream will just contain no data
  12279. */
  12280. explicit FileInputStream (const File& fileToRead);
  12281. /** Destructor. */
  12282. ~FileInputStream();
  12283. const File& getFile() const throw() { return file; }
  12284. int64 getTotalLength();
  12285. int read (void* destBuffer, int maxBytesToRead);
  12286. bool isExhausted();
  12287. int64 getPosition();
  12288. bool setPosition (int64 pos);
  12289. private:
  12290. File file;
  12291. void* fileHandle;
  12292. int64 currentPosition, totalSize;
  12293. bool needToSeek;
  12294. void openHandle();
  12295. void closeHandle();
  12296. size_t readInternal (void* buffer, size_t numBytes);
  12297. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  12298. };
  12299. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  12300. /*** End of inlined file: juce_FileInputStream.h ***/
  12301. #endif
  12302. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  12303. /*** Start of inlined file: juce_FileOutputStream.h ***/
  12304. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  12305. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  12306. /**
  12307. An output stream that writes into a local file.
  12308. @see OutputStream, FileInputStream, File::createOutputStream
  12309. */
  12310. class JUCE_API FileOutputStream : public OutputStream
  12311. {
  12312. public:
  12313. /** Creates a FileOutputStream.
  12314. If the file doesn't exist, it will first be created. If the file can't be
  12315. created or opened, the failedToOpen() method will return
  12316. true.
  12317. If the file already exists when opened, the stream's write-postion will
  12318. be set to the end of the file. To overwrite an existing file,
  12319. use File::deleteFile() before opening the stream, or use setPosition(0)
  12320. after it's opened (although this won't truncate the file).
  12321. It's better to use File::createOutputStream() to create one of these, rather
  12322. than using the class directly.
  12323. @see TemporaryFile
  12324. */
  12325. FileOutputStream (const File& fileToWriteTo,
  12326. int bufferSizeToUse = 16384);
  12327. /** Destructor. */
  12328. ~FileOutputStream();
  12329. /** Returns the file that this stream is writing to.
  12330. */
  12331. const File& getFile() const { return file; }
  12332. /** Returns true if the stream couldn't be opened for some reason.
  12333. */
  12334. bool failedToOpen() const { return fileHandle == 0; }
  12335. void flush();
  12336. int64 getPosition();
  12337. bool setPosition (int64 pos);
  12338. bool write (const void* data, int numBytes);
  12339. private:
  12340. File file;
  12341. void* fileHandle;
  12342. int64 currentPosition;
  12343. int bufferSize, bytesInBuffer;
  12344. HeapBlock <char> buffer;
  12345. void openHandle();
  12346. void closeHandle();
  12347. void flushInternal();
  12348. int64 setPositionInternal (int64 newPosition);
  12349. int writeInternal (const void* data, int numBytes);
  12350. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  12351. };
  12352. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  12353. /*** End of inlined file: juce_FileOutputStream.h ***/
  12354. #endif
  12355. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  12356. /*** Start of inlined file: juce_FileSearchPath.h ***/
  12357. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  12358. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  12359. /**
  12360. Encapsulates a set of folders that make up a search path.
  12361. @see File
  12362. */
  12363. class JUCE_API FileSearchPath
  12364. {
  12365. public:
  12366. /** Creates an empty search path. */
  12367. FileSearchPath();
  12368. /** Creates a search path from a string of pathnames.
  12369. The path can be semicolon- or comma-separated, e.g.
  12370. "/foo/bar;/foo/moose;/fish/moose"
  12371. The separate folders are tokenised and added to the search path.
  12372. */
  12373. FileSearchPath (const String& path);
  12374. /** Creates a copy of another search path. */
  12375. FileSearchPath (const FileSearchPath& other);
  12376. /** Destructor. */
  12377. ~FileSearchPath();
  12378. /** Uses a string containing a list of pathnames to re-initialise this list.
  12379. This search path is cleared and the semicolon- or comma-separated folders
  12380. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  12381. */
  12382. FileSearchPath& operator= (const String& path);
  12383. /** Returns the number of folders in this search path.
  12384. @see operator[]
  12385. */
  12386. int getNumPaths() const;
  12387. /** Returns one of the folders in this search path.
  12388. The file returned isn't guaranteed to actually be a valid directory.
  12389. @see getNumPaths
  12390. */
  12391. const File operator[] (int index) const;
  12392. /** Returns the search path as a semicolon-separated list of directories. */
  12393. const String toString() const;
  12394. /** Adds a new directory to the search path.
  12395. The new directory is added to the end of the list if the insertIndex parameter is
  12396. less than zero, otherwise it is inserted at the given index.
  12397. */
  12398. void add (const File& directoryToAdd,
  12399. int insertIndex = -1);
  12400. /** Adds a new directory to the search path if it's not already in there. */
  12401. void addIfNotAlreadyThere (const File& directoryToAdd);
  12402. /** Removes a directory from the search path. */
  12403. void remove (int indexToRemove);
  12404. /** Merges another search path into this one.
  12405. This will remove any duplicate directories.
  12406. */
  12407. void addPath (const FileSearchPath& other);
  12408. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  12409. If the search is intended to be recursive, there's no point having nested folders in the search
  12410. path, because they'll just get searched twice and you'll get duplicate results.
  12411. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  12412. */
  12413. void removeRedundantPaths();
  12414. /** Removes any directories that don't actually exist. */
  12415. void removeNonExistentPaths();
  12416. /** Searches the path for a wildcard.
  12417. This will search all the directories in the search path in order, adding any
  12418. matching files to the results array.
  12419. @param results an array to append the results to
  12420. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  12421. return files, directories, or both.
  12422. @param searchRecursively whether to recursively search the subdirectories too
  12423. @param wildCardPattern a pattern to match against the filenames
  12424. @returns the number of files added to the array
  12425. @see File::findChildFiles
  12426. */
  12427. int findChildFiles (Array<File>& results,
  12428. int whatToLookFor,
  12429. bool searchRecursively,
  12430. const String& wildCardPattern = "*") const;
  12431. /** Finds out whether a file is inside one of the path's directories.
  12432. This will return true if the specified file is a child of one of the
  12433. directories specified by this path. Note that this doesn't actually do any
  12434. searching or check that the files exist - it just looks at the pathnames
  12435. to work out whether the file would be inside a directory.
  12436. @param fileToCheck the file to look for
  12437. @param checkRecursively if true, then this will return true if the file is inside a
  12438. subfolder of one of the path's directories (at any depth). If false
  12439. it will only return true if the file is actually a direct child
  12440. of one of the directories.
  12441. @see File::isAChildOf
  12442. */
  12443. bool isFileInPath (const File& fileToCheck,
  12444. bool checkRecursively) const;
  12445. private:
  12446. StringArray directories;
  12447. void init (const String& path);
  12448. JUCE_LEAK_DETECTOR (FileSearchPath);
  12449. };
  12450. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  12451. /*** End of inlined file: juce_FileSearchPath.h ***/
  12452. #endif
  12453. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  12454. /*** Start of inlined file: juce_NamedPipe.h ***/
  12455. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  12456. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  12457. /**
  12458. A cross-process pipe that can have data written to and read from it.
  12459. Two or more processes can use these for inter-process communication.
  12460. @see InterprocessConnection
  12461. */
  12462. class JUCE_API NamedPipe
  12463. {
  12464. public:
  12465. /** Creates a NamedPipe. */
  12466. NamedPipe();
  12467. /** Destructor. */
  12468. ~NamedPipe();
  12469. /** Tries to open a pipe that already exists.
  12470. Returns true if it succeeds.
  12471. */
  12472. bool openExisting (const String& pipeName);
  12473. /** Tries to create a new pipe.
  12474. Returns true if it succeeds.
  12475. */
  12476. bool createNewPipe (const String& pipeName);
  12477. /** Closes the pipe, if it's open. */
  12478. void close();
  12479. /** True if the pipe is currently open. */
  12480. bool isOpen() const;
  12481. /** Returns the last name that was used to try to open this pipe. */
  12482. const String getName() const;
  12483. /** Reads data from the pipe.
  12484. This will block until another thread has written enough data into the pipe to fill
  12485. the number of bytes specified, or until another thread calls the cancelPendingReads()
  12486. method.
  12487. If the operation fails, it returns -1, otherwise, it will return the number of
  12488. bytes read.
  12489. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  12490. this is a maximum timeout for reading from the pipe.
  12491. */
  12492. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  12493. /** Writes some data to the pipe.
  12494. If the operation fails, it returns -1, otherwise, it will return the number of
  12495. bytes written.
  12496. */
  12497. int write (const void* sourceBuffer, int numBytesToWrite,
  12498. int timeOutMilliseconds = 2000);
  12499. /** If any threads are currently blocked on a read operation, this tells them to abort.
  12500. */
  12501. void cancelPendingReads();
  12502. private:
  12503. void* internal;
  12504. String currentPipeName;
  12505. CriticalSection lock;
  12506. bool openInternal (const String& pipeName, const bool createPipe);
  12507. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  12508. };
  12509. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  12510. /*** End of inlined file: juce_NamedPipe.h ***/
  12511. #endif
  12512. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  12513. /*** Start of inlined file: juce_TemporaryFile.h ***/
  12514. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  12515. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  12516. /**
  12517. Manages a temporary file, which will be deleted when this object is deleted.
  12518. This object is intended to be used as a stack based object, using its scope
  12519. to make sure the temporary file isn't left lying around.
  12520. For example:
  12521. @code
  12522. {
  12523. File myTargetFile ("~/myfile.txt");
  12524. // this will choose a file called something like "~/myfile_temp239348.txt"
  12525. // which definitely doesn't exist at the time the constructor is called.
  12526. TemporaryFile temp (myTargetFile);
  12527. // create a stream to the temporary file, and write some data to it...
  12528. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  12529. if (out != 0)
  12530. {
  12531. out->write ( ...etc )
  12532. out->flush();
  12533. out = 0; // (deletes the stream)
  12534. // ..now we've finished writing, this will rename the temp file to
  12535. // make it replace the target file we specified above.
  12536. bool succeeded = temp.overwriteTargetFileWithTemporary();
  12537. }
  12538. // ..and even if something went wrong and our overwrite failed,
  12539. // as the TemporaryFile object goes out of scope here, it'll make sure
  12540. // that the temp file gets deleted.
  12541. }
  12542. @endcode
  12543. @see File, FileOutputStream
  12544. */
  12545. class JUCE_API TemporaryFile
  12546. {
  12547. public:
  12548. enum OptionFlags
  12549. {
  12550. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  12551. i.e. its name should start with a dot. */
  12552. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  12553. the file is unique, they should go in brackets rather
  12554. than just being appended (see File::getNonexistentSibling() )*/
  12555. };
  12556. /** Creates a randomly-named temporary file in the default temp directory.
  12557. @param suffix a file suffix to use for the file
  12558. @param optionFlags a combination of the values listed in the OptionFlags enum
  12559. The file will not be created until you write to it. And remember that when
  12560. this object is deleted, the file will also be deleted!
  12561. */
  12562. TemporaryFile (const String& suffix = String::empty,
  12563. int optionFlags = 0);
  12564. /** Creates a temporary file in the same directory as a specified file.
  12565. This is useful if you have a file that you want to overwrite, but don't
  12566. want to harm the original file if the write operation fails. You can
  12567. use this to create a temporary file next to the target file, then
  12568. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  12569. to replace the target file with the one you've just written.
  12570. This class won't create any files until you actually write to them. And remember
  12571. that when this object is deleted, the temporary file will also be deleted!
  12572. @param targetFile the file that you intend to overwrite - the temporary
  12573. file will be created in the same directory as this
  12574. @param optionFlags a combination of the values listed in the OptionFlags enum
  12575. */
  12576. TemporaryFile (const File& targetFile,
  12577. int optionFlags = 0);
  12578. /** Destructor.
  12579. When this object is deleted it will make sure that its temporary file is
  12580. also deleted! If the operation fails, it'll throw an assertion in debug
  12581. mode.
  12582. */
  12583. ~TemporaryFile();
  12584. /** Returns the temporary file. */
  12585. const File getFile() const { return temporaryFile; }
  12586. /** Returns the target file that was specified in the constructor. */
  12587. const File getTargetFile() const { return targetFile; }
  12588. /** Tries to move the temporary file to overwrite the target file that was
  12589. specified in the constructor.
  12590. If you used the constructor that specified a target file, this will attempt
  12591. to replace that file with the temporary one.
  12592. Before calling this, make sure:
  12593. - that you've actually written to the temporary file
  12594. - that you've closed any open streams that you were using to write to it
  12595. - and that you don't have any streams open to the target file, which would
  12596. prevent it being overwritten
  12597. If the file move succeeds, this returns false, and the temporary file will
  12598. have disappeared. If it fails, the temporary file will probably still exist,
  12599. but will be deleted when this object is destroyed.
  12600. */
  12601. bool overwriteTargetFileWithTemporary() const;
  12602. /** Attempts to delete the temporary file, if it exists.
  12603. @returns true if the file is successfully deleted (or if it didn't exist).
  12604. */
  12605. bool deleteTemporaryFile() const;
  12606. private:
  12607. File temporaryFile, targetFile;
  12608. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  12609. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  12610. };
  12611. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  12612. /*** End of inlined file: juce_TemporaryFile.h ***/
  12613. #endif
  12614. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  12615. /*** Start of inlined file: juce_ZipFile.h ***/
  12616. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  12617. #define __JUCE_ZIPFILE_JUCEHEADER__
  12618. /*** Start of inlined file: juce_InputSource.h ***/
  12619. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12620. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  12621. /**
  12622. A lightweight object that can create a stream to read some kind of resource.
  12623. This may be used to refer to a file, or some other kind of source, allowing a
  12624. caller to create an input stream that can read from it when required.
  12625. @see FileInputSource
  12626. */
  12627. class JUCE_API InputSource
  12628. {
  12629. public:
  12630. InputSource() throw() {}
  12631. /** Destructor. */
  12632. virtual ~InputSource() {}
  12633. /** Returns a new InputStream to read this item.
  12634. @returns an inputstream that the caller will delete, or 0 if
  12635. the filename isn't found.
  12636. */
  12637. virtual InputStream* createInputStream() = 0;
  12638. /** Returns a new InputStream to read an item, relative.
  12639. @param relatedItemPath the relative pathname of the resource that is required
  12640. @returns an inputstream that the caller will delete, or 0 if
  12641. the item isn't found.
  12642. */
  12643. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  12644. /** Returns a hash code that uniquely represents this item.
  12645. */
  12646. virtual int64 hashCode() const = 0;
  12647. private:
  12648. JUCE_LEAK_DETECTOR (InputSource);
  12649. };
  12650. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  12651. /*** End of inlined file: juce_InputSource.h ***/
  12652. /**
  12653. Decodes a ZIP file from a stream.
  12654. This can enumerate the items in a ZIP file and can create suitable stream objects
  12655. to read each one.
  12656. */
  12657. class JUCE_API ZipFile
  12658. {
  12659. public:
  12660. /** Creates a ZipFile for a given stream.
  12661. @param inputStream the stream to read from
  12662. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  12663. will be deleted when this ZipFile object is deleted
  12664. */
  12665. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  12666. /** Creates a ZipFile based for a file. */
  12667. ZipFile (const File& file);
  12668. /** Creates a ZipFile for an input source.
  12669. The inputSource object will be owned by the zip file, which will delete
  12670. it later when not needed.
  12671. */
  12672. ZipFile (InputSource* inputSource);
  12673. /** Destructor. */
  12674. ~ZipFile();
  12675. /**
  12676. Contains information about one of the entries in a ZipFile.
  12677. @see ZipFile::getEntry
  12678. */
  12679. struct ZipEntry
  12680. {
  12681. /** The name of the file, which may also include a partial pathname. */
  12682. String filename;
  12683. /** The file's original size. */
  12684. unsigned int uncompressedSize;
  12685. /** The last time the file was modified. */
  12686. Time fileTime;
  12687. };
  12688. /** Returns the number of items in the zip file. */
  12689. int getNumEntries() const throw();
  12690. /** Returns a structure that describes one of the entries in the zip file.
  12691. This may return zero if the index is out of range.
  12692. @see ZipFile::ZipEntry
  12693. */
  12694. const ZipEntry* getEntry (int index) const throw();
  12695. /** Returns the index of the first entry with a given filename.
  12696. This uses a case-sensitive comparison to look for a filename in the
  12697. list of entries. It might return -1 if no match is found.
  12698. @see ZipFile::ZipEntry
  12699. */
  12700. int getIndexOfFileName (const String& fileName) const throw();
  12701. /** Returns a structure that describes one of the entries in the zip file.
  12702. This uses a case-sensitive comparison to look for a filename in the
  12703. list of entries. It might return 0 if no match is found.
  12704. @see ZipFile::ZipEntry
  12705. */
  12706. const ZipEntry* getEntry (const String& fileName) const throw();
  12707. /** Sorts the list of entries, based on the filename.
  12708. */
  12709. void sortEntriesByFilename();
  12710. /** Creates a stream that can read from one of the zip file's entries.
  12711. The stream that is returned must be deleted by the caller (and
  12712. zero might be returned if a stream can't be opened for some reason).
  12713. The stream must not be used after the ZipFile object that created
  12714. has been deleted.
  12715. */
  12716. InputStream* createStreamForEntry (int index);
  12717. /** Creates a stream that can read from one of the zip file's entries.
  12718. The stream that is returned must be deleted by the caller (and
  12719. zero might be returned if a stream can't be opened for some reason).
  12720. The stream must not be used after the ZipFile object that created
  12721. has been deleted.
  12722. */
  12723. InputStream* createStreamForEntry (ZipEntry& entry);
  12724. /** Uncompresses all of the files in the zip file.
  12725. This will expand all the entries into a target directory. The relative
  12726. paths of the entries are used.
  12727. @param targetDirectory the root folder to uncompress to
  12728. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  12729. @returns true if all the files are successfully unzipped
  12730. */
  12731. bool uncompressTo (const File& targetDirectory,
  12732. bool shouldOverwriteFiles = true);
  12733. /** Uncompresses one of the entries from the zip file.
  12734. This will expand the entry and write it in a target directory. The entry's path is used to
  12735. determine which subfolder of the target should contain the new file.
  12736. @param index the index of the entry to uncompress
  12737. @param targetDirectory the root folder to uncompress into
  12738. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  12739. @returns true if the files is successfully unzipped
  12740. */
  12741. bool uncompressEntry (int index,
  12742. const File& targetDirectory,
  12743. bool shouldOverwriteFiles = true);
  12744. private:
  12745. class ZipInputStream;
  12746. class ZipFilenameComparator;
  12747. class ZipEntryInfo;
  12748. friend class ZipInputStream;
  12749. friend class ZipFilenameComparator;
  12750. friend class ZipEntryInfo;
  12751. OwnedArray <ZipEntryInfo> entries;
  12752. CriticalSection lock;
  12753. InputStream* inputStream;
  12754. ScopedPointer <InputStream> streamToDelete;
  12755. ScopedPointer <InputSource> inputSource;
  12756. #if JUCE_DEBUG
  12757. int numOpenStreams;
  12758. #endif
  12759. void init();
  12760. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  12761. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  12762. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  12763. };
  12764. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  12765. /*** End of inlined file: juce_ZipFile.h ***/
  12766. #endif
  12767. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  12768. /*** Start of inlined file: juce_MACAddress.h ***/
  12769. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  12770. #define __JUCE_MACADDRESS_JUCEHEADER__
  12771. /**
  12772. A wrapper for a streaming (TCP) socket.
  12773. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12774. sockets, you could also try the InterprocessConnection class.
  12775. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  12776. */
  12777. class JUCE_API MACAddress
  12778. {
  12779. public:
  12780. /** Populates a list of the MAC addresses of all the available network cards. */
  12781. static void findAllAddresses (Array<MACAddress>& results);
  12782. /** Creates a null address (00-00-00-00-00-00). */
  12783. MACAddress();
  12784. /** Creates a copy of another address. */
  12785. MACAddress (const MACAddress& other);
  12786. /** Creates a copy of another address. */
  12787. MACAddress& operator= (const MACAddress& other);
  12788. /** Creates an address from 6 bytes. */
  12789. explicit MACAddress (const uint8 bytes[6]);
  12790. /** Returns a pointer to the 6 bytes that make up this address. */
  12791. const uint8* getBytes() const throw() { return asBytes; }
  12792. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  12793. const String toString() const;
  12794. /** Returns the address in the lower 6 bytes of an int64.
  12795. This uses a little-endian arrangement, with the first byte of the address being
  12796. stored in the least-significant byte of the result value.
  12797. */
  12798. int64 toInt64() const throw();
  12799. /** Returns true if this address is null (00-00-00-00-00-00). */
  12800. bool isNull() const throw();
  12801. bool operator== (const MACAddress& other) const throw();
  12802. bool operator!= (const MACAddress& other) const throw();
  12803. private:
  12804. #ifndef DOXYGEN
  12805. union
  12806. {
  12807. uint64 asInt64;
  12808. uint8 asBytes[6];
  12809. };
  12810. #endif
  12811. };
  12812. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  12813. /*** End of inlined file: juce_MACAddress.h ***/
  12814. #endif
  12815. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12816. /*** Start of inlined file: juce_Socket.h ***/
  12817. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12818. #define __JUCE_SOCKET_JUCEHEADER__
  12819. /**
  12820. A wrapper for a streaming (TCP) socket.
  12821. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12822. sockets, you could also try the InterprocessConnection class.
  12823. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  12824. */
  12825. class JUCE_API StreamingSocket
  12826. {
  12827. public:
  12828. /** Creates an uninitialised socket.
  12829. To connect it, use the connect() method, after which you can read() or write()
  12830. to it.
  12831. To wait for other sockets to connect to this one, the createListener() method
  12832. enters "listener" mode, and can be used to spawn new sockets for each connection
  12833. that comes along.
  12834. */
  12835. StreamingSocket();
  12836. /** Destructor. */
  12837. ~StreamingSocket();
  12838. /** Binds the socket to the specified local port.
  12839. @returns true on success; false may indicate that another socket is already bound
  12840. on the same port
  12841. */
  12842. bool bindToPort (int localPortNumber);
  12843. /** Tries to connect the socket to hostname:port.
  12844. If timeOutMillisecs is 0, then this method will block until the operating system
  12845. rejects the connection (which could take a long time).
  12846. @returns true if it succeeds.
  12847. @see isConnected
  12848. */
  12849. bool connect (const String& remoteHostname,
  12850. int remotePortNumber,
  12851. int timeOutMillisecs = 3000);
  12852. /** True if the socket is currently connected. */
  12853. bool isConnected() const throw() { return connected; }
  12854. /** Closes the connection. */
  12855. void close();
  12856. /** Returns the name of the currently connected host. */
  12857. const String& getHostName() const throw() { return hostName; }
  12858. /** Returns the port number that's currently open. */
  12859. int getPort() const throw() { return portNumber; }
  12860. /** True if the socket is connected to this machine rather than over the network. */
  12861. bool isLocal() const throw();
  12862. /** Waits until the socket is ready for reading or writing.
  12863. If readyForReading is true, it will wait until the socket is ready for
  12864. reading; if false, it will wait until it's ready for writing.
  12865. If the timeout is < 0, it will wait forever, or else will give up after
  12866. the specified time.
  12867. If the socket is ready on return, this returns 1. If it times-out before
  12868. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12869. */
  12870. int waitUntilReady (bool readyForReading,
  12871. int timeoutMsecs) const;
  12872. /** Reads bytes from the socket.
  12873. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12874. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12875. flag is false, the method will return as much data as is currently available
  12876. without blocking.
  12877. @returns the number of bytes read, or -1 if there was an error.
  12878. @see waitUntilReady
  12879. */
  12880. int read (void* destBuffer, int maxBytesToRead,
  12881. bool blockUntilSpecifiedAmountHasArrived);
  12882. /** Writes bytes to the socket from a buffer.
  12883. Note that this method will block unless you have checked the socket is ready
  12884. for writing before calling it (see the waitUntilReady() method).
  12885. @returns the number of bytes written, or -1 if there was an error.
  12886. */
  12887. int write (const void* sourceBuffer, int numBytesToWrite);
  12888. /** Puts this socket into "listener" mode.
  12889. When in this mode, your thread can call waitForNextConnection() repeatedly,
  12890. which will spawn new sockets for each new connection, so that these can
  12891. be handled in parallel by other threads.
  12892. @param portNumber the port number to listen on
  12893. @param localHostName the interface address to listen on - pass an empty
  12894. string to listen on all addresses
  12895. @returns true if it manages to open the socket successfully.
  12896. @see waitForNextConnection
  12897. */
  12898. bool createListener (int portNumber, const String& localHostName = String::empty);
  12899. /** When in "listener" mode, this waits for a connection and spawns it as a new
  12900. socket.
  12901. The object that gets returned will be owned by the caller.
  12902. This method can only be called after using createListener().
  12903. @see createListener
  12904. */
  12905. StreamingSocket* waitForNextConnection() const;
  12906. private:
  12907. String hostName;
  12908. int volatile portNumber, handle;
  12909. bool connected, isListener;
  12910. StreamingSocket (const String& hostname, int portNumber, int handle);
  12911. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  12912. };
  12913. /**
  12914. A wrapper for a datagram (UDP) socket.
  12915. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12916. sockets, you could also try the InterprocessConnection class.
  12917. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  12918. */
  12919. class JUCE_API DatagramSocket
  12920. {
  12921. public:
  12922. /**
  12923. Creates an (uninitialised) datagram socket.
  12924. The localPortNumber is the port on which to bind this socket. If this value is 0,
  12925. the port number is assigned by the operating system.
  12926. To use the socket for sending, call the connect() method. This will not immediately
  12927. make a connection, but will save the destination you've provided. After this, you can
  12928. call read() or write().
  12929. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  12930. (may require extra privileges on linux)
  12931. To wait for other sockets to connect to this one, call waitForNextConnection().
  12932. */
  12933. DatagramSocket (int localPortNumber,
  12934. bool enableBroadcasting = false);
  12935. /** Destructor. */
  12936. ~DatagramSocket();
  12937. /** Binds the socket to the specified local port.
  12938. @returns true on success; false may indicate that another socket is already bound
  12939. on the same port
  12940. */
  12941. bool bindToPort (int localPortNumber);
  12942. /** Tries to connect the socket to hostname:port.
  12943. If timeOutMillisecs is 0, then this method will block until the operating system
  12944. rejects the connection (which could take a long time).
  12945. @returns true if it succeeds.
  12946. @see isConnected
  12947. */
  12948. bool connect (const String& remoteHostname,
  12949. int remotePortNumber,
  12950. int timeOutMillisecs = 3000);
  12951. /** True if the socket is currently connected. */
  12952. bool isConnected() const throw() { return connected; }
  12953. /** Closes the connection. */
  12954. void close();
  12955. /** Returns the name of the currently connected host. */
  12956. const String& getHostName() const throw() { return hostName; }
  12957. /** Returns the port number that's currently open. */
  12958. int getPort() const throw() { return portNumber; }
  12959. /** True if the socket is connected to this machine rather than over the network. */
  12960. bool isLocal() const throw();
  12961. /** Waits until the socket is ready for reading or writing.
  12962. If readyForReading is true, it will wait until the socket is ready for
  12963. reading; if false, it will wait until it's ready for writing.
  12964. If the timeout is < 0, it will wait forever, or else will give up after
  12965. the specified time.
  12966. If the socket is ready on return, this returns 1. If it times-out before
  12967. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12968. */
  12969. int waitUntilReady (bool readyForReading,
  12970. int timeoutMsecs) const;
  12971. /** Reads bytes from the socket.
  12972. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12973. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12974. flag is false, the method will return as much data as is currently available
  12975. without blocking.
  12976. @returns the number of bytes read, or -1 if there was an error.
  12977. @see waitUntilReady
  12978. */
  12979. int read (void* destBuffer, int maxBytesToRead,
  12980. bool blockUntilSpecifiedAmountHasArrived);
  12981. /** Writes bytes to the socket from a buffer.
  12982. Note that this method will block unless you have checked the socket is ready
  12983. for writing before calling it (see the waitUntilReady() method).
  12984. @returns the number of bytes written, or -1 if there was an error.
  12985. */
  12986. int write (const void* sourceBuffer, int numBytesToWrite);
  12987. /** This waits for incoming data to be sent, and returns a socket that can be used
  12988. to read it.
  12989. The object that gets returned is owned by the caller, and can't be used for
  12990. sending, but can be used to read the data.
  12991. */
  12992. DatagramSocket* waitForNextConnection() const;
  12993. private:
  12994. String hostName;
  12995. int volatile portNumber, handle;
  12996. bool connected, allowBroadcast;
  12997. void* serverAddress;
  12998. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  12999. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  13000. };
  13001. #endif // __JUCE_SOCKET_JUCEHEADER__
  13002. /*** End of inlined file: juce_Socket.h ***/
  13003. #endif
  13004. #ifndef __JUCE_URL_JUCEHEADER__
  13005. /*** Start of inlined file: juce_URL.h ***/
  13006. #ifndef __JUCE_URL_JUCEHEADER__
  13007. #define __JUCE_URL_JUCEHEADER__
  13008. /**
  13009. Represents a URL and has a bunch of useful functions to manipulate it.
  13010. This class can be used to launch URLs in browsers, and also to create
  13011. InputStreams that can read from remote http or ftp sources.
  13012. */
  13013. class JUCE_API URL
  13014. {
  13015. public:
  13016. /** Creates an empty URL. */
  13017. URL();
  13018. /** Creates a URL from a string. */
  13019. URL (const String& url);
  13020. /** Creates a copy of another URL. */
  13021. URL (const URL& other);
  13022. /** Destructor. */
  13023. ~URL();
  13024. /** Copies this URL from another one. */
  13025. URL& operator= (const URL& other);
  13026. /** Returns a string version of the URL.
  13027. If includeGetParameters is true and any parameters have been set with the
  13028. withParameter() method, then the string will have these appended on the
  13029. end and url-encoded.
  13030. */
  13031. const String toString (bool includeGetParameters) const;
  13032. /** True if it seems to be valid. */
  13033. bool isWellFormed() const;
  13034. /** Returns just the domain part of the URL.
  13035. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  13036. */
  13037. const String getDomain() const;
  13038. /** Returns the path part of the URL.
  13039. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  13040. */
  13041. const String getSubPath() const;
  13042. /** Returns the scheme of the URL.
  13043. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  13044. include the colon).
  13045. */
  13046. const String getScheme() const;
  13047. /** Returns a new version of this URL that uses a different sub-path.
  13048. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  13049. "bar", it'll return "http://www.xyz.com/bar?x=1".
  13050. */
  13051. const URL withNewSubPath (const String& newPath) const;
  13052. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  13053. Any control characters in the value will be encoded.
  13054. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  13055. would produce a new url whose toString(true) method would return
  13056. "www.fish.com?amount=some+fish".
  13057. */
  13058. const URL withParameter (const String& parameterName,
  13059. const String& parameterValue) const;
  13060. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  13061. When performing a POST where one of your parameters is a binary file, this
  13062. lets you specify the file.
  13063. Note that the filename is stored, but the file itself won't actually be read
  13064. until this URL is later used to create a network input stream.
  13065. */
  13066. const URL withFileToUpload (const String& parameterName,
  13067. const File& fileToUpload,
  13068. const String& mimeType) const;
  13069. /** Returns a set of all the parameters encoded into the url.
  13070. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  13071. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  13072. The values returned will have been cleaned up to remove any escape characters.
  13073. @see getNamedParameter, withParameter
  13074. */
  13075. const StringPairArray& getParameters() const;
  13076. /** Returns the set of files that should be uploaded as part of a POST operation.
  13077. This is the set of files that were added to the URL with the withFileToUpload()
  13078. method.
  13079. */
  13080. const StringPairArray& getFilesToUpload() const;
  13081. /** Returns the set of mime types associated with each of the upload files.
  13082. */
  13083. const StringPairArray& getMimeTypesOfUploadFiles() const;
  13084. /** Returns a copy of this URL, with a block of data to send as the POST data.
  13085. If you're setting the POST data, be careful not to have any parameters set
  13086. as well, otherwise it'll all get thrown in together, and might not have the
  13087. desired effect.
  13088. If the URL already contains some POST data, this will replace it, rather
  13089. than being appended to it.
  13090. This data will only be used if you specify a post operation when you call
  13091. createInputStream().
  13092. */
  13093. const URL withPOSTData (const String& postData) const;
  13094. /** Returns the data that was set using withPOSTData().
  13095. */
  13096. const String getPostData() const { return postData; }
  13097. /** Tries to launch the system's default browser to open the URL.
  13098. Returns true if this seems to have worked.
  13099. */
  13100. bool launchInDefaultBrowser() const;
  13101. /** Takes a guess as to whether a string might be a valid website address.
  13102. This isn't foolproof!
  13103. */
  13104. static bool isProbablyAWebsiteURL (const String& possibleURL);
  13105. /** Takes a guess as to whether a string might be a valid email address.
  13106. This isn't foolproof!
  13107. */
  13108. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  13109. /** This callback function can be used by the createInputStream() method.
  13110. It allows your app to receive progress updates during a lengthy POST operation. If you
  13111. want to continue the operation, this should return true, or false to abort.
  13112. */
  13113. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  13114. /** Attempts to open a stream that can read from this URL.
  13115. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  13116. the paramters, otherwise it'll encode them into the
  13117. URL and do a 'GET'.
  13118. @param progressCallback if this is non-zero, it lets you supply a callback function
  13119. to keep track of the operation's progress. This can be useful
  13120. for lengthy POST operations, so that you can provide user feedback.
  13121. @param progressCallbackContext if a callback is specified, this value will be passed to
  13122. the function
  13123. @param extraHeaders if not empty, this string is appended onto the headers that
  13124. are used for the request. It must therefore be a valid set of HTML
  13125. header directives, separated by newlines.
  13126. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  13127. a negative number, it will be infinite. Otherwise it specifies a
  13128. time in milliseconds.
  13129. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  13130. in the response will be stored in this array
  13131. @returns an input stream that the caller must delete, or a null pointer if there was an
  13132. error trying to open it.
  13133. */
  13134. InputStream* createInputStream (bool usePostCommand,
  13135. OpenStreamProgressCallback* progressCallback = 0,
  13136. void* progressCallbackContext = 0,
  13137. const String& extraHeaders = String::empty,
  13138. int connectionTimeOutMs = 0,
  13139. StringPairArray* responseHeaders = 0) const;
  13140. /** Tries to download the entire contents of this URL into a binary data block.
  13141. If it succeeds, this will return true and append the data it read onto the end
  13142. of the memory block.
  13143. @param destData the memory block to append the new data to
  13144. @param usePostCommand whether to use a POST command to get the data (uses
  13145. a GET command if this is false)
  13146. @see readEntireTextStream, readEntireXmlStream
  13147. */
  13148. bool readEntireBinaryStream (MemoryBlock& destData,
  13149. bool usePostCommand = false) const;
  13150. /** Tries to download the entire contents of this URL as a string.
  13151. If it fails, this will return an empty string, otherwise it will return the
  13152. contents of the downloaded file. If you need to distinguish between a read
  13153. operation that fails and one that returns an empty string, you'll need to use
  13154. a different method, such as readEntireBinaryStream().
  13155. @param usePostCommand whether to use a POST command to get the data (uses
  13156. a GET command if this is false)
  13157. @see readEntireBinaryStream, readEntireXmlStream
  13158. */
  13159. const String readEntireTextStream (bool usePostCommand = false) const;
  13160. /** Tries to download the entire contents of this URL and parse it as XML.
  13161. If it fails, or if the text that it reads can't be parsed as XML, this will
  13162. return 0.
  13163. When it returns a valid XmlElement object, the caller is responsibile for deleting
  13164. this object when no longer needed.
  13165. @param usePostCommand whether to use a POST command to get the data (uses
  13166. a GET command if this is false)
  13167. @see readEntireBinaryStream, readEntireTextStream
  13168. */
  13169. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  13170. /** Adds escape sequences to a string to encode any characters that aren't
  13171. legal in a URL.
  13172. E.g. any spaces will be replaced with "%20".
  13173. This is the opposite of removeEscapeChars().
  13174. If isParameter is true, it means that the string is going to be used
  13175. as a parameter, so it also encodes '$' and ',' (which would otherwise
  13176. be legal in a URL.
  13177. @see removeEscapeChars
  13178. */
  13179. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  13180. bool isParameter);
  13181. /** Replaces any escape character sequences in a string with their original
  13182. character codes.
  13183. E.g. any instances of "%20" will be replaced by a space.
  13184. This is the opposite of addEscapeChars().
  13185. @see addEscapeChars
  13186. */
  13187. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  13188. private:
  13189. String url, postData;
  13190. StringPairArray parameters, filesToUpload, mimeTypes;
  13191. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  13192. OpenStreamProgressCallback* progressCallback,
  13193. void* progressCallbackContext, const String& headers,
  13194. const int timeOutMs, StringPairArray* responseHeaders);
  13195. JUCE_LEAK_DETECTOR (URL);
  13196. };
  13197. #endif // __JUCE_URL_JUCEHEADER__
  13198. /*** End of inlined file: juce_URL.h ***/
  13199. #endif
  13200. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  13201. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  13202. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  13203. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  13204. /** Wraps another input stream, and reads from it using an intermediate buffer
  13205. If you're using an input stream such as a file input stream, and making lots of
  13206. small read accesses to it, it's probably sensible to wrap it in one of these,
  13207. so that the source stream gets accessed in larger chunk sizes, meaning less
  13208. work for the underlying stream.
  13209. */
  13210. class JUCE_API BufferedInputStream : public InputStream
  13211. {
  13212. public:
  13213. /** Creates a BufferedInputStream from an input source.
  13214. @param sourceStream the source stream to read from
  13215. @param bufferSize the size of reservoir to use to buffer the source
  13216. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  13217. deleted by this object when it is itself deleted.
  13218. */
  13219. BufferedInputStream (InputStream* sourceStream,
  13220. int bufferSize,
  13221. bool deleteSourceWhenDestroyed);
  13222. /** Creates a BufferedInputStream from an input source.
  13223. @param sourceStream the source stream to read from - the source stream must not
  13224. be deleted until this object has been destroyed.
  13225. @param bufferSize the size of reservoir to use to buffer the source
  13226. */
  13227. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  13228. /** Destructor.
  13229. This may also delete the source stream, if that option was chosen when the
  13230. buffered stream was created.
  13231. */
  13232. ~BufferedInputStream();
  13233. int64 getTotalLength();
  13234. int64 getPosition();
  13235. bool setPosition (int64 newPosition);
  13236. int read (void* destBuffer, int maxBytesToRead);
  13237. const String readString();
  13238. bool isExhausted();
  13239. private:
  13240. InputStream* const source;
  13241. ScopedPointer <InputStream> sourceToDelete;
  13242. int bufferSize;
  13243. int64 position, lastReadPos, bufferStart, bufferOverlap;
  13244. HeapBlock <char> buffer;
  13245. void ensureBuffered();
  13246. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  13247. };
  13248. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  13249. /*** End of inlined file: juce_BufferedInputStream.h ***/
  13250. #endif
  13251. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  13252. /*** Start of inlined file: juce_FileInputSource.h ***/
  13253. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  13254. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  13255. /**
  13256. A type of InputSource that represents a normal file.
  13257. @see InputSource
  13258. */
  13259. class JUCE_API FileInputSource : public InputSource
  13260. {
  13261. public:
  13262. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  13263. ~FileInputSource();
  13264. InputStream* createInputStream();
  13265. InputStream* createInputStreamFor (const String& relatedItemPath);
  13266. int64 hashCode() const;
  13267. private:
  13268. const File file;
  13269. bool useFileTimeInHashGeneration;
  13270. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  13271. };
  13272. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  13273. /*** End of inlined file: juce_FileInputSource.h ***/
  13274. #endif
  13275. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  13276. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  13277. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  13278. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  13279. /**
  13280. A stream which uses zlib to compress the data written into it.
  13281. @see GZIPDecompressorInputStream
  13282. */
  13283. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  13284. {
  13285. public:
  13286. /** Creates a compression stream.
  13287. @param destStream the stream into which the compressed data should
  13288. be written
  13289. @param compressionLevel how much to compress the data, between 1 and 9, where
  13290. 1 is the fastest/lowest compression, and 9 is the
  13291. slowest/highest compression. Any value outside this range
  13292. indicates that a default compression level should be used.
  13293. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  13294. this stream is destroyed
  13295. @param windowBits this is used internally to change the window size used
  13296. by zlib - leave it as 0 unless you specifically need to set
  13297. its value for some reason
  13298. */
  13299. GZIPCompressorOutputStream (OutputStream* destStream,
  13300. int compressionLevel = 0,
  13301. bool deleteDestStreamWhenDestroyed = false,
  13302. int windowBits = 0);
  13303. /** Destructor. */
  13304. ~GZIPCompressorOutputStream();
  13305. void flush();
  13306. int64 getPosition();
  13307. bool setPosition (int64 newPosition);
  13308. bool write (const void* destBuffer, int howMany);
  13309. /** These are preset values that can be used for the constructor's windowBits paramter.
  13310. For more info about this, see the zlib documentation for its windowBits parameter.
  13311. */
  13312. enum WindowBitsValues
  13313. {
  13314. windowBitsRaw = -15,
  13315. windowBitsGZIP = 15 + 16
  13316. };
  13317. private:
  13318. OutputStream* const destStream;
  13319. ScopedPointer <OutputStream> streamToDelete;
  13320. HeapBlock <uint8> buffer;
  13321. class GZIPCompressorHelper;
  13322. friend class ScopedPointer <GZIPCompressorHelper>;
  13323. ScopedPointer <GZIPCompressorHelper> helper;
  13324. bool doNextBlock();
  13325. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  13326. };
  13327. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  13328. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  13329. #endif
  13330. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  13331. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  13332. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  13333. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  13334. /**
  13335. This stream will decompress a source-stream using zlib.
  13336. Tip: if you're reading lots of small items from one of these streams, you
  13337. can increase the performance enormously by passing it through a
  13338. BufferedInputStream, so that it has to read larger blocks less often.
  13339. @see GZIPCompressorOutputStream
  13340. */
  13341. class JUCE_API GZIPDecompressorInputStream : public InputStream
  13342. {
  13343. public:
  13344. /** Creates a decompressor stream.
  13345. @param sourceStream the stream to read from
  13346. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  13347. when this object is destroyed
  13348. @param noWrap this is used internally by the ZipFile class
  13349. and should be ignored by user applications
  13350. @param uncompressedStreamLength if the creator knows the length that the
  13351. uncompressed stream will be, then it can supply this
  13352. value, which will be returned by getTotalLength()
  13353. */
  13354. GZIPDecompressorInputStream (InputStream* sourceStream,
  13355. bool deleteSourceWhenDestroyed,
  13356. bool noWrap = false,
  13357. int64 uncompressedStreamLength = -1);
  13358. /** Creates a decompressor stream.
  13359. @param sourceStream the stream to read from - the source stream must not be
  13360. deleted until this object has been destroyed
  13361. */
  13362. GZIPDecompressorInputStream (InputStream& sourceStream);
  13363. /** Destructor. */
  13364. ~GZIPDecompressorInputStream();
  13365. int64 getPosition();
  13366. bool setPosition (int64 pos);
  13367. int64 getTotalLength();
  13368. bool isExhausted();
  13369. int read (void* destBuffer, int maxBytesToRead);
  13370. private:
  13371. InputStream* const sourceStream;
  13372. ScopedPointer <InputStream> streamToDelete;
  13373. const int64 uncompressedStreamLength;
  13374. const bool noWrap;
  13375. bool isEof;
  13376. int activeBufferSize;
  13377. int64 originalSourcePos, currentPos;
  13378. HeapBlock <uint8> buffer;
  13379. class GZIPDecompressHelper;
  13380. friend class ScopedPointer <GZIPDecompressHelper>;
  13381. ScopedPointer <GZIPDecompressHelper> helper;
  13382. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  13383. };
  13384. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  13385. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  13386. #endif
  13387. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  13388. #endif
  13389. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  13390. #endif
  13391. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  13392. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  13393. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  13394. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  13395. /**
  13396. Allows a block of data and to be accessed as a stream.
  13397. This can either be used to refer to a shared block of memory, or can make its
  13398. own internal copy of the data when the MemoryInputStream is created.
  13399. */
  13400. class JUCE_API MemoryInputStream : public InputStream
  13401. {
  13402. public:
  13403. /** Creates a MemoryInputStream.
  13404. @param sourceData the block of data to use as the stream's source
  13405. @param sourceDataSize the number of bytes in the source data block
  13406. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  13407. the source data, so this data shouldn't be changed
  13408. for the lifetime of the stream; if this parameter is
  13409. true, the stream will make its own copy of the
  13410. data and use that.
  13411. */
  13412. MemoryInputStream (const void* sourceData,
  13413. size_t sourceDataSize,
  13414. bool keepInternalCopyOfData);
  13415. /** Creates a MemoryInputStream.
  13416. @param data a block of data to use as the stream's source
  13417. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  13418. the source data, so this data shouldn't be changed
  13419. for the lifetime of the stream; if this parameter is
  13420. true, the stream will make its own copy of the
  13421. data and use that.
  13422. */
  13423. MemoryInputStream (const MemoryBlock& data,
  13424. bool keepInternalCopyOfData);
  13425. /** Destructor. */
  13426. ~MemoryInputStream();
  13427. int64 getPosition();
  13428. bool setPosition (int64 pos);
  13429. int64 getTotalLength();
  13430. bool isExhausted();
  13431. int read (void* destBuffer, int maxBytesToRead);
  13432. private:
  13433. const char* data;
  13434. size_t dataSize, position;
  13435. MemoryBlock internalCopy;
  13436. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  13437. };
  13438. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  13439. /*** End of inlined file: juce_MemoryInputStream.h ***/
  13440. #endif
  13441. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  13442. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  13443. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  13444. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  13445. /**
  13446. Writes data to an internal memory buffer, which grows as required.
  13447. The data that was written into the stream can then be accessed later as
  13448. a contiguous block of memory.
  13449. */
  13450. class JUCE_API MemoryOutputStream : public OutputStream
  13451. {
  13452. public:
  13453. /** Creates an empty memory stream ready for writing into.
  13454. @param initialSize the intial amount of capacity to allocate for writing into
  13455. */
  13456. MemoryOutputStream (size_t initialSize = 256);
  13457. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  13458. Note that the destination block will always be larger than the amount of data
  13459. that has been written to the stream, because the MemoryOutputStream keeps some
  13460. spare capactity at its end. To trim the block's size down to fit the actual
  13461. data, call flush(), or delete the MemoryOutputStream.
  13462. @param memoryBlockToWriteTo the block into which new data will be written.
  13463. @param appendToExistingBlockContent if this is true, the contents of the block will be
  13464. kept, and new data will be appended to it. If false,
  13465. the block will be cleared before use
  13466. */
  13467. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  13468. bool appendToExistingBlockContent);
  13469. /** Destructor.
  13470. This will free any data that was written to it.
  13471. */
  13472. ~MemoryOutputStream();
  13473. /** Returns a pointer to the data that has been written to the stream.
  13474. @see getDataSize
  13475. */
  13476. const void* getData() const throw();
  13477. /** Returns the number of bytes of data that have been written to the stream.
  13478. @see getData
  13479. */
  13480. size_t getDataSize() const throw() { return size; }
  13481. /** Resets the stream, clearing any data that has been written to it so far. */
  13482. void reset() throw();
  13483. /** Increases the internal storage capacity to be able to contain at least the specified
  13484. amount of data without needing to be resized.
  13485. */
  13486. void preallocate (size_t bytesToPreallocate);
  13487. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  13488. const String toUTF8() const;
  13489. /** Attempts to detect the encoding of the data and convert it to a string.
  13490. @see String::createStringFromData
  13491. */
  13492. const String toString() const;
  13493. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  13494. capacity off the block, so that its length matches the amount of actual data that
  13495. has been written so far.
  13496. */
  13497. void flush();
  13498. bool write (const void* buffer, int howMany);
  13499. int64 getPosition() { return position; }
  13500. bool setPosition (int64 newPosition);
  13501. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  13502. private:
  13503. MemoryBlock& data;
  13504. MemoryBlock internalBlock;
  13505. size_t position, size;
  13506. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  13507. };
  13508. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  13509. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  13510. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  13511. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  13512. #endif
  13513. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  13514. #endif
  13515. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  13516. /*** Start of inlined file: juce_SubregionStream.h ***/
  13517. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  13518. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  13519. /** Wraps another input stream, and reads from a specific part of it.
  13520. This lets you take a subsection of a stream and present it as an entire
  13521. stream in its own right.
  13522. */
  13523. class JUCE_API SubregionStream : public InputStream
  13524. {
  13525. public:
  13526. /** Creates a SubregionStream from an input source.
  13527. @param sourceStream the source stream to read from
  13528. @param startPositionInSourceStream this is the position in the source stream that
  13529. corresponds to position 0 in this stream
  13530. @param lengthOfSourceStream this specifies the maximum number of bytes
  13531. from the source stream that will be passed through
  13532. by this stream. When the position of this stream
  13533. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  13534. If the length passed in here is greater than the length
  13535. of the source stream (as returned by getTotalLength()),
  13536. then the smaller value will be used.
  13537. Passing a negative value for this parameter means it
  13538. will keep reading until the source's end-of-stream.
  13539. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  13540. deleted by this object when it is itself deleted.
  13541. */
  13542. SubregionStream (InputStream* sourceStream,
  13543. int64 startPositionInSourceStream,
  13544. int64 lengthOfSourceStream,
  13545. bool deleteSourceWhenDestroyed);
  13546. /** Destructor.
  13547. This may also delete the source stream, if that option was chosen when the
  13548. buffered stream was created.
  13549. */
  13550. ~SubregionStream();
  13551. int64 getTotalLength();
  13552. int64 getPosition();
  13553. bool setPosition (int64 newPosition);
  13554. int read (void* destBuffer, int maxBytesToRead);
  13555. bool isExhausted();
  13556. private:
  13557. InputStream* const source;
  13558. ScopedPointer <InputStream> sourceToDelete;
  13559. const int64 startPositionInSourceStream, lengthOfSourceStream;
  13560. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  13561. };
  13562. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  13563. /*** End of inlined file: juce_SubregionStream.h ***/
  13564. #endif
  13565. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  13566. #endif
  13567. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  13568. /*** Start of inlined file: juce_Expression.h ***/
  13569. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  13570. #define __JUCE_EXPRESSION_JUCEHEADER__
  13571. /**
  13572. A class for dynamically evaluating simple numeric expressions.
  13573. This class can parse a simple C-style string expression involving floating point
  13574. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  13575. are supported, as well as parentheses, and any alphanumeric identifiers are
  13576. assumed to be named symbols which will be resolved when the expression is
  13577. evaluated.
  13578. Expressions which use identifiers and functions require a subclass of
  13579. Expression::EvaluationContext to be supplied when evaluating them, and this object
  13580. is expected to be able to resolve the symbol names and perform the functions that
  13581. are used.
  13582. */
  13583. class JUCE_API Expression
  13584. {
  13585. public:
  13586. /** Creates a simple expression with a value of 0. */
  13587. Expression();
  13588. /** Destructor. */
  13589. ~Expression();
  13590. /** Creates a simple expression with a specified constant value. */
  13591. explicit Expression (double constant);
  13592. /** Creates a copy of an expression. */
  13593. Expression (const Expression& other);
  13594. /** Copies another expression. */
  13595. Expression& operator= (const Expression& other);
  13596. /** Creates an expression by parsing a string.
  13597. If there's a syntax error in the string, this will throw a ParseError exception.
  13598. @throws ParseError
  13599. */
  13600. explicit Expression (const String& stringToParse);
  13601. /** Returns a string version of the expression. */
  13602. const String toString() const;
  13603. /** Returns an expression which is an addtion operation of two existing expressions. */
  13604. const Expression operator+ (const Expression& other) const;
  13605. /** Returns an expression which is a subtraction operation of two existing expressions. */
  13606. const Expression operator- (const Expression& other) const;
  13607. /** Returns an expression which is a multiplication operation of two existing expressions. */
  13608. const Expression operator* (const Expression& other) const;
  13609. /** Returns an expression which is a division operation of two existing expressions. */
  13610. const Expression operator/ (const Expression& other) const;
  13611. /** Returns an expression which performs a negation operation on an existing expression. */
  13612. const Expression operator-() const;
  13613. /** Returns an Expression which is an identifier reference. */
  13614. static const Expression symbol (const String& symbol);
  13615. /** Returns an Expression which is a function call. */
  13616. static const Expression function (const String& functionName, const Array<Expression>& parameters);
  13617. /** Returns an Expression which parses a string from a specified character index.
  13618. The index value is incremented so that on return, it indicates the character that follows
  13619. the end of the expression that was parsed.
  13620. If there's a syntax error in the string, this will throw a ParseError exception.
  13621. @throws ParseError
  13622. */
  13623. static const Expression parse (const String& stringToParse, int& textIndexToStartFrom);
  13624. /** When evaluating an Expression object, this class is used to resolve symbols and
  13625. perform functions that the expression uses.
  13626. */
  13627. class JUCE_API EvaluationContext
  13628. {
  13629. public:
  13630. EvaluationContext();
  13631. virtual ~EvaluationContext();
  13632. /** Returns the value of a symbol.
  13633. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  13634. The member value is set to the part of the symbol that followed the dot, if there is
  13635. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  13636. @throws Expression::EvaluationError
  13637. */
  13638. virtual const Expression getSymbolValue (const String& symbol, const String& member) const;
  13639. /** Executes a named function.
  13640. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  13641. @throws Expression::EvaluationError
  13642. */
  13643. virtual double evaluateFunction (const String& functionName, const double* parameters, int numParams) const;
  13644. };
  13645. /** Evaluates this expression, without using an EvaluationContext.
  13646. Without an EvaluationContext, no symbols can be used, and only basic functions such as sin, cos, tan,
  13647. min, max are available.
  13648. @throws Expression::EvaluationError
  13649. */
  13650. double evaluate() const;
  13651. /** Evaluates this expression, providing a context that should be able to evaluate any symbols
  13652. or functions that it uses.
  13653. @throws Expression::EvaluationError
  13654. */
  13655. double evaluate (const EvaluationContext& context) const;
  13656. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  13657. to make the expression resolve to a target value.
  13658. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  13659. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  13660. case they might just be adjusted by adding a constant to them.
  13661. @throws Expression::EvaluationError
  13662. */
  13663. const Expression adjustedToGiveNewResult (double targetValue, const EvaluationContext& context) const;
  13664. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  13665. const Expression withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const;
  13666. /** Returns true if this expression makes use of the specified symbol.
  13667. If a suitable context is supplied, the search will dereference and recursively check
  13668. all symbols, so that it can be determined whether this expression relies on the given
  13669. symbol at any level in its evaluation. If the context parameter is null, this just checks
  13670. whether the expression contains any direct references to the symbol.
  13671. @throws Expression::EvaluationError
  13672. */
  13673. bool referencesSymbol (const String& symbol, const EvaluationContext* context) const;
  13674. /** Returns true if this expression contains any symbols. */
  13675. bool usesAnySymbols() const;
  13676. /** An exception that can be thrown by Expression::parse(). */
  13677. class ParseError : public std::exception
  13678. {
  13679. public:
  13680. ParseError (const String& message);
  13681. String description;
  13682. };
  13683. /** An exception that can be thrown by Expression::evaluate(). */
  13684. class EvaluationError : public std::exception
  13685. {
  13686. public:
  13687. EvaluationError (const String& message);
  13688. EvaluationError (const String& symbolName, const String& memberName);
  13689. String description;
  13690. };
  13691. /** Expression type.
  13692. @see Expression::getType()
  13693. */
  13694. enum Type
  13695. {
  13696. constantType,
  13697. functionType,
  13698. operatorType,
  13699. symbolType
  13700. };
  13701. /** Returns the type of this expression. */
  13702. Type getType() const throw();
  13703. /** If this expression is a symbol, this returns its full name. */
  13704. const String getSymbol() const;
  13705. /** For a symbol that contains a dot, this returns the two */
  13706. void getSymbolParts (String& objectName, String& memberName) const;
  13707. /** If this expression is a function, this returns its name. */
  13708. const String getFunction() const;
  13709. /** If this expression is an operator, this returns its name.
  13710. E.g. "+", "-", "*", "/", etc.
  13711. */
  13712. const String getOperator() const;
  13713. /** Returns the number of inputs to this expression.
  13714. @see getInput
  13715. */
  13716. int getNumInputs() const;
  13717. /** Retrieves one of the inputs to this expression.
  13718. @see getNumInputs
  13719. */
  13720. const Expression getInput (int index) const;
  13721. private:
  13722. class Helpers;
  13723. friend class Helpers;
  13724. class Term : public ReferenceCountedObject
  13725. {
  13726. public:
  13727. Term() {}
  13728. virtual ~Term() {}
  13729. virtual Term* clone() const = 0;
  13730. virtual double evaluate (const EvaluationContext&, int recursionDepth) const = 0;
  13731. virtual int getNumInputs() const = 0;
  13732. virtual Term* getInput (int index) const = 0;
  13733. virtual int getInputIndexFor (const Term* possibleInput) const;
  13734. virtual const String toString() const = 0;
  13735. virtual int getOperatorPrecedence() const;
  13736. virtual bool referencesSymbol (const String& symbol, const EvaluationContext*, int recursionDepth) const;
  13737. virtual const ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const EvaluationContext&, const Term* inputTerm,
  13738. double overallTarget, Term* topLevelTerm) const;
  13739. virtual const ReferenceCountedObjectPtr<Term> negated();
  13740. virtual Type getType() const throw() = 0;
  13741. virtual void getSymbolParts (String& objectName, String& memberName) const;
  13742. virtual const String getFunctionName() const;
  13743. private:
  13744. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Term);
  13745. };
  13746. friend class ScopedPointer<Term>;
  13747. ReferenceCountedObjectPtr<Term> term;
  13748. explicit Expression (Term* term);
  13749. };
  13750. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  13751. /*** End of inlined file: juce_Expression.h ***/
  13752. #endif
  13753. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  13754. #endif
  13755. #ifndef __JUCE_RANDOM_JUCEHEADER__
  13756. /*** Start of inlined file: juce_Random.h ***/
  13757. #ifndef __JUCE_RANDOM_JUCEHEADER__
  13758. #define __JUCE_RANDOM_JUCEHEADER__
  13759. /**
  13760. A simple pseudo-random number generator.
  13761. */
  13762. class JUCE_API Random
  13763. {
  13764. public:
  13765. /** Creates a Random object based on a seed value.
  13766. For a given seed value, the subsequent numbers generated by this object
  13767. will be predictable, so a good idea is to set this value based
  13768. on the time, e.g.
  13769. new Random (Time::currentTimeMillis())
  13770. */
  13771. explicit Random (int64 seedValue) throw();
  13772. /** Destructor. */
  13773. ~Random() throw();
  13774. /** Returns the next random 32 bit integer.
  13775. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  13776. */
  13777. int nextInt() throw();
  13778. /** Returns the next random number, limited to a given range.
  13779. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  13780. */
  13781. int nextInt (int maxValue) throw();
  13782. /** Returns the next 64-bit random number.
  13783. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  13784. */
  13785. int64 nextInt64() throw();
  13786. /** Returns the next random floating-point number.
  13787. @returns a random value in the range 0 to 1.0
  13788. */
  13789. float nextFloat() throw();
  13790. /** Returns the next random floating-point number.
  13791. @returns a random value in the range 0 to 1.0
  13792. */
  13793. double nextDouble() throw();
  13794. /** Returns the next random boolean value.
  13795. */
  13796. bool nextBool() throw();
  13797. /** Returns a BigInteger containing a random number.
  13798. @returns a random value in the range 0 to (maximumValue - 1).
  13799. */
  13800. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  13801. /** Sets a range of bits in a BigInteger to random values. */
  13802. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  13803. /** To avoid the overhead of having to create a new Random object whenever
  13804. you need a number, this is a shared application-wide object that
  13805. can be used.
  13806. It's not thread-safe though, so threads should use their own Random object.
  13807. */
  13808. static Random& getSystemRandom() throw();
  13809. /** Resets this Random object to a given seed value. */
  13810. void setSeed (int64 newSeed) throw();
  13811. /** Merges this object's seed with another value.
  13812. This sets the seed to be a value created by combining the current seed and this
  13813. new value.
  13814. */
  13815. void combineSeed (int64 seedValue) throw();
  13816. /** Reseeds this generator using a value generated from various semi-random system
  13817. properties like the current time, etc.
  13818. Because this function convolves the time with the last seed value, calling
  13819. it repeatedly will increase the randomness of the final result.
  13820. */
  13821. void setSeedRandomly();
  13822. private:
  13823. int64 seed;
  13824. JUCE_LEAK_DETECTOR (Random);
  13825. };
  13826. #endif // __JUCE_RANDOM_JUCEHEADER__
  13827. /*** End of inlined file: juce_Random.h ***/
  13828. #endif
  13829. #ifndef __JUCE_RANGE_JUCEHEADER__
  13830. #endif
  13831. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  13832. #endif
  13833. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  13834. #endif
  13835. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  13836. #endif
  13837. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  13838. #endif
  13839. #ifndef __JUCE_MEMORY_JUCEHEADER__
  13840. #endif
  13841. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  13842. #endif
  13843. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  13844. #endif
  13845. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  13846. #endif
  13847. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  13848. /*** Start of inlined file: juce_WeakReference.h ***/
  13849. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  13850. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  13851. /**
  13852. This class acts as a pointer which will automatically become null if the object
  13853. to which it points is deleted.
  13854. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  13855. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  13856. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  13857. E.g.
  13858. @code
  13859. class MyObject
  13860. {
  13861. public:
  13862. MyObject()
  13863. {
  13864. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  13865. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  13866. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  13867. // the first call to getWeakReference().
  13868. }
  13869. ~MyObject()
  13870. {
  13871. // This will zero all the references - you need to call this in your destructor.
  13872. masterReference.clear();
  13873. }
  13874. // Your object must provide a method that looks pretty much identical to this (except
  13875. // for the templated class name, of course).
  13876. const WeakReference<MyObject>::SharedRef& getWeakReference()
  13877. {
  13878. return masterReference (this);
  13879. }
  13880. private:
  13881. // You need to embed one of these inside your object. It can be private.
  13882. WeakReference<MyObject>::Master masterReference;
  13883. };
  13884. // Here's an example of using a pointer..
  13885. MyObject* n = new MyObject();
  13886. WeakReference<MyObject> myObjectRef = n;
  13887. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  13888. delete n;
  13889. MyObject* pointer2 = myObjectRef; // returns a null pointer
  13890. @endcode
  13891. @see WeakReference::Master
  13892. */
  13893. template <class ObjectType>
  13894. class WeakReference
  13895. {
  13896. public:
  13897. /** Creates a null SafePointer. */
  13898. WeakReference() throw() {}
  13899. /** Creates a WeakReference that points at the given object. */
  13900. WeakReference (ObjectType* const object) : holder (object != 0 ? object->getWeakReference() : 0) {}
  13901. /** Creates a copy of another WeakReference. */
  13902. WeakReference (const WeakReference& other) throw() : holder (other.holder) {}
  13903. /** Copies another pointer to this one. */
  13904. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  13905. /** Copies another pointer to this one. */
  13906. WeakReference& operator= (ObjectType* const newObject) { holder = newObject != 0 ? newObject->getWeakReference() : 0; return *this; }
  13907. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  13908. ObjectType* get() const throw() { return holder != 0 ? holder->get() : 0; }
  13909. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  13910. operator ObjectType*() const throw() { return get(); }
  13911. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  13912. ObjectType* operator->() throw() { return get(); }
  13913. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  13914. const ObjectType* operator->() const throw() { return get(); }
  13915. /** This returns true if this reference has been pointing at an object, but that object has
  13916. since been deleted.
  13917. If this reference was only ever pointing at a null pointer, this will return false. Using
  13918. operator=() to make this refer to a different object will reset this flag to match the status
  13919. of the reference from which you're copying.
  13920. */
  13921. bool wasObjectDeleted() const throw() { return holder != 0 && holder->get() == 0; }
  13922. bool operator== (ObjectType* const object) const throw() { return get() == object; }
  13923. bool operator!= (ObjectType* const object) const throw() { return get() != object; }
  13924. /** This class is used internally by the WeakReference class - don't use it directly
  13925. in your code!
  13926. @see WeakReference
  13927. */
  13928. class SharedPointer : public ReferenceCountedObject
  13929. {
  13930. public:
  13931. explicit SharedPointer (ObjectType* const owner_) throw() : owner (owner_) {}
  13932. inline ObjectType* get() const throw() { return owner; }
  13933. void clearPointer() throw() { owner = 0; }
  13934. private:
  13935. ObjectType* volatile owner;
  13936. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  13937. };
  13938. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  13939. /**
  13940. This class is embedded inside an object to which you want to attach WeakReference pointers.
  13941. See the WeakReference class notes for an example of how to use this class.
  13942. @see WeakReference
  13943. */
  13944. class Master
  13945. {
  13946. public:
  13947. Master() throw() {}
  13948. ~Master()
  13949. {
  13950. // You must remember to call clear() in your source object's destructor! See the notes
  13951. // for the WeakReference class for an example of how to do this.
  13952. jassert (sharedPointer == 0 || sharedPointer->get() == 0);
  13953. }
  13954. /** The first call to this method will create an internal object that is shared by all weak
  13955. references to the object.
  13956. You need to call this from your main object's getWeakReference() method - see the WeakReference
  13957. class notes for an example.
  13958. */
  13959. const SharedRef& operator() (ObjectType* const object)
  13960. {
  13961. if (sharedPointer == 0)
  13962. {
  13963. sharedPointer = new SharedPointer (object);
  13964. }
  13965. else
  13966. {
  13967. // You're trying to create a weak reference to an object that has already been deleted!!
  13968. jassert (sharedPointer->get() != 0);
  13969. }
  13970. return sharedPointer;
  13971. }
  13972. /** The object that owns this master pointer should call this before it gets destroyed,
  13973. to zero all the references to this object that may be out there. See the WeakReference
  13974. class notes for an example of how to do this.
  13975. */
  13976. void clear()
  13977. {
  13978. if (sharedPointer != 0)
  13979. sharedPointer->clearPointer();
  13980. }
  13981. private:
  13982. SharedRef sharedPointer;
  13983. JUCE_DECLARE_NON_COPYABLE (Master);
  13984. };
  13985. private:
  13986. SharedRef holder;
  13987. };
  13988. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  13989. /*** End of inlined file: juce_WeakReference.h ***/
  13990. #endif
  13991. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  13992. #endif
  13993. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  13994. #endif
  13995. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  13996. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  13997. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  13998. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  13999. /** Used in the same way as the T(text) macro, this will attempt to translate a
  14000. string into a localised version using the LocalisedStrings class.
  14001. @see LocalisedStrings
  14002. */
  14003. #define TRANS(stringLiteral) \
  14004. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  14005. /**
  14006. Used to convert strings to localised foreign-language versions.
  14007. This is basically a look-up table of strings and their translated equivalents.
  14008. It can be loaded from a text file, so that you can supply a set of localised
  14009. versions of strings that you use in your app.
  14010. To use it in your code, simply call the translate() method on each string that
  14011. might have foreign versions, and if none is found, the method will just return
  14012. the original string.
  14013. The translation file should start with some lines specifying a description of
  14014. the language it contains, and also a list of ISO country codes where it might
  14015. be appropriate to use the file. After that, each line of the file should contain
  14016. a pair of quoted strings with an '=' sign.
  14017. E.g. for a french translation, the file might be:
  14018. @code
  14019. language: French
  14020. countries: fr be mc ch lu
  14021. "hello" = "bonjour"
  14022. "goodbye" = "au revoir"
  14023. @endcode
  14024. If the strings need to contain a quote character, they can use '\"' instead, and
  14025. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  14026. (you can use this to add comments).
  14027. Note that this is a singleton class, so don't create or destroy the object directly.
  14028. There's also a TRANS(text) macro defined to make it easy to use the this.
  14029. E.g. @code
  14030. printSomething (TRANS("hello"));
  14031. @endcode
  14032. This macro is used in the Juce classes themselves, so your application has a chance to
  14033. intercept and translate any internal Juce text strings that might be shown. (You can easily
  14034. get a list of all the messages by searching for the TRANS() macro in the Juce source
  14035. code).
  14036. */
  14037. class JUCE_API LocalisedStrings
  14038. {
  14039. public:
  14040. /** Creates a set of translations from the text of a translation file.
  14041. When you create one of these, you can call setCurrentMappings() to make it
  14042. the set of mappings that the system's using.
  14043. */
  14044. LocalisedStrings (const String& fileContents);
  14045. /** Creates a set of translations from a file.
  14046. When you create one of these, you can call setCurrentMappings() to make it
  14047. the set of mappings that the system's using.
  14048. */
  14049. LocalisedStrings (const File& fileToLoad);
  14050. /** Destructor. */
  14051. ~LocalisedStrings();
  14052. /** Selects the current set of mappings to be used by the system.
  14053. The object you pass in will be automatically deleted when no longer needed, so
  14054. don't keep a pointer to it. You can also pass in zero to remove the current
  14055. mappings.
  14056. See also the TRANS() macro, which uses the current set to do its translation.
  14057. @see translateWithCurrentMappings
  14058. */
  14059. static void setCurrentMappings (LocalisedStrings* newTranslations);
  14060. /** Returns the currently selected set of mappings.
  14061. This is the object that was last passed to setCurrentMappings(). It may
  14062. be 0 if none has been created.
  14063. */
  14064. static LocalisedStrings* getCurrentMappings();
  14065. /** Tries to translate a string using the currently selected set of mappings.
  14066. If no mapping has been set, or if the mapping doesn't contain a translation
  14067. for the string, this will just return the original string.
  14068. See also the TRANS() macro, which uses this method to do its translation.
  14069. @see setCurrentMappings, getCurrentMappings
  14070. */
  14071. static const String translateWithCurrentMappings (const String& text);
  14072. /** Tries to translate a string using the currently selected set of mappings.
  14073. If no mapping has been set, or if the mapping doesn't contain a translation
  14074. for the string, this will just return the original string.
  14075. See also the TRANS() macro, which uses this method to do its translation.
  14076. @see setCurrentMappings, getCurrentMappings
  14077. */
  14078. static const String translateWithCurrentMappings (const char* text);
  14079. /** Attempts to look up a string and return its localised version.
  14080. If the string isn't found in the list, the original string will be returned.
  14081. */
  14082. const String translate (const String& text) const;
  14083. /** Returns the name of the language specified in the translation file.
  14084. This is specified in the file using a line starting with "language:", e.g.
  14085. @code
  14086. language: german
  14087. @endcode
  14088. */
  14089. const String getLanguageName() const { return languageName; }
  14090. /** Returns the list of suitable country codes listed in the translation file.
  14091. These is specified in the file using a line starting with "countries:", e.g.
  14092. @code
  14093. countries: fr be mc ch lu
  14094. @endcode
  14095. The country codes are supposed to be 2-character ISO complient codes.
  14096. */
  14097. const StringArray getCountryCodes() const { return countryCodes; }
  14098. /** Indicates whether to use a case-insensitive search when looking up a string.
  14099. This defaults to true.
  14100. */
  14101. void setIgnoresCase (bool shouldIgnoreCase);
  14102. private:
  14103. String languageName;
  14104. StringArray countryCodes;
  14105. StringPairArray translations;
  14106. void loadFromText (const String& fileContents);
  14107. JUCE_LEAK_DETECTOR (LocalisedStrings);
  14108. };
  14109. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  14110. /*** End of inlined file: juce_LocalisedStrings.h ***/
  14111. #endif
  14112. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  14113. #endif
  14114. #ifndef __JUCE_STRING_JUCEHEADER__
  14115. #endif
  14116. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  14117. #endif
  14118. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  14119. #endif
  14120. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  14121. #endif
  14122. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  14123. /*** Start of inlined file: juce_XmlDocument.h ***/
  14124. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  14125. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  14126. /**
  14127. Parses a text-based XML document and creates an XmlElement object from it.
  14128. The parser will parse DTDs to load external entities but won't
  14129. check the document for validity against the DTD.
  14130. e.g.
  14131. @code
  14132. XmlDocument myDocument (File ("myfile.xml"));
  14133. XmlElement* mainElement = myDocument.getDocumentElement();
  14134. if (mainElement == 0)
  14135. {
  14136. String error = myDocument.getLastParseError();
  14137. }
  14138. else
  14139. {
  14140. ..use the element
  14141. }
  14142. @endcode
  14143. Or you can use the static helper methods for quick parsing..
  14144. @code
  14145. XmlElement* xml = XmlDocument::parse (myXmlFile);
  14146. if (xml != 0 && xml->hasTagName ("foobar"))
  14147. {
  14148. ...etc
  14149. @endcode
  14150. @see XmlElement
  14151. */
  14152. class JUCE_API XmlDocument
  14153. {
  14154. public:
  14155. /** Creates an XmlDocument from the xml text.
  14156. The text doesn't actually get parsed until the getDocumentElement() method is called.
  14157. */
  14158. XmlDocument (const String& documentText);
  14159. /** Creates an XmlDocument from a file.
  14160. The text doesn't actually get parsed until the getDocumentElement() method is called.
  14161. */
  14162. XmlDocument (const File& file);
  14163. /** Destructor. */
  14164. ~XmlDocument();
  14165. /** Creates an XmlElement object to represent the main document node.
  14166. This method will do the actual parsing of the text, and if there's a
  14167. parse error, it may returns 0 (and you can find out the error using
  14168. the getLastParseError() method).
  14169. See also the parse() methods, which provide a shorthand way to quickly
  14170. parse a file or string.
  14171. @param onlyReadOuterDocumentElement if true, the parser will only read the
  14172. first section of the file, and will only
  14173. return the outer document element - this
  14174. allows quick checking of large files to
  14175. see if they contain the correct type of
  14176. tag, without having to parse the entire file
  14177. @returns a new XmlElement which the caller will need to delete, or null if
  14178. there was an error.
  14179. @see getLastParseError
  14180. */
  14181. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  14182. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  14183. @returns the error, or an empty string if there was no error.
  14184. */
  14185. const String& getLastParseError() const throw();
  14186. /** Sets an input source object to use for parsing documents that reference external entities.
  14187. If the document has been created from a file, this probably won't be needed, but
  14188. if you're parsing some text and there might be a DTD that references external
  14189. files, you may need to create a custom input source that can retrieve the
  14190. other files it needs.
  14191. The object that is passed-in will be deleted automatically when no longer needed.
  14192. @see InputSource
  14193. */
  14194. void setInputSource (InputSource* newSource) throw();
  14195. /** Sets a flag to change the treatment of empty text elements.
  14196. If this is true (the default state), then any text elements that contain only
  14197. whitespace characters will be ingored during parsing. If you need to catch
  14198. whitespace-only text, then you should set this to false before calling the
  14199. getDocumentElement() method.
  14200. */
  14201. void setEmptyTextElementsIgnored (bool shouldBeIgnored) throw();
  14202. /** A handy static method that parses a file.
  14203. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  14204. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  14205. */
  14206. static XmlElement* parse (const File& file);
  14207. /** A handy static method that parses some XML data.
  14208. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  14209. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  14210. */
  14211. static XmlElement* parse (const String& xmlData);
  14212. private:
  14213. String originalText;
  14214. const juce_wchar* input;
  14215. bool outOfData, errorOccurred;
  14216. String lastError, dtdText;
  14217. StringArray tokenisedDTD;
  14218. bool needToLoadDTD, ignoreEmptyTextElements;
  14219. ScopedPointer <InputSource> inputSource;
  14220. void setLastError (const String& desc, bool carryOn);
  14221. void skipHeader();
  14222. void skipNextWhiteSpace();
  14223. juce_wchar readNextChar() throw();
  14224. XmlElement* readNextElement (bool alsoParseSubElements);
  14225. void readChildElements (XmlElement* parent);
  14226. int findNextTokenLength() throw();
  14227. void readQuotedString (String& result);
  14228. void readEntity (String& result);
  14229. const String getFileContents (const String& filename) const;
  14230. const String expandEntity (const String& entity);
  14231. const String expandExternalEntity (const String& entity);
  14232. const String getParameterEntity (const String& entity);
  14233. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  14234. };
  14235. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  14236. /*** End of inlined file: juce_XmlDocument.h ***/
  14237. #endif
  14238. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  14239. #endif
  14240. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  14241. #endif
  14242. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  14243. /*** Start of inlined file: juce_InterProcessLock.h ***/
  14244. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  14245. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  14246. /**
  14247. Acts as a critical section which processes can use to block each other.
  14248. @see CriticalSection
  14249. */
  14250. class JUCE_API InterProcessLock
  14251. {
  14252. public:
  14253. /** Creates a lock object.
  14254. @param name a name that processes will use to identify this lock object
  14255. */
  14256. explicit InterProcessLock (const String& name);
  14257. /** Destructor.
  14258. This will also release the lock if it's currently held by this process.
  14259. */
  14260. ~InterProcessLock();
  14261. /** Attempts to lock the critical section.
  14262. @param timeOutMillisecs how many milliseconds to wait if the lock
  14263. is already held by another process - a value of
  14264. 0 will return immediately, negative values will wait
  14265. forever
  14266. @returns true if the lock could be gained within the timeout period, or
  14267. false if the timeout expired.
  14268. */
  14269. bool enter (int timeOutMillisecs = -1);
  14270. /** Releases the lock if it's currently held by this process.
  14271. */
  14272. void exit();
  14273. /**
  14274. Automatically locks and unlocks an InterProcessLock object.
  14275. This works like a ScopedLock, but using an InterprocessLock rather than
  14276. a CriticalSection.
  14277. @see ScopedLock
  14278. */
  14279. class ScopedLockType
  14280. {
  14281. public:
  14282. /** Creates a scoped lock.
  14283. As soon as it is created, this will lock the InterProcessLock, and
  14284. when the ScopedLockType object is deleted, the InterProcessLock will
  14285. be unlocked.
  14286. Note that since an InterprocessLock can fail due to errors, you should check
  14287. isLocked() to make sure that the lock was successful before using it.
  14288. Make sure this object is created and deleted by the same thread,
  14289. otherwise there are no guarantees what will happen! Best just to use it
  14290. as a local stack object, rather than creating one with the new() operator.
  14291. */
  14292. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  14293. /** Destructor.
  14294. The InterProcessLock will be unlocked when the destructor is called.
  14295. Make sure this object is created and deleted by the same thread,
  14296. otherwise there are no guarantees what will happen!
  14297. */
  14298. inline ~ScopedLockType() { lock_.exit(); }
  14299. /** Returns true if the InterProcessLock was successfully locked. */
  14300. bool isLocked() const throw() { return lockWasSuccessful; }
  14301. private:
  14302. InterProcessLock& lock_;
  14303. bool lockWasSuccessful;
  14304. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  14305. };
  14306. private:
  14307. class Pimpl;
  14308. friend class ScopedPointer <Pimpl>;
  14309. ScopedPointer <Pimpl> pimpl;
  14310. CriticalSection lock;
  14311. String name;
  14312. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  14313. };
  14314. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  14315. /*** End of inlined file: juce_InterProcessLock.h ***/
  14316. #endif
  14317. #ifndef __JUCE_PROCESS_JUCEHEADER__
  14318. /*** Start of inlined file: juce_Process.h ***/
  14319. #ifndef __JUCE_PROCESS_JUCEHEADER__
  14320. #define __JUCE_PROCESS_JUCEHEADER__
  14321. /** Represents the current executable's process.
  14322. This contains methods for controlling the current application at the
  14323. process-level.
  14324. @see Thread, JUCEApplication
  14325. */
  14326. class JUCE_API Process
  14327. {
  14328. public:
  14329. enum ProcessPriority
  14330. {
  14331. LowPriority = 0,
  14332. NormalPriority = 1,
  14333. HighPriority = 2,
  14334. RealtimePriority = 3
  14335. };
  14336. /** Changes the current process's priority.
  14337. @param priority the process priority, where
  14338. 0=low, 1=normal, 2=high, 3=realtime
  14339. */
  14340. static void setPriority (const ProcessPriority priority);
  14341. /** Kills the current process immediately.
  14342. This is an emergency process terminator that kills the application
  14343. immediately - it's intended only for use only when something goes
  14344. horribly wrong.
  14345. @see JUCEApplication::quit
  14346. */
  14347. static void terminate();
  14348. /** Returns true if this application process is the one that the user is
  14349. currently using.
  14350. */
  14351. static bool isForegroundProcess();
  14352. /** Raises the current process's privilege level.
  14353. Does nothing if this isn't supported by the current OS, or if process
  14354. privilege level is fixed.
  14355. */
  14356. static void raisePrivilege();
  14357. /** Lowers the current process's privilege level.
  14358. Does nothing if this isn't supported by the current OS, or if process
  14359. privilege level is fixed.
  14360. */
  14361. static void lowerPrivilege();
  14362. /** Returns true if this process is being hosted by a debugger.
  14363. */
  14364. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  14365. private:
  14366. Process();
  14367. JUCE_DECLARE_NON_COPYABLE (Process);
  14368. };
  14369. #endif // __JUCE_PROCESS_JUCEHEADER__
  14370. /*** End of inlined file: juce_Process.h ***/
  14371. #endif
  14372. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  14373. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  14374. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  14375. #define __JUCE_READWRITELOCK_JUCEHEADER__
  14376. /*** Start of inlined file: juce_WaitableEvent.h ***/
  14377. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  14378. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  14379. /**
  14380. Allows threads to wait for events triggered by other threads.
  14381. A thread can call wait() on a WaitableObject, and this will suspend the
  14382. calling thread until another thread wakes it up by calling the signal()
  14383. method.
  14384. */
  14385. class JUCE_API WaitableEvent
  14386. {
  14387. public:
  14388. /** Creates a WaitableEvent object.
  14389. @param manualReset If this is false, the event will be reset automatically when the wait()
  14390. method is called. If manualReset is true, then once the event is signalled,
  14391. the only way to reset it will be by calling the reset() method.
  14392. */
  14393. WaitableEvent (bool manualReset = false) throw();
  14394. /** Destructor.
  14395. If other threads are waiting on this object when it gets deleted, this
  14396. can cause nasty errors, so be careful!
  14397. */
  14398. ~WaitableEvent() throw();
  14399. /** Suspends the calling thread until the event has been signalled.
  14400. This will wait until the object's signal() method is called by another thread,
  14401. or until the timeout expires.
  14402. After the event has been signalled, this method will return true and if manualReset
  14403. was set to false in the WaitableEvent's constructor, then the event will be reset.
  14404. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  14405. value will cause it to wait forever.
  14406. @returns true if the object has been signalled, false if the timeout expires first.
  14407. @see signal, reset
  14408. */
  14409. bool wait (int timeOutMilliseconds = -1) const throw();
  14410. /** Wakes up any threads that are currently waiting on this object.
  14411. If signal() is called when nothing is waiting, the next thread to call wait()
  14412. will return immediately and reset the signal.
  14413. @see wait, reset
  14414. */
  14415. void signal() const throw();
  14416. /** Resets the event to an unsignalled state.
  14417. If it's not already signalled, this does nothing.
  14418. */
  14419. void reset() const throw();
  14420. private:
  14421. void* internal;
  14422. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  14423. };
  14424. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  14425. /*** End of inlined file: juce_WaitableEvent.h ***/
  14426. /*** Start of inlined file: juce_Thread.h ***/
  14427. #ifndef __JUCE_THREAD_JUCEHEADER__
  14428. #define __JUCE_THREAD_JUCEHEADER__
  14429. /**
  14430. Encapsulates a thread.
  14431. Subclasses derive from Thread and implement the run() method, in which they
  14432. do their business. The thread can then be started with the startThread() method
  14433. and controlled with various other methods.
  14434. This class also contains some thread-related static methods, such
  14435. as sleep(), yield(), getCurrentThreadId() etc.
  14436. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  14437. MessageManagerLock
  14438. */
  14439. class JUCE_API Thread
  14440. {
  14441. public:
  14442. /**
  14443. Creates a thread.
  14444. When first created, the thread is not running. Use the startThread()
  14445. method to start it.
  14446. */
  14447. explicit Thread (const String& threadName);
  14448. /** Destructor.
  14449. Deleting a Thread object that is running will only give the thread a
  14450. brief opportunity to stop itself cleanly, so it's recommended that you
  14451. should always call stopThread() with a decent timeout before deleting,
  14452. to avoid the thread being forcibly killed (which is a Bad Thing).
  14453. */
  14454. virtual ~Thread();
  14455. /** Must be implemented to perform the thread's actual code.
  14456. Remember that the thread must regularly check the threadShouldExit()
  14457. method whilst running, and if this returns true it should return from
  14458. the run() method as soon as possible to avoid being forcibly killed.
  14459. @see threadShouldExit, startThread
  14460. */
  14461. virtual void run() = 0;
  14462. // Thread control functions..
  14463. /** Starts the thread running.
  14464. This will start the thread's run() method.
  14465. (if it's already started, startThread() won't do anything).
  14466. @see stopThread
  14467. */
  14468. void startThread();
  14469. /** Starts the thread with a given priority.
  14470. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  14471. If the thread is already running, its priority will be changed.
  14472. @see startThread, setPriority
  14473. */
  14474. void startThread (int priority);
  14475. /** Attempts to stop the thread running.
  14476. This method will cause the threadShouldExit() method to return true
  14477. and call notify() in case the thread is currently waiting.
  14478. Hopefully the thread will then respond to this by exiting cleanly, and
  14479. the stopThread method will wait for a given time-period for this to
  14480. happen.
  14481. If the thread is stuck and fails to respond after the time-out, it gets
  14482. forcibly killed, which is a very bad thing to happen, as it could still
  14483. be holding locks, etc. which are needed by other parts of your program.
  14484. @param timeOutMilliseconds The number of milliseconds to wait for the
  14485. thread to finish before killing it by force. A negative
  14486. value in here will wait forever.
  14487. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  14488. */
  14489. void stopThread (int timeOutMilliseconds);
  14490. /** Returns true if the thread is currently active */
  14491. bool isThreadRunning() const;
  14492. /** Sets a flag to tell the thread it should stop.
  14493. Calling this means that the threadShouldExit() method will then return true.
  14494. The thread should be regularly checking this to see whether it should exit.
  14495. If your thread makes use of wait(), you might want to call notify() after calling
  14496. this method, to interrupt any waits that might be in progress, and allow it
  14497. to reach a point where it can exit.
  14498. @see threadShouldExit
  14499. @see waitForThreadToExit
  14500. */
  14501. void signalThreadShouldExit();
  14502. /** Checks whether the thread has been told to stop running.
  14503. Threads need to check this regularly, and if it returns true, they should
  14504. return from their run() method at the first possible opportunity.
  14505. @see signalThreadShouldExit
  14506. */
  14507. inline bool threadShouldExit() const { return threadShouldExit_; }
  14508. /** Waits for the thread to stop.
  14509. This will waits until isThreadRunning() is false or until a timeout expires.
  14510. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  14511. is less than zero, it will wait forever.
  14512. @returns true if the thread exits, or false if the timeout expires first.
  14513. */
  14514. bool waitForThreadToExit (int timeOutMilliseconds) const;
  14515. /** Changes the thread's priority.
  14516. May return false if for some reason the priority can't be changed.
  14517. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  14518. of 5 is normal.
  14519. */
  14520. bool setPriority (int priority);
  14521. /** Changes the priority of the caller thread.
  14522. Similar to setPriority(), but this static method acts on the caller thread.
  14523. May return false if for some reason the priority can't be changed.
  14524. @see setPriority
  14525. */
  14526. static bool setCurrentThreadPriority (int priority);
  14527. /** Sets the affinity mask for the thread.
  14528. This will only have an effect next time the thread is started - i.e. if the
  14529. thread is already running when called, it'll have no effect.
  14530. @see setCurrentThreadAffinityMask
  14531. */
  14532. void setAffinityMask (uint32 affinityMask);
  14533. /** Changes the affinity mask for the caller thread.
  14534. This will change the affinity mask for the thread that calls this static method.
  14535. @see setAffinityMask
  14536. */
  14537. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  14538. // this can be called from any thread that needs to pause..
  14539. static void JUCE_CALLTYPE sleep (int milliseconds);
  14540. /** Yields the calling thread's current time-slot. */
  14541. static void JUCE_CALLTYPE yield();
  14542. /** Makes the thread wait for a notification.
  14543. This puts the thread to sleep until either the timeout period expires, or
  14544. another thread calls the notify() method to wake it up.
  14545. A negative time-out value means that the method will wait indefinitely.
  14546. @returns true if the event has been signalled, false if the timeout expires.
  14547. */
  14548. bool wait (int timeOutMilliseconds) const;
  14549. /** Wakes up the thread.
  14550. If the thread has called the wait() method, this will wake it up.
  14551. @see wait
  14552. */
  14553. void notify() const;
  14554. /** A value type used for thread IDs.
  14555. @see getCurrentThreadId(), getThreadId()
  14556. */
  14557. typedef void* ThreadID;
  14558. /** Returns an id that identifies the caller thread.
  14559. To find the ID of a particular thread object, use getThreadId().
  14560. @returns a unique identifier that identifies the calling thread.
  14561. @see getThreadId
  14562. */
  14563. static ThreadID getCurrentThreadId();
  14564. /** Finds the thread object that is currently running.
  14565. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  14566. object associated with them, so this will return 0.
  14567. */
  14568. static Thread* getCurrentThread();
  14569. /** Returns the ID of this thread.
  14570. That means the ID of this thread object - not of the thread that's calling the method.
  14571. This can change when the thread is started and stopped, and will be invalid if the
  14572. thread's not actually running.
  14573. @see getCurrentThreadId
  14574. */
  14575. ThreadID getThreadId() const throw() { return threadId_; }
  14576. /** Returns the name of the thread.
  14577. This is the name that gets set in the constructor.
  14578. */
  14579. const String getThreadName() const { return threadName_; }
  14580. /** Returns the number of currently-running threads.
  14581. @returns the number of Thread objects known to be currently running.
  14582. @see stopAllThreads
  14583. */
  14584. static int getNumRunningThreads();
  14585. /** Tries to stop all currently-running threads.
  14586. This will attempt to stop all the threads known to be running at the moment.
  14587. */
  14588. static void stopAllThreads (int timeoutInMillisecs);
  14589. private:
  14590. const String threadName_;
  14591. void* volatile threadHandle_;
  14592. ThreadID threadId_;
  14593. CriticalSection startStopLock;
  14594. WaitableEvent startSuspensionEvent_, defaultEvent_;
  14595. int threadPriority_;
  14596. uint32 affinityMask_;
  14597. bool volatile threadShouldExit_;
  14598. #ifndef DOXYGEN
  14599. friend class MessageManager;
  14600. friend void JUCE_API juce_threadEntryPoint (void*);
  14601. #endif
  14602. void launchThread();
  14603. void closeThreadHandle();
  14604. void killThread();
  14605. void threadEntryPoint();
  14606. static void setCurrentThreadName (const String& name);
  14607. static bool setThreadPriority (void* handle, int priority);
  14608. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  14609. };
  14610. #endif // __JUCE_THREAD_JUCEHEADER__
  14611. /*** End of inlined file: juce_Thread.h ***/
  14612. /**
  14613. A critical section that allows multiple simultaneous readers.
  14614. Features of this type of lock are:
  14615. - Multiple readers can hold the lock at the same time, but only one writer
  14616. can hold it at once.
  14617. - Writers trying to gain the lock will be blocked until all readers and writers
  14618. have released it
  14619. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  14620. blocked until the writer has obtained and released it
  14621. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  14622. there are no other readers
  14623. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  14624. - Recursive locking is supported.
  14625. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  14626. */
  14627. class JUCE_API ReadWriteLock
  14628. {
  14629. public:
  14630. /**
  14631. Creates a ReadWriteLock object.
  14632. */
  14633. ReadWriteLock() throw();
  14634. /** Destructor.
  14635. If the object is deleted whilst locked, any subsequent behaviour
  14636. is unpredictable.
  14637. */
  14638. ~ReadWriteLock() throw();
  14639. /** Locks this object for reading.
  14640. Multiple threads can simulaneously lock the object for reading, but if another
  14641. thread has it locked for writing, then this will block until it releases the
  14642. lock.
  14643. @see exitRead, ScopedReadLock
  14644. */
  14645. void enterRead() const throw();
  14646. /** Releases the read-lock.
  14647. If the caller thread hasn't got the lock, this can have unpredictable results.
  14648. If the enterRead() method has been called multiple times by the thread, each
  14649. call must be matched by a call to exitRead() before other threads will be allowed
  14650. to take over the lock.
  14651. @see enterRead, ScopedReadLock
  14652. */
  14653. void exitRead() const throw();
  14654. /** Locks this object for writing.
  14655. This will block until any other threads that have it locked for reading or
  14656. writing have released their lock.
  14657. @see exitWrite, ScopedWriteLock
  14658. */
  14659. void enterWrite() const throw();
  14660. /** Tries to lock this object for writing.
  14661. This is like enterWrite(), but doesn't block - it returns true if it manages
  14662. to obtain the lock.
  14663. @see enterWrite
  14664. */
  14665. bool tryEnterWrite() const throw();
  14666. /** Releases the write-lock.
  14667. If the caller thread hasn't got the lock, this can have unpredictable results.
  14668. If the enterWrite() method has been called multiple times by the thread, each
  14669. call must be matched by a call to exit() before other threads will be allowed
  14670. to take over the lock.
  14671. @see enterWrite, ScopedWriteLock
  14672. */
  14673. void exitWrite() const throw();
  14674. private:
  14675. CriticalSection accessLock;
  14676. WaitableEvent waitEvent;
  14677. mutable int numWaitingWriters, numWriters;
  14678. mutable Thread::ThreadID writerThreadId;
  14679. mutable Array <Thread::ThreadID> readerThreads;
  14680. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  14681. };
  14682. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  14683. /*** End of inlined file: juce_ReadWriteLock.h ***/
  14684. #endif
  14685. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  14686. #endif
  14687. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  14688. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  14689. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  14690. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  14691. /**
  14692. Automatically locks and unlocks a ReadWriteLock object.
  14693. Use one of these as a local variable to control access to a ReadWriteLock.
  14694. e.g. @code
  14695. ReadWriteLock myLock;
  14696. for (;;)
  14697. {
  14698. const ScopedReadLock myScopedLock (myLock);
  14699. // myLock is now locked
  14700. ...do some stuff...
  14701. // myLock gets unlocked here.
  14702. }
  14703. @endcode
  14704. @see ReadWriteLock, ScopedWriteLock
  14705. */
  14706. class JUCE_API ScopedReadLock
  14707. {
  14708. public:
  14709. /** Creates a ScopedReadLock.
  14710. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  14711. when the ScopedReadLock object is deleted, the ReadWriteLock will
  14712. be unlocked.
  14713. Make sure this object is created and deleted by the same thread,
  14714. otherwise there are no guarantees what will happen! Best just to use it
  14715. as a local stack object, rather than creating one with the new() operator.
  14716. */
  14717. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  14718. /** Destructor.
  14719. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  14720. Make sure this object is created and deleted by the same thread,
  14721. otherwise there are no guarantees what will happen!
  14722. */
  14723. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  14724. private:
  14725. const ReadWriteLock& lock_;
  14726. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  14727. };
  14728. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  14729. /*** End of inlined file: juce_ScopedReadLock.h ***/
  14730. #endif
  14731. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  14732. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  14733. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  14734. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  14735. /**
  14736. Automatically tries to lock and unlock a CriticalSection object.
  14737. Use one of these as a local variable to control access to a CriticalSection.
  14738. e.g. @code
  14739. CriticalSection myCriticalSection;
  14740. for (;;)
  14741. {
  14742. const ScopedTryLock myScopedTryLock (myCriticalSection);
  14743. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  14744. // should test this with the isLocked() method before doing your thread-unsafe
  14745. // action..
  14746. if (myScopedTryLock.isLocked())
  14747. {
  14748. ...do some stuff...
  14749. }
  14750. else
  14751. {
  14752. ..our attempt at locking failed because another thread had already locked it..
  14753. }
  14754. // myCriticalSection gets unlocked here (if it was locked)
  14755. }
  14756. @endcode
  14757. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  14758. */
  14759. class JUCE_API ScopedTryLock
  14760. {
  14761. public:
  14762. /** Creates a ScopedTryLock.
  14763. As soon as it is created, this will try to lock the CriticalSection, and
  14764. when the ScopedTryLock object is deleted, the CriticalSection will
  14765. be unlocked if the lock was successful.
  14766. Make sure this object is created and deleted by the same thread,
  14767. otherwise there are no guarantees what will happen! Best just to use it
  14768. as a local stack object, rather than creating one with the new() operator.
  14769. */
  14770. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  14771. /** Destructor.
  14772. The CriticalSection will be unlocked (if locked) when the destructor is called.
  14773. Make sure this object is created and deleted by the same thread,
  14774. otherwise there are no guarantees what will happen!
  14775. */
  14776. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  14777. /** Returns true if the CriticalSection was successfully locked. */
  14778. bool isLocked() const throw() { return lockWasSuccessful; }
  14779. private:
  14780. const CriticalSection& lock_;
  14781. const bool lockWasSuccessful;
  14782. JUCE_DECLARE_NON_COPYABLE (ScopedTryLock);
  14783. };
  14784. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  14785. /*** End of inlined file: juce_ScopedTryLock.h ***/
  14786. #endif
  14787. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  14788. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  14789. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  14790. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  14791. /**
  14792. Automatically locks and unlocks a ReadWriteLock object.
  14793. Use one of these as a local variable to control access to a ReadWriteLock.
  14794. e.g. @code
  14795. ReadWriteLock myLock;
  14796. for (;;)
  14797. {
  14798. const ScopedWriteLock myScopedLock (myLock);
  14799. // myLock is now locked
  14800. ...do some stuff...
  14801. // myLock gets unlocked here.
  14802. }
  14803. @endcode
  14804. @see ReadWriteLock, ScopedReadLock
  14805. */
  14806. class JUCE_API ScopedWriteLock
  14807. {
  14808. public:
  14809. /** Creates a ScopedWriteLock.
  14810. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  14811. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  14812. be unlocked.
  14813. Make sure this object is created and deleted by the same thread,
  14814. otherwise there are no guarantees what will happen! Best just to use it
  14815. as a local stack object, rather than creating one with the new() operator.
  14816. */
  14817. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  14818. /** Destructor.
  14819. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  14820. Make sure this object is created and deleted by the same thread,
  14821. otherwise there are no guarantees what will happen!
  14822. */
  14823. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  14824. private:
  14825. const ReadWriteLock& lock_;
  14826. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  14827. };
  14828. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  14829. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  14830. #endif
  14831. #ifndef __JUCE_THREAD_JUCEHEADER__
  14832. #endif
  14833. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  14834. /*** Start of inlined file: juce_ThreadPool.h ***/
  14835. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  14836. #define __JUCE_THREADPOOL_JUCEHEADER__
  14837. class ThreadPool;
  14838. class ThreadPoolThread;
  14839. /**
  14840. A task that is executed by a ThreadPool object.
  14841. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  14842. its threads.
  14843. The runJob() method needs to be implemented to do the task, and if the code that
  14844. does the work takes a significant time to run, it must keep checking the shouldExit()
  14845. method to see if something is trying to interrupt the job. If shouldExit() returns
  14846. true, the runJob() method must return immediately.
  14847. @see ThreadPool, Thread
  14848. */
  14849. class JUCE_API ThreadPoolJob
  14850. {
  14851. public:
  14852. /** Creates a thread pool job object.
  14853. After creating your job, add it to a thread pool with ThreadPool::addJob().
  14854. */
  14855. explicit ThreadPoolJob (const String& name);
  14856. /** Destructor. */
  14857. virtual ~ThreadPoolJob();
  14858. /** Returns the name of this job.
  14859. @see setJobName
  14860. */
  14861. const String getJobName() const;
  14862. /** Changes the job's name.
  14863. @see getJobName
  14864. */
  14865. void setJobName (const String& newName);
  14866. /** These are the values that can be returned by the runJob() method.
  14867. */
  14868. enum JobStatus
  14869. {
  14870. jobHasFinished = 0, /**< indicates that the job has finished and can be
  14871. removed from the pool. */
  14872. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  14873. should be automatically deleted by the pool. */
  14874. jobNeedsRunningAgain /**< indicates that the job would like to be called
  14875. again when a thread is free. */
  14876. };
  14877. /** Peforms the actual work that this job needs to do.
  14878. Your subclass must implement this method, in which is does its work.
  14879. If the code in this method takes a significant time to run, it must repeatedly check
  14880. the shouldExit() method to see if something is trying to interrupt the job.
  14881. If shouldExit() ever returns true, the runJob() method must return immediately.
  14882. If this method returns jobHasFinished, then the job will be removed from the pool
  14883. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  14884. pool and will get a chance to run again as soon as a thread is free.
  14885. @see shouldExit()
  14886. */
  14887. virtual JobStatus runJob() = 0;
  14888. /** Returns true if this job is currently running its runJob() method. */
  14889. bool isRunning() const { return isActive; }
  14890. /** Returns true if something is trying to interrupt this job and make it stop.
  14891. Your runJob() method must call this whenever it gets a chance, and if it ever
  14892. returns true, the runJob() method must return immediately.
  14893. @see signalJobShouldExit()
  14894. */
  14895. bool shouldExit() const { return shouldStop; }
  14896. /** Calling this will cause the shouldExit() method to return true, and the job
  14897. should (if it's been implemented correctly) stop as soon as possible.
  14898. @see shouldExit()
  14899. */
  14900. void signalJobShouldExit();
  14901. private:
  14902. friend class ThreadPool;
  14903. friend class ThreadPoolThread;
  14904. String jobName;
  14905. ThreadPool* pool;
  14906. bool shouldStop, isActive, shouldBeDeleted;
  14907. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  14908. };
  14909. /**
  14910. A set of threads that will run a list of jobs.
  14911. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  14912. will be called by the next pooled thread that becomes free.
  14913. @see ThreadPoolJob, Thread
  14914. */
  14915. class JUCE_API ThreadPool
  14916. {
  14917. public:
  14918. /** Creates a thread pool.
  14919. Once you've created a pool, you can give it some things to do with the addJob()
  14920. method.
  14921. @param numberOfThreads the maximum number of actual threads to run.
  14922. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  14923. until there are some jobs to run. If false, then
  14924. all the threads will be fired-up immediately so that
  14925. they're ready for action
  14926. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  14927. inactive for this length of time, they will automatically
  14928. be stopped until more jobs come along and they're needed
  14929. */
  14930. ThreadPool (int numberOfThreads,
  14931. bool startThreadsOnlyWhenNeeded = true,
  14932. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  14933. /** Destructor.
  14934. This will attempt to remove all the jobs before deleting, but if you want to
  14935. specify a timeout, you should call removeAllJobs() explicitly before deleting
  14936. the pool.
  14937. */
  14938. ~ThreadPool();
  14939. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  14940. for some kind of operation.
  14941. @see ThreadPool::removeAllJobs
  14942. */
  14943. class JUCE_API JobSelector
  14944. {
  14945. public:
  14946. virtual ~JobSelector() {}
  14947. /** Should return true if the specified thread matches your criteria for whatever
  14948. operation that this object is being used for.
  14949. Any implementation of this method must be extremely fast and thread-safe!
  14950. */
  14951. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  14952. };
  14953. /** Adds a job to the queue.
  14954. Once a job has been added, then the next time a thread is free, it will run
  14955. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  14956. runJob() method, the pool will either remove the job from the pool or add it to
  14957. the back of the queue to be run again.
  14958. */
  14959. void addJob (ThreadPoolJob* job);
  14960. /** Tries to remove a job from the pool.
  14961. If the job isn't yet running, this will simply remove it. If it is running, it
  14962. will wait for it to finish.
  14963. If the timeout period expires before the job finishes running, then the job will be
  14964. left in the pool and this will return false. It returns true if the job is sucessfully
  14965. stopped and removed.
  14966. @param job the job to remove
  14967. @param interruptIfRunning if true, then if the job is currently busy, its
  14968. ThreadPoolJob::signalJobShouldExit() method will be called to try
  14969. to interrupt it. If false, then if the job will be allowed to run
  14970. until it stops normally (or the timeout expires)
  14971. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  14972. before giving up and returning false
  14973. */
  14974. bool removeJob (ThreadPoolJob* job,
  14975. bool interruptIfRunning,
  14976. int timeOutMilliseconds);
  14977. /** Tries to remove all jobs from the pool.
  14978. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  14979. methods called to try to interrupt them
  14980. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  14981. before giving up and returning false
  14982. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  14983. they will simply be removed from the pool. Jobs that are already running when
  14984. this method is called can choose whether they should be deleted by
  14985. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  14986. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  14987. jobs should be removed. If it is zero, all jobs are removed
  14988. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  14989. expires while waiting for one or more jobs to stop
  14990. */
  14991. bool removeAllJobs (bool interruptRunningJobs,
  14992. int timeOutMilliseconds,
  14993. bool deleteInactiveJobs = false,
  14994. JobSelector* selectedJobsToRemove = 0);
  14995. /** Returns the number of jobs currently running or queued.
  14996. */
  14997. int getNumJobs() const;
  14998. /** Returns one of the jobs in the queue.
  14999. Note that this can be a very volatile list as jobs might be continuously getting shifted
  15000. around in the list, and this method may return 0 if the index is currently out-of-range.
  15001. */
  15002. ThreadPoolJob* getJob (int index) const;
  15003. /** Returns true if the given job is currently queued or running.
  15004. @see isJobRunning()
  15005. */
  15006. bool contains (const ThreadPoolJob* job) const;
  15007. /** Returns true if the given job is currently being run by a thread.
  15008. */
  15009. bool isJobRunning (const ThreadPoolJob* job) const;
  15010. /** Waits until a job has finished running and has been removed from the pool.
  15011. This will wait until the job is no longer in the pool - i.e. until its
  15012. runJob() method returns ThreadPoolJob::jobHasFinished.
  15013. If the timeout period expires before the job finishes, this will return false;
  15014. it returns true if the job has finished successfully.
  15015. */
  15016. bool waitForJobToFinish (const ThreadPoolJob* job,
  15017. int timeOutMilliseconds) const;
  15018. /** Returns a list of the names of all the jobs currently running or queued.
  15019. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  15020. */
  15021. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  15022. /** Changes the priority of all the threads.
  15023. This will call Thread::setPriority() for each thread in the pool.
  15024. May return false if for some reason the priority can't be changed.
  15025. */
  15026. bool setThreadPriorities (int newPriority);
  15027. private:
  15028. const int threadStopTimeout;
  15029. int priority;
  15030. class ThreadPoolThread;
  15031. friend class OwnedArray <ThreadPoolThread>;
  15032. OwnedArray <ThreadPoolThread> threads;
  15033. Array <ThreadPoolJob*> jobs;
  15034. CriticalSection lock;
  15035. uint32 lastJobEndTime;
  15036. WaitableEvent jobFinishedSignal;
  15037. friend class ThreadPoolThread;
  15038. bool runNextJob();
  15039. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  15040. };
  15041. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  15042. /*** End of inlined file: juce_ThreadPool.h ***/
  15043. #endif
  15044. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  15045. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  15046. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  15047. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  15048. /**
  15049. Used by the TimeSliceThread class.
  15050. To register your class with a TimeSliceThread, derive from this class and
  15051. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  15052. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  15053. deleting your client!
  15054. @see TimeSliceThread
  15055. */
  15056. class JUCE_API TimeSliceClient
  15057. {
  15058. public:
  15059. /** Destructor. */
  15060. virtual ~TimeSliceClient() {}
  15061. /** Called back by a TimeSliceThread.
  15062. When you register this class with it, a TimeSliceThread will repeatedly call
  15063. this method.
  15064. The implementation of this method should use its time-slice to do something that's
  15065. quick - never block for longer than absolutely necessary.
  15066. @returns Your method should return true if it needs more time, or false if it's
  15067. not too busy and doesn't need calling back urgently. If all the thread's
  15068. clients indicate that they're not busy, then it'll save CPU by sleeping for
  15069. up to half a second in between callbacks. You can force the TimeSliceThread
  15070. to wake up and poll again immediately by calling its notify() method.
  15071. */
  15072. virtual bool useTimeSlice() = 0;
  15073. };
  15074. /**
  15075. A thread that keeps a list of clients, and calls each one in turn, giving them
  15076. all a chance to run some sort of short task.
  15077. @see TimeSliceClient, Thread
  15078. */
  15079. class JUCE_API TimeSliceThread : public Thread
  15080. {
  15081. public:
  15082. /**
  15083. Creates a TimeSliceThread.
  15084. When first created, the thread is not running. Use the startThread()
  15085. method to start it.
  15086. */
  15087. explicit TimeSliceThread (const String& threadName);
  15088. /** Destructor.
  15089. Deleting a Thread object that is running will only give the thread a
  15090. brief opportunity to stop itself cleanly, so it's recommended that you
  15091. should always call stopThread() with a decent timeout before deleting,
  15092. to avoid the thread being forcibly killed (which is a Bad Thing).
  15093. */
  15094. ~TimeSliceThread();
  15095. /** Adds a client to the list.
  15096. The client's callbacks will start immediately (possibly before the method
  15097. has returned).
  15098. */
  15099. void addTimeSliceClient (TimeSliceClient* client);
  15100. /** Removes a client from the list.
  15101. This method will make sure that all callbacks to the client have completely
  15102. finished before the method returns.
  15103. */
  15104. void removeTimeSliceClient (TimeSliceClient* client);
  15105. /** Returns the number of registered clients. */
  15106. int getNumClients() const;
  15107. /** Returns one of the registered clients. */
  15108. TimeSliceClient* getClient (int index) const;
  15109. /** @internal */
  15110. void run();
  15111. private:
  15112. CriticalSection callbackLock, listLock;
  15113. Array <TimeSliceClient*> clients;
  15114. int index;
  15115. TimeSliceClient* clientBeingCalled;
  15116. bool clientsChanged;
  15117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  15118. };
  15119. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  15120. /*** End of inlined file: juce_TimeSliceThread.h ***/
  15121. #endif
  15122. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  15123. #endif
  15124. #endif
  15125. /*** End of inlined file: juce_core_includes.h ***/
  15126. // if you're compiling a command-line app, you might want to just include the core headers,
  15127. // so you can set this macro before including juce.h
  15128. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  15129. /*** Start of inlined file: juce_app_includes.h ***/
  15130. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  15131. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  15132. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  15133. /*** Start of inlined file: juce_Application.h ***/
  15134. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  15135. #define __JUCE_APPLICATION_JUCEHEADER__
  15136. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  15137. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  15138. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  15139. /*** Start of inlined file: juce_Component.h ***/
  15140. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  15141. #define __JUCE_COMPONENT_JUCEHEADER__
  15142. /*** Start of inlined file: juce_MouseCursor.h ***/
  15143. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  15144. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  15145. class Image;
  15146. class ComponentPeer;
  15147. class Component;
  15148. /**
  15149. Represents a mouse cursor image.
  15150. This object can either be used to represent one of the standard mouse
  15151. cursor shapes, or a custom one generated from an image.
  15152. */
  15153. class JUCE_API MouseCursor
  15154. {
  15155. public:
  15156. /** The set of available standard mouse cursors. */
  15157. enum StandardCursorType
  15158. {
  15159. NoCursor = 0, /**< An invisible cursor. */
  15160. NormalCursor, /**< The stardard arrow cursor. */
  15161. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  15162. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  15163. CrosshairCursor, /**< A pair of crosshairs. */
  15164. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  15165. that you're dragging a copy of something. */
  15166. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  15167. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  15168. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  15169. UpDownResizeCursor, /**< an arrow pointing up and down. */
  15170. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  15171. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  15172. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  15173. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  15174. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  15175. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  15176. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  15177. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  15178. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  15179. };
  15180. /** Creates the standard arrow cursor. */
  15181. MouseCursor();
  15182. /** Creates one of the standard mouse cursor */
  15183. MouseCursor (StandardCursorType type);
  15184. /** Creates a custom cursor from an image.
  15185. @param image the image to use for the cursor - if this is bigger than the
  15186. system can manage, it might get scaled down first, and might
  15187. also have to be turned to black-and-white if it can't do colour
  15188. cursors.
  15189. @param hotSpotX the x position of the cursor's hotspot within the image
  15190. @param hotSpotY the y position of the cursor's hotspot within the image
  15191. */
  15192. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  15193. /** Creates a copy of another cursor object. */
  15194. MouseCursor (const MouseCursor& other);
  15195. /** Copies this cursor from another object. */
  15196. MouseCursor& operator= (const MouseCursor& other);
  15197. /** Destructor. */
  15198. ~MouseCursor();
  15199. /** Checks whether two mouse cursors are the same.
  15200. For custom cursors, two cursors created from the same image won't be
  15201. recognised as the same, only MouseCursor objects that have been
  15202. copied from the same object.
  15203. */
  15204. bool operator== (const MouseCursor& other) const throw();
  15205. /** Checks whether two mouse cursors are the same.
  15206. For custom cursors, two cursors created from the same image won't be
  15207. recognised as the same, only MouseCursor objects that have been
  15208. copied from the same object.
  15209. */
  15210. bool operator!= (const MouseCursor& other) const throw();
  15211. /** Makes the system show its default 'busy' cursor.
  15212. This will turn the system cursor to an hourglass or spinning beachball
  15213. until the next time the mouse is moved, or hideWaitCursor() is called.
  15214. This is handy if the message loop is about to block for a couple of
  15215. seconds while busy and you want to give the user feedback about this.
  15216. @see MessageManager::setTimeBeforeShowingWaitCursor
  15217. */
  15218. static void showWaitCursor();
  15219. /** If showWaitCursor has been called, this will return the mouse to its
  15220. normal state.
  15221. This will look at what component is under the mouse, and update the
  15222. cursor to be the correct one for that component.
  15223. @see showWaitCursor
  15224. */
  15225. static void hideWaitCursor();
  15226. private:
  15227. class SharedCursorHandle;
  15228. friend class SharedCursorHandle;
  15229. SharedCursorHandle* cursorHandle;
  15230. friend class MouseInputSourceInternal;
  15231. void showInWindow (ComponentPeer* window) const;
  15232. void showInAllWindows() const;
  15233. void* getHandle() const throw();
  15234. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  15235. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  15236. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  15237. JUCE_LEAK_DETECTOR (MouseCursor);
  15238. };
  15239. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  15240. /*** End of inlined file: juce_MouseCursor.h ***/
  15241. /*** Start of inlined file: juce_MouseListener.h ***/
  15242. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  15243. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  15244. class MouseEvent;
  15245. /**
  15246. A MouseListener can be registered with a component to receive callbacks
  15247. about mouse events that happen to that component.
  15248. @see Component::addMouseListener, Component::removeMouseListener
  15249. */
  15250. class JUCE_API MouseListener
  15251. {
  15252. public:
  15253. /** Destructor. */
  15254. virtual ~MouseListener() {}
  15255. /** Called when the mouse moves inside a component.
  15256. If the mouse button isn't pressed and the mouse moves over a component,
  15257. this will be called to let the component react to this.
  15258. A component will always get a mouseEnter callback before a mouseMove.
  15259. @param e details about the position and status of the mouse event, including
  15260. the source component in which it occurred
  15261. @see mouseEnter, mouseExit, mouseDrag, contains
  15262. */
  15263. virtual void mouseMove (const MouseEvent& e);
  15264. /** Called when the mouse first enters a component.
  15265. If the mouse button isn't pressed and the mouse moves into a component,
  15266. this will be called to let the component react to this.
  15267. When the mouse button is pressed and held down while being moved in
  15268. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  15269. mouseDrag messages are sent to the component that the mouse was originally
  15270. clicked on, until the button is released.
  15271. @param e details about the position and status of the mouse event, including
  15272. the source component in which it occurred
  15273. @see mouseExit, mouseDrag, mouseMove, contains
  15274. */
  15275. virtual void mouseEnter (const MouseEvent& e);
  15276. /** Called when the mouse moves out of a component.
  15277. This will be called when the mouse moves off the edge of this
  15278. component.
  15279. If the mouse button was pressed, and it was then dragged off the
  15280. edge of the component and released, then this callback will happen
  15281. when the button is released, after the mouseUp callback.
  15282. @param e details about the position and status of the mouse event, including
  15283. the source component in which it occurred
  15284. @see mouseEnter, mouseDrag, mouseMove, contains
  15285. */
  15286. virtual void mouseExit (const MouseEvent& e);
  15287. /** Called when a mouse button is pressed.
  15288. The MouseEvent object passed in contains lots of methods for finding out
  15289. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  15290. were held down at the time.
  15291. Once a button is held down, the mouseDrag method will be called when the
  15292. mouse moves, until the button is released.
  15293. @param e details about the position and status of the mouse event, including
  15294. the source component in which it occurred
  15295. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  15296. */
  15297. virtual void mouseDown (const MouseEvent& e);
  15298. /** Called when the mouse is moved while a button is held down.
  15299. When a mouse button is pressed inside a component, that component
  15300. receives mouseDrag callbacks each time the mouse moves, even if the
  15301. mouse strays outside the component's bounds.
  15302. @param e details about the position and status of the mouse event, including
  15303. the source component in which it occurred
  15304. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  15305. */
  15306. virtual void mouseDrag (const MouseEvent& e);
  15307. /** Called when a mouse button is released.
  15308. A mouseUp callback is sent to the component in which a button was pressed
  15309. even if the mouse is actually over a different component when the
  15310. button is released.
  15311. The MouseEvent object passed in contains lots of methods for finding out
  15312. which buttons were down just before they were released.
  15313. @param e details about the position and status of the mouse event, including
  15314. the source component in which it occurred
  15315. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  15316. */
  15317. virtual void mouseUp (const MouseEvent& e);
  15318. /** Called when a mouse button has been double-clicked on a component.
  15319. The MouseEvent object passed in contains lots of methods for finding out
  15320. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  15321. were held down at the time.
  15322. @param e details about the position and status of the mouse event, including
  15323. the source component in which it occurred
  15324. @see mouseDown, mouseUp
  15325. */
  15326. virtual void mouseDoubleClick (const MouseEvent& e);
  15327. /** Called when the mouse-wheel is moved.
  15328. This callback is sent to the component that the mouse is over when the
  15329. wheel is moved.
  15330. If not overridden, the component will forward this message to its parent, so
  15331. that parent components can collect mouse-wheel messages that happen to
  15332. child components which aren't interested in them.
  15333. @param e details about the position and status of the mouse event, including
  15334. the source component in which it occurred
  15335. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  15336. value means the wheel has been pushed to the right, negative means it
  15337. was pushed to the left
  15338. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  15339. value means the wheel has been pushed upwards, negative means it
  15340. was pushed downwards
  15341. */
  15342. virtual void mouseWheelMove (const MouseEvent& e,
  15343. float wheelIncrementX,
  15344. float wheelIncrementY);
  15345. };
  15346. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  15347. /*** End of inlined file: juce_MouseListener.h ***/
  15348. /*** Start of inlined file: juce_MouseEvent.h ***/
  15349. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  15350. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  15351. class Component;
  15352. class MouseInputSource;
  15353. /*** Start of inlined file: juce_ModifierKeys.h ***/
  15354. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  15355. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  15356. /**
  15357. Represents the state of the mouse buttons and modifier keys.
  15358. This is used both by mouse events and by KeyPress objects to describe
  15359. the state of keys such as shift, control, alt, etc.
  15360. @see KeyPress, MouseEvent::mods
  15361. */
  15362. class JUCE_API ModifierKeys
  15363. {
  15364. public:
  15365. /** Creates a ModifierKeys object from a raw set of flags.
  15366. @param flags to represent the keys that are down
  15367. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  15368. rightButtonModifier, commandModifier, popupMenuClickModifier
  15369. */
  15370. ModifierKeys (int flags = 0) throw();
  15371. /** Creates a copy of another object. */
  15372. ModifierKeys (const ModifierKeys& other) throw();
  15373. /** Copies this object from another one. */
  15374. ModifierKeys& operator= (const ModifierKeys& other) throw();
  15375. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  15376. This is a platform-agnostic way of checking for the operating system's
  15377. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  15378. Windows/Linux, it's actually checking for the CTRL key.
  15379. */
  15380. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  15381. /** Checks whether the user is trying to launch a pop-up menu.
  15382. This checks for platform-specific modifiers that might indicate that the user
  15383. is following the operating system's normal method of showing a pop-up menu.
  15384. So on Windows/Linux, this method is really testing for a right-click.
  15385. On the Mac, it tests for either the CTRL key being down, or a right-click.
  15386. */
  15387. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  15388. /** Checks whether the flag is set for the left mouse-button. */
  15389. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  15390. /** Checks whether the flag is set for the right mouse-button.
  15391. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  15392. this is platform-independent (and makes your code more explanatory too).
  15393. */
  15394. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  15395. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  15396. /** Tests for any of the mouse-button flags. */
  15397. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  15398. /** Tests for any of the modifier key flags. */
  15399. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  15400. /** Checks whether the shift key's flag is set. */
  15401. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  15402. /** Checks whether the CTRL key's flag is set.
  15403. Remember that it's better to use the platform-agnostic routines to test for command-key and
  15404. popup-menu modifiers.
  15405. @see isCommandDown, isPopupMenu
  15406. */
  15407. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  15408. /** Checks whether the shift key's flag is set. */
  15409. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  15410. /** Flags that represent the different keys. */
  15411. enum Flags
  15412. {
  15413. /** Shift key flag. */
  15414. shiftModifier = 1,
  15415. /** CTRL key flag. */
  15416. ctrlModifier = 2,
  15417. /** ALT key flag. */
  15418. altModifier = 4,
  15419. /** Left mouse button flag. */
  15420. leftButtonModifier = 16,
  15421. /** Right mouse button flag. */
  15422. rightButtonModifier = 32,
  15423. /** Middle mouse button flag. */
  15424. middleButtonModifier = 64,
  15425. #if JUCE_MAC
  15426. /** Command key flag - on windows this is the same as the CTRL key flag. */
  15427. commandModifier = 8,
  15428. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  15429. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  15430. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  15431. #else
  15432. /** Command key flag - on windows this is the same as the CTRL key flag. */
  15433. commandModifier = ctrlModifier,
  15434. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  15435. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  15436. popupMenuClickModifier = rightButtonModifier,
  15437. #endif
  15438. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  15439. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  15440. /** Represents a combination of all the mouse buttons at once. */
  15441. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  15442. };
  15443. /** Returns a copy of only the mouse-button flags */
  15444. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  15445. /** Returns a copy of only the non-mouse flags */
  15446. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  15447. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  15448. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  15449. /** Returns the raw flags for direct testing. */
  15450. inline int getRawFlags() const throw() { return flags; }
  15451. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  15452. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  15453. /** Tests a combination of flags and returns true if any of them are set. */
  15454. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  15455. /** Returns the total number of mouse buttons that are down. */
  15456. int getNumMouseButtonsDown() const throw();
  15457. /** Creates a ModifierKeys object to represent the last-known state of the
  15458. keyboard and mouse buttons.
  15459. @see getCurrentModifiersRealtime
  15460. */
  15461. static const ModifierKeys getCurrentModifiers() throw();
  15462. /** Creates a ModifierKeys object to represent the current state of the
  15463. keyboard and mouse buttons.
  15464. This isn't often needed and isn't recommended, but will actively check all the
  15465. mouse and key states rather than just returning their last-known state like
  15466. getCurrentModifiers() does.
  15467. This is only needed in special circumstances for up-to-date modifier information
  15468. at times when the app's event loop isn't running normally.
  15469. Another reason to avoid this method is that it's not stateless, and calling it may
  15470. update the value returned by getCurrentModifiers(), which could cause subtle changes
  15471. in the behaviour of some components.
  15472. */
  15473. static const ModifierKeys getCurrentModifiersRealtime() throw();
  15474. private:
  15475. int flags;
  15476. static ModifierKeys currentModifiers;
  15477. friend class ComponentPeer;
  15478. friend class MouseInputSource;
  15479. friend class MouseInputSourceInternal;
  15480. static void updateCurrentModifiers() throw();
  15481. };
  15482. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  15483. /*** End of inlined file: juce_ModifierKeys.h ***/
  15484. /*** Start of inlined file: juce_Point.h ***/
  15485. #ifndef __JUCE_POINT_JUCEHEADER__
  15486. #define __JUCE_POINT_JUCEHEADER__
  15487. /*** Start of inlined file: juce_AffineTransform.h ***/
  15488. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  15489. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  15490. /**
  15491. Represents a 2D affine-transformation matrix.
  15492. An affine transformation is a transformation such as a rotation, scale, shear,
  15493. resize or translation.
  15494. These are used for various 2D transformation tasks, e.g. with Path objects.
  15495. @see Path, Point, Line
  15496. */
  15497. class JUCE_API AffineTransform
  15498. {
  15499. public:
  15500. /** Creates an identity transform. */
  15501. AffineTransform() throw();
  15502. /** Creates a copy of another transform. */
  15503. AffineTransform (const AffineTransform& other) throw();
  15504. /** Creates a transform from a set of raw matrix values.
  15505. The resulting matrix is:
  15506. (mat00 mat01 mat02)
  15507. (mat10 mat11 mat12)
  15508. ( 0 0 1 )
  15509. */
  15510. AffineTransform (float mat00, float mat01, float mat02,
  15511. float mat10, float mat11, float mat12) throw();
  15512. /** Copies from another AffineTransform object */
  15513. AffineTransform& operator= (const AffineTransform& other) throw();
  15514. /** Compares two transforms. */
  15515. bool operator== (const AffineTransform& other) const throw();
  15516. /** Compares two transforms. */
  15517. bool operator!= (const AffineTransform& other) const throw();
  15518. /** A ready-to-use identity transform, which you can use to append other
  15519. transformations to.
  15520. e.g. @code
  15521. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  15522. .scaled (2.0f);
  15523. @endcode
  15524. */
  15525. static const AffineTransform identity;
  15526. /** Transforms a 2D co-ordinate using this matrix. */
  15527. template <typename ValueType>
  15528. void transformPoint (ValueType& x, ValueType& y) const throw()
  15529. {
  15530. const ValueType oldX = x;
  15531. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  15532. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  15533. }
  15534. /** Transforms two 2D co-ordinates using this matrix.
  15535. This is just a shortcut for calling transformPoint() on each of these pairs of
  15536. coordinates in turn. (And putting all the calculations into one function hopefully
  15537. also gives the compiler a bit more scope for pipelining it).
  15538. */
  15539. template <typename ValueType>
  15540. void transformPoints (ValueType& x1, ValueType& y1,
  15541. ValueType& x2, ValueType& y2) const throw()
  15542. {
  15543. const ValueType oldX1 = x1, oldX2 = x2;
  15544. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  15545. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  15546. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  15547. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  15548. }
  15549. /** Transforms three 2D co-ordinates using this matrix.
  15550. This is just a shortcut for calling transformPoint() on each of these pairs of
  15551. coordinates in turn. (And putting all the calculations into one function hopefully
  15552. also gives the compiler a bit more scope for pipelining it).
  15553. */
  15554. template <typename ValueType>
  15555. void transformPoints (ValueType& x1, ValueType& y1,
  15556. ValueType& x2, ValueType& y2,
  15557. ValueType& x3, ValueType& y3) const throw()
  15558. {
  15559. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  15560. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  15561. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  15562. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  15563. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  15564. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  15565. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  15566. }
  15567. /** Returns a new transform which is the same as this one followed by a translation. */
  15568. const AffineTransform translated (float deltaX,
  15569. float deltaY) const throw();
  15570. /** Returns a new transform which is a translation. */
  15571. static const AffineTransform translation (float deltaX,
  15572. float deltaY) throw();
  15573. /** Returns a transform which is the same as this one followed by a rotation.
  15574. The rotation is specified by a number of radians to rotate clockwise, centred around
  15575. the origin (0, 0).
  15576. */
  15577. const AffineTransform rotated (float angleInRadians) const throw();
  15578. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  15579. The rotation is specified by a number of radians to rotate clockwise, centred around
  15580. the co-ordinates passed in.
  15581. */
  15582. const AffineTransform rotated (float angleInRadians,
  15583. float pivotX,
  15584. float pivotY) const throw();
  15585. /** Returns a new transform which is a rotation about (0, 0). */
  15586. static const AffineTransform rotation (float angleInRadians) throw();
  15587. /** Returns a new transform which is a rotation about a given point. */
  15588. static const AffineTransform rotation (float angleInRadians,
  15589. float pivotX,
  15590. float pivotY) throw();
  15591. /** Returns a transform which is the same as this one followed by a re-scaling.
  15592. The scaling is centred around the origin (0, 0).
  15593. */
  15594. const AffineTransform scaled (float factorX,
  15595. float factorY) const throw();
  15596. /** Returns a transform which is the same as this one followed by a re-scaling.
  15597. The scaling is centred around the origin provided.
  15598. */
  15599. const AffineTransform scaled (float factorX, float factorY,
  15600. float pivotX, float pivotY) const throw();
  15601. /** Returns a new transform which is a re-scale about the origin. */
  15602. static const AffineTransform scale (float factorX,
  15603. float factorY) throw();
  15604. /** Returns a new transform which is a re-scale centred around the point provided. */
  15605. static const AffineTransform scale (float factorX, float factorY,
  15606. float pivotX, float pivotY) throw();
  15607. /** Returns a transform which is the same as this one followed by a shear.
  15608. The shear is centred around the origin (0, 0).
  15609. */
  15610. const AffineTransform sheared (float shearX, float shearY) const throw();
  15611. /** Returns a shear transform, centred around the origin (0, 0). */
  15612. static const AffineTransform shear (float shearX, float shearY) throw();
  15613. /** Returns a matrix which is the inverse operation of this one.
  15614. Some matrices don't have an inverse - in this case, the method will just return
  15615. an identity transform.
  15616. */
  15617. const AffineTransform inverted() const throw();
  15618. /** Returns the transform that will map three known points onto three coordinates
  15619. that are supplied.
  15620. This returns the transform that will transform (0, 0) into (x00, y00),
  15621. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  15622. */
  15623. static const AffineTransform fromTargetPoints (float x00, float y00,
  15624. float x10, float y10,
  15625. float x01, float y01) throw();
  15626. /** Returns the transform that will map three specified points onto three target points.
  15627. */
  15628. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  15629. float sourceX2, float sourceY2, float targetX2, float targetY2,
  15630. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  15631. /** Returns the result of concatenating another transformation after this one. */
  15632. const AffineTransform followedBy (const AffineTransform& other) const throw();
  15633. /** Returns true if this transform has no effect on points. */
  15634. bool isIdentity() const throw();
  15635. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  15636. bool isSingularity() const throw();
  15637. /** Returns true if the transform only translates, and doesn't scale or rotate the
  15638. points. */
  15639. bool isOnlyTranslation() const throw();
  15640. /** If this transform is only a translation, this returns the X offset.
  15641. @see isOnlyTranslation
  15642. */
  15643. float getTranslationX() const throw() { return mat02; }
  15644. /** If this transform is only a translation, this returns the X offset.
  15645. @see isOnlyTranslation
  15646. */
  15647. float getTranslationY() const throw() { return mat12; }
  15648. /** Returns the approximate scale factor by which lengths will be transformed.
  15649. Obviously a length may be scaled by entirely different amounts depending on its
  15650. direction, so this is only appropriate as a rough guide.
  15651. */
  15652. float getScaleFactor() const throw();
  15653. /* The transform matrix is:
  15654. (mat00 mat01 mat02)
  15655. (mat10 mat11 mat12)
  15656. ( 0 0 1 )
  15657. */
  15658. float mat00, mat01, mat02;
  15659. float mat10, mat11, mat12;
  15660. private:
  15661. JUCE_LEAK_DETECTOR (AffineTransform);
  15662. };
  15663. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  15664. /*** End of inlined file: juce_AffineTransform.h ***/
  15665. /**
  15666. A pair of (x, y) co-ordinates.
  15667. The ValueType template should be a primitive type such as int, float, double,
  15668. rather than a class.
  15669. @see Line, Path, AffineTransform
  15670. */
  15671. template <typename ValueType>
  15672. class Point
  15673. {
  15674. public:
  15675. /** Creates a point with co-ordinates (0, 0). */
  15676. Point() throw() : x (0), y (0) {}
  15677. /** Creates a copy of another point. */
  15678. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  15679. /** Creates a point from an (x, y) position. */
  15680. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  15681. /** Destructor. */
  15682. ~Point() throw() {}
  15683. /** Copies this point from another one. */
  15684. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  15685. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  15686. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  15687. /** Returns true if the point is (0, 0). */
  15688. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  15689. /** Returns the point's x co-ordinate. */
  15690. inline ValueType getX() const throw() { return x; }
  15691. /** Returns the point's y co-ordinate. */
  15692. inline ValueType getY() const throw() { return y; }
  15693. /** Sets the point's x co-ordinate. */
  15694. inline void setX (const ValueType newX) throw() { x = newX; }
  15695. /** Sets the point's y co-ordinate. */
  15696. inline void setY (const ValueType newY) throw() { y = newY; }
  15697. /** Returns a point which has the same Y position as this one, but a new X. */
  15698. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  15699. /** Returns a point which has the same X position as this one, but a new Y. */
  15700. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  15701. /** Changes the point's x and y co-ordinates. */
  15702. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  15703. /** Adds a pair of co-ordinates to this value. */
  15704. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  15705. /** Returns a point with a given offset from this one. */
  15706. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  15707. /** Adds two points together. */
  15708. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  15709. /** Adds another point's co-ordinates to this one. */
  15710. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  15711. /** Subtracts one points from another. */
  15712. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  15713. /** Subtracts another point's co-ordinates to this one. */
  15714. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  15715. /** Returns a point whose coordinates are multiplied by a given value. */
  15716. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  15717. /** Multiplies the point's co-ordinates by a value. */
  15718. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  15719. /** Returns a point whose coordinates are divided by a given value. */
  15720. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  15721. /** Divides the point's co-ordinates by a value. */
  15722. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  15723. /** Returns the inverse of this point. */
  15724. const Point operator-() const throw() { return Point (-x, -y); }
  15725. /** Returns the straight-line distance between this point and another one. */
  15726. ValueType getDistanceFromOrigin() const throw() { return juce_hypot (x, y); }
  15727. /** Returns the straight-line distance between this point and another one. */
  15728. ValueType getDistanceFrom (const Point& other) const throw() { return juce_hypot (x - other.x, y - other.y); }
  15729. /** Returns the angle from this point to another one.
  15730. The return value is the number of radians clockwise from the 3 o'clock direction,
  15731. where this point is the centre and the other point is on the circumference.
  15732. */
  15733. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  15734. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  15735. @param radius the radius of the circle.
  15736. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  15737. */
  15738. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  15739. y - radius * std::cos (angle)); }
  15740. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  15741. @param radiusX the horizontal radius of the circle.
  15742. @param radiusY the vertical radius of the circle.
  15743. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  15744. */
  15745. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  15746. y - radiusY * std::cos (angle)); }
  15747. /** Uses a transform to change the point's co-ordinates.
  15748. This will only compile if ValueType = float!
  15749. @see AffineTransform::transformPoint
  15750. */
  15751. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  15752. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  15753. const Point transformedBy (const AffineTransform& transform) const throw() { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  15754. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  15755. /** Casts this point to a Point<float> object. */
  15756. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  15757. /** Casts this point to a Point<int> object. */
  15758. const Point<int> toInt() const throw() { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  15759. /** Returns the point as a string in the form "x, y". */
  15760. const String toString() const { return String (x) + ", " + String (y); }
  15761. private:
  15762. ValueType x, y;
  15763. };
  15764. #endif // __JUCE_POINT_JUCEHEADER__
  15765. /*** End of inlined file: juce_Point.h ***/
  15766. /**
  15767. Contains position and status information about a mouse event.
  15768. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  15769. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  15770. */
  15771. class JUCE_API MouseEvent
  15772. {
  15773. public:
  15774. /** Creates a MouseEvent.
  15775. Normally an application will never need to use this.
  15776. @param source the source that's invoking the event
  15777. @param position the position of the mouse, relative to the component that is passed-in
  15778. @param modifiers the key modifiers at the time of the event
  15779. @param eventComponent the component that the mouse event applies to
  15780. @param originator the component that originally received the event
  15781. @param eventTime the time the event happened
  15782. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  15783. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  15784. the same as the current mouse-x position.
  15785. @param mouseDownTime the time at which the corresponding mouse-down event happened
  15786. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  15787. the same as the current mouse-event time.
  15788. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  15789. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  15790. */
  15791. MouseEvent (MouseInputSource& source,
  15792. const Point<int>& position,
  15793. const ModifierKeys& modifiers,
  15794. Component* eventComponent,
  15795. Component* originator,
  15796. const Time& eventTime,
  15797. const Point<int> mouseDownPos,
  15798. const Time& mouseDownTime,
  15799. int numberOfClicks,
  15800. bool mouseWasDragged) throw();
  15801. /** Destructor. */
  15802. ~MouseEvent() throw();
  15803. /** The x-position of the mouse when the event occurred.
  15804. This value is relative to the top-left of the component to which the
  15805. event applies (as indicated by the MouseEvent::eventComponent field).
  15806. */
  15807. const int x;
  15808. /** The y-position of the mouse when the event occurred.
  15809. This value is relative to the top-left of the component to which the
  15810. event applies (as indicated by the MouseEvent::eventComponent field).
  15811. */
  15812. const int y;
  15813. /** The key modifiers associated with the event.
  15814. This will let you find out which mouse buttons were down, as well as which
  15815. modifier keys were held down.
  15816. When used for mouse-up events, this will indicate the state of the mouse buttons
  15817. just before they were released, so that you can tell which button they let go of.
  15818. */
  15819. const ModifierKeys mods;
  15820. /** The component that this event applies to.
  15821. This is usually the component that the mouse was over at the time, but for mouse-drag
  15822. events the mouse could actually be over a different component and the events are
  15823. still sent to the component that the button was originally pressed on.
  15824. The x and y member variables are relative to this component's position.
  15825. If you use getEventRelativeTo() to retarget this object to be relative to a different
  15826. component, this pointer will be updated, but originalComponent remains unchanged.
  15827. @see originalComponent
  15828. */
  15829. Component* const eventComponent;
  15830. /** The component that the event first occurred on.
  15831. If you use getEventRelativeTo() to retarget this object to be relative to a different
  15832. component, this value remains unchanged to indicate the first component that received it.
  15833. @see eventComponent
  15834. */
  15835. Component* const originalComponent;
  15836. /** The time that this mouse-event occurred.
  15837. */
  15838. const Time eventTime;
  15839. /** The source device that generated this event.
  15840. */
  15841. MouseInputSource& source;
  15842. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  15843. The co-ordinate is relative to the component specified in MouseEvent::component.
  15844. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  15845. */
  15846. int getMouseDownX() const throw();
  15847. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  15848. The co-ordinate is relative to the component specified in MouseEvent::component.
  15849. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  15850. */
  15851. int getMouseDownY() const throw();
  15852. /** Returns the co-ordinates of the last place that a mouse was pressed.
  15853. The co-ordinates are relative to the component specified in MouseEvent::component.
  15854. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  15855. */
  15856. const Point<int> getMouseDownPosition() const throw();
  15857. /** Returns the straight-line distance between where the mouse is now and where it
  15858. was the last time the button was pressed.
  15859. This is quite handy for things like deciding whether the user has moved far enough
  15860. for it to be considered a drag operation.
  15861. @see getDistanceFromDragStartX
  15862. */
  15863. int getDistanceFromDragStart() const throw();
  15864. /** Returns the difference between the mouse's current x postion and where it was
  15865. when the button was last pressed.
  15866. @see getDistanceFromDragStart
  15867. */
  15868. int getDistanceFromDragStartX() const throw();
  15869. /** Returns the difference between the mouse's current y postion and where it was
  15870. when the button was last pressed.
  15871. @see getDistanceFromDragStart
  15872. */
  15873. int getDistanceFromDragStartY() const throw();
  15874. /** Returns the difference between the mouse's current postion and where it was
  15875. when the button was last pressed.
  15876. @see getDistanceFromDragStart
  15877. */
  15878. const Point<int> getOffsetFromDragStart() const throw();
  15879. /** Returns true if the mouse has just been clicked.
  15880. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  15881. the user has dragged the mouse more than a few pixels from the place where the
  15882. mouse-down occurred.
  15883. Once they have dragged it far enough for this method to return false, it will continue
  15884. to return false until the mouse-up, even if they move the mouse back to the same
  15885. position where they originally pressed it. This means that it's very handy for
  15886. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  15887. callback to ignore any small movements they might make while clicking.
  15888. @returns true if the mouse wasn't dragged by more than a few pixels between
  15889. the last time the button was pressed and released.
  15890. */
  15891. bool mouseWasClicked() const throw();
  15892. /** For a click event, the number of times the mouse was clicked in succession.
  15893. So for example a double-click event will return 2, a triple-click 3, etc.
  15894. */
  15895. int getNumberOfClicks() const throw() { return numberOfClicks; }
  15896. /** Returns the time that the mouse button has been held down for.
  15897. If called from a mouseDrag or mouseUp callback, this will return the
  15898. number of milliseconds since the corresponding mouseDown event occurred.
  15899. If called in other contexts, e.g. a mouseMove, then the returned value
  15900. may be 0 or an undefined value.
  15901. */
  15902. int getLengthOfMousePress() const throw();
  15903. /** The position of the mouse when the event occurred.
  15904. This position is relative to the top-left of the component to which the
  15905. event applies (as indicated by the MouseEvent::eventComponent field).
  15906. */
  15907. const Point<int> getPosition() const throw();
  15908. /** Returns the mouse x position of this event, in global screen co-ordinates.
  15909. The co-ordinates are relative to the top-left of the main monitor.
  15910. @see getScreenPosition
  15911. */
  15912. int getScreenX() const;
  15913. /** Returns the mouse y position of this event, in global screen co-ordinates.
  15914. The co-ordinates are relative to the top-left of the main monitor.
  15915. @see getScreenPosition
  15916. */
  15917. int getScreenY() const;
  15918. /** Returns the mouse position of this event, in global screen co-ordinates.
  15919. The co-ordinates are relative to the top-left of the main monitor.
  15920. @see getMouseDownScreenPosition
  15921. */
  15922. const Point<int> getScreenPosition() const;
  15923. /** Returns the x co-ordinate at which the mouse button was last pressed.
  15924. The co-ordinates are relative to the top-left of the main monitor.
  15925. @see getMouseDownScreenPosition
  15926. */
  15927. int getMouseDownScreenX() const;
  15928. /** Returns the y co-ordinate at which the mouse button was last pressed.
  15929. The co-ordinates are relative to the top-left of the main monitor.
  15930. @see getMouseDownScreenPosition
  15931. */
  15932. int getMouseDownScreenY() const;
  15933. /** Returns the co-ordinates at which the mouse button was last pressed.
  15934. The co-ordinates are relative to the top-left of the main monitor.
  15935. @see getScreenPosition
  15936. */
  15937. const Point<int> getMouseDownScreenPosition() const;
  15938. /** Creates a version of this event that is relative to a different component.
  15939. The x and y positions of the event that is returned will have been
  15940. adjusted to be relative to the new component.
  15941. */
  15942. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  15943. /** Creates a copy of this event with a different position.
  15944. All other members of the event object are the same, but the x and y are
  15945. replaced with these new values.
  15946. */
  15947. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  15948. /** Changes the application-wide setting for the double-click time limit.
  15949. This is the maximum length of time between mouse-clicks for it to be
  15950. considered a double-click. It's used by the Component class.
  15951. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  15952. */
  15953. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  15954. /** Returns the application-wide setting for the double-click time limit.
  15955. This is the maximum length of time between mouse-clicks for it to be
  15956. considered a double-click. It's used by the Component class.
  15957. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  15958. */
  15959. static int getDoubleClickTimeout() throw();
  15960. private:
  15961. const Point<int> mouseDownPos;
  15962. const Time mouseDownTime;
  15963. const int numberOfClicks;
  15964. const bool wasMovedSinceMouseDown;
  15965. static int doubleClickTimeOutMs;
  15966. MouseEvent& operator= (const MouseEvent&);
  15967. JUCE_LEAK_DETECTOR (MouseEvent);
  15968. };
  15969. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  15970. /*** End of inlined file: juce_MouseEvent.h ***/
  15971. /*** Start of inlined file: juce_ComponentListener.h ***/
  15972. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  15973. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  15974. class Component;
  15975. /**
  15976. Gets informed about changes to a component's hierarchy or position.
  15977. To monitor a component for changes, register a subclass of ComponentListener
  15978. with the component using Component::addComponentListener().
  15979. Be sure to deregister listeners before you delete them!
  15980. @see Component::addComponentListener, Component::removeComponentListener
  15981. */
  15982. class JUCE_API ComponentListener
  15983. {
  15984. public:
  15985. /** Destructor. */
  15986. virtual ~ComponentListener() {}
  15987. /** Called when the component's position or size changes.
  15988. @param component the component that was moved or resized
  15989. @param wasMoved true if the component's top-left corner has just moved
  15990. @param wasResized true if the component's width or height has just changed
  15991. @see Component::setBounds, Component::resized, Component::moved
  15992. */
  15993. virtual void componentMovedOrResized (Component& component,
  15994. bool wasMoved,
  15995. bool wasResized);
  15996. /** Called when the component is brought to the top of the z-order.
  15997. @param component the component that was moved
  15998. @see Component::toFront, Component::broughtToFront
  15999. */
  16000. virtual void componentBroughtToFront (Component& component);
  16001. /** Called when the component is made visible or invisible.
  16002. @param component the component that changed
  16003. @see Component::setVisible
  16004. */
  16005. virtual void componentVisibilityChanged (Component& component);
  16006. /** Called when the component has children added or removed.
  16007. @param component the component whose children were changed
  16008. @see Component::childrenChanged, Component::addChildComponent,
  16009. Component::removeChildComponent
  16010. */
  16011. virtual void componentChildrenChanged (Component& component);
  16012. /** Called to indicate that the component's parents have changed.
  16013. When a component is added or removed from its parent, all of its children
  16014. will produce this notification (recursively - so all children of its
  16015. children will also be called as well).
  16016. @param component the component that this listener is registered with
  16017. @see Component::parentHierarchyChanged
  16018. */
  16019. virtual void componentParentHierarchyChanged (Component& component);
  16020. /** Called when the component's name is changed.
  16021. @see Component::setName, Component::getName
  16022. */
  16023. virtual void componentNameChanged (Component& component);
  16024. /** Called when the component is in the process of being deleted.
  16025. This callback is made from inside the destructor, so be very, very cautious
  16026. about what you do in here.
  16027. In particular, bear in mind that it's the Component base class's destructor that calls
  16028. this - so if the object that's being deleted is a subclass of Component, then the
  16029. subclass layers of the object will already have been destructed when it gets to this
  16030. point!
  16031. */
  16032. virtual void componentBeingDeleted (Component& component);
  16033. };
  16034. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  16035. /*** End of inlined file: juce_ComponentListener.h ***/
  16036. /*** Start of inlined file: juce_KeyListener.h ***/
  16037. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  16038. #define __JUCE_KEYLISTENER_JUCEHEADER__
  16039. /*** Start of inlined file: juce_KeyPress.h ***/
  16040. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  16041. #define __JUCE_KEYPRESS_JUCEHEADER__
  16042. /**
  16043. Represents a key press, including any modifier keys that are needed.
  16044. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  16045. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  16046. */
  16047. class JUCE_API KeyPress
  16048. {
  16049. public:
  16050. /** Creates an (invalid) KeyPress.
  16051. @see isValid
  16052. */
  16053. KeyPress() throw();
  16054. /** Creates a KeyPress for a key and some modifiers.
  16055. e.g.
  16056. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  16057. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  16058. @param keyCode a code that represents the key - this value must be
  16059. one of special constants listed in this class, or an
  16060. 8-bit character code such as a letter (case is ignored),
  16061. digit or a simple key like "," or ".". Note that this
  16062. isn't the same as the textCharacter parameter, so for example
  16063. a keyCode of 'a' and a shift-key modifier should have a
  16064. textCharacter value of 'A'.
  16065. @param modifiers the modifiers to associate with the keystroke
  16066. @param textCharacter the character that would be printed if someone typed
  16067. this keypress into a text editor. This value may be
  16068. null if the keypress is a non-printing character
  16069. @see getKeyCode, isKeyCode, getModifiers
  16070. */
  16071. KeyPress (int keyCode,
  16072. const ModifierKeys& modifiers,
  16073. juce_wchar textCharacter) throw();
  16074. /** Creates a keypress with a keyCode but no modifiers or text character.
  16075. */
  16076. KeyPress (int keyCode) throw();
  16077. /** Creates a copy of another KeyPress. */
  16078. KeyPress (const KeyPress& other) throw();
  16079. /** Copies this KeyPress from another one. */
  16080. KeyPress& operator= (const KeyPress& other) throw();
  16081. /** Compares two KeyPress objects. */
  16082. bool operator== (const KeyPress& other) const throw();
  16083. /** Compares two KeyPress objects. */
  16084. bool operator!= (const KeyPress& other) const throw();
  16085. /** Returns true if this is a valid KeyPress.
  16086. A null keypress can be created by the default constructor, in case it's
  16087. needed.
  16088. */
  16089. bool isValid() const throw() { return keyCode != 0; }
  16090. /** Returns the key code itself.
  16091. This will either be one of the special constants defined in this class,
  16092. or an 8-bit character code.
  16093. */
  16094. int getKeyCode() const throw() { return keyCode; }
  16095. /** Returns the key modifiers.
  16096. @see ModifierKeys
  16097. */
  16098. const ModifierKeys getModifiers() const throw() { return mods; }
  16099. /** Returns the character that is associated with this keypress.
  16100. This is the character that you'd expect to see printed if you press this
  16101. keypress in a text editor or similar component.
  16102. */
  16103. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  16104. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  16105. the modifiers.
  16106. The values for key codes can either be one of the special constants defined in
  16107. this class, or an 8-bit character code.
  16108. @see getKeyCode
  16109. */
  16110. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  16111. /** Converts a textual key description to a KeyPress.
  16112. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  16113. This isn't designed to cope with any kind of input, but should be given the
  16114. strings that are created by the getTextDescription() method.
  16115. If the string can't be parsed, the object returned will be invalid.
  16116. @see getTextDescription
  16117. */
  16118. static const KeyPress createFromDescription (const String& textVersion);
  16119. /** Creates a textual description of the key combination.
  16120. e.g. "CTRL + C" or "DELETE".
  16121. To store a keypress in a file, use this method, along with createFromDescription()
  16122. to retrieve it later.
  16123. */
  16124. const String getTextDescription() const;
  16125. /** Checks whether the user is currently holding down the keys that make up this
  16126. KeyPress.
  16127. Note that this will return false if any extra modifier keys are
  16128. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  16129. then it will be false.
  16130. */
  16131. bool isCurrentlyDown() const;
  16132. /** Checks whether a particular key is held down, irrespective of modifiers.
  16133. The values for key codes can either be one of the special constants defined in
  16134. this class, or an 8-bit character code.
  16135. */
  16136. static bool isKeyCurrentlyDown (int keyCode);
  16137. // Key codes
  16138. //
  16139. // Note that the actual values of these are platform-specific and may change
  16140. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  16141. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  16142. //
  16143. static const int spaceKey; /**< key-code for the space bar */
  16144. static const int escapeKey; /**< key-code for the escape key */
  16145. static const int returnKey; /**< key-code for the return key*/
  16146. static const int tabKey; /**< key-code for the tab key*/
  16147. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  16148. static const int backspaceKey; /**< key-code for the backspace key */
  16149. static const int insertKey; /**< key-code for the insert key */
  16150. static const int upKey; /**< key-code for the cursor-up key */
  16151. static const int downKey; /**< key-code for the cursor-down key */
  16152. static const int leftKey; /**< key-code for the cursor-left key */
  16153. static const int rightKey; /**< key-code for the cursor-right key */
  16154. static const int pageUpKey; /**< key-code for the page-up key */
  16155. static const int pageDownKey; /**< key-code for the page-down key */
  16156. static const int homeKey; /**< key-code for the home key */
  16157. static const int endKey; /**< key-code for the end key */
  16158. static const int F1Key; /**< key-code for the F1 key */
  16159. static const int F2Key; /**< key-code for the F2 key */
  16160. static const int F3Key; /**< key-code for the F3 key */
  16161. static const int F4Key; /**< key-code for the F4 key */
  16162. static const int F5Key; /**< key-code for the F5 key */
  16163. static const int F6Key; /**< key-code for the F6 key */
  16164. static const int F7Key; /**< key-code for the F7 key */
  16165. static const int F8Key; /**< key-code for the F8 key */
  16166. static const int F9Key; /**< key-code for the F9 key */
  16167. static const int F10Key; /**< key-code for the F10 key */
  16168. static const int F11Key; /**< key-code for the F11 key */
  16169. static const int F12Key; /**< key-code for the F12 key */
  16170. static const int F13Key; /**< key-code for the F13 key */
  16171. static const int F14Key; /**< key-code for the F14 key */
  16172. static const int F15Key; /**< key-code for the F15 key */
  16173. static const int F16Key; /**< key-code for the F16 key */
  16174. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  16175. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  16176. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  16177. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  16178. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  16179. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  16180. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  16181. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  16182. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  16183. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  16184. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  16185. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  16186. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  16187. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  16188. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  16189. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  16190. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  16191. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  16192. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  16193. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  16194. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  16195. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  16196. private:
  16197. int keyCode;
  16198. ModifierKeys mods;
  16199. juce_wchar textCharacter;
  16200. JUCE_LEAK_DETECTOR (KeyPress);
  16201. };
  16202. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  16203. /*** End of inlined file: juce_KeyPress.h ***/
  16204. class Component;
  16205. /**
  16206. Receives callbacks when keys are pressed.
  16207. You can add a key listener to a component to be informed when that component
  16208. gets key events. See the Component::addListener method for more details.
  16209. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  16210. */
  16211. class JUCE_API KeyListener
  16212. {
  16213. public:
  16214. /** Destructor. */
  16215. virtual ~KeyListener() {}
  16216. /** Called to indicate that a key has been pressed.
  16217. If your implementation returns true, then the key event is considered to have
  16218. been consumed, and will not be passed on to any other components. If it returns
  16219. false, then the key will be passed to other components that might want to use it.
  16220. @param key the keystroke, including modifier keys
  16221. @param originatingComponent the component that received the key event
  16222. @see keyStateChanged, Component::keyPressed
  16223. */
  16224. virtual bool keyPressed (const KeyPress& key,
  16225. Component* originatingComponent) = 0;
  16226. /** Called when any key is pressed or released.
  16227. When this is called, classes that might be interested in
  16228. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  16229. check whether their key has changed.
  16230. If your implementation returns true, then the key event is considered to have
  16231. been consumed, and will not be passed on to any other components. If it returns
  16232. false, then the key will be passed to other components that might want to use it.
  16233. @param originatingComponent the component that received the key event
  16234. @param isKeyDown true if a key is being pressed, false if one is being released
  16235. @see KeyPress, Component::keyStateChanged
  16236. */
  16237. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  16238. };
  16239. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  16240. /*** End of inlined file: juce_KeyListener.h ***/
  16241. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  16242. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  16243. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  16244. class Component;
  16245. /**
  16246. Controls the order in which focus moves between components.
  16247. The default algorithm used by this class to work out the order of traversal
  16248. is as follows:
  16249. - if two components both have an explicit focus order specified, then the
  16250. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  16251. method).
  16252. - any component with an explicit focus order greater than 0 comes before ones
  16253. that don't have an order specified.
  16254. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  16255. order.
  16256. If you need traversal in a more customised way, you can create a subclass
  16257. of KeyboardFocusTraverser that uses your own algorithm, and use
  16258. Component::createFocusTraverser() to create it.
  16259. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  16260. */
  16261. class JUCE_API KeyboardFocusTraverser
  16262. {
  16263. public:
  16264. KeyboardFocusTraverser();
  16265. /** Destructor. */
  16266. virtual ~KeyboardFocusTraverser();
  16267. /** Returns the component that should be given focus after the specified one
  16268. when moving "forwards".
  16269. The default implementation will return the next component which is to the
  16270. right of or below this one.
  16271. This may return 0 if there's no suitable candidate.
  16272. */
  16273. virtual Component* getNextComponent (Component* current);
  16274. /** Returns the component that should be given focus after the specified one
  16275. when moving "backwards".
  16276. The default implementation will return the next component which is to the
  16277. left of or above this one.
  16278. This may return 0 if there's no suitable candidate.
  16279. */
  16280. virtual Component* getPreviousComponent (Component* current);
  16281. /** Returns the component that should receive focus be default within the given
  16282. parent component.
  16283. The default implementation will just return the foremost child component that
  16284. wants focus.
  16285. This may return 0 if there's no suitable candidate.
  16286. */
  16287. virtual Component* getDefaultComponent (Component* parentComponent);
  16288. };
  16289. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  16290. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  16291. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  16292. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  16293. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  16294. /*** Start of inlined file: juce_Graphics.h ***/
  16295. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  16296. #define __JUCE_GRAPHICS_JUCEHEADER__
  16297. /*** Start of inlined file: juce_Font.h ***/
  16298. #ifndef __JUCE_FONT_JUCEHEADER__
  16299. #define __JUCE_FONT_JUCEHEADER__
  16300. /*** Start of inlined file: juce_Typeface.h ***/
  16301. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  16302. #define __JUCE_TYPEFACE_JUCEHEADER__
  16303. /*** Start of inlined file: juce_Path.h ***/
  16304. #ifndef __JUCE_PATH_JUCEHEADER__
  16305. #define __JUCE_PATH_JUCEHEADER__
  16306. /*** Start of inlined file: juce_Line.h ***/
  16307. #ifndef __JUCE_LINE_JUCEHEADER__
  16308. #define __JUCE_LINE_JUCEHEADER__
  16309. /**
  16310. Represents a line.
  16311. This class contains a bunch of useful methods for various geometric
  16312. tasks.
  16313. The ValueType template parameter should be a primitive type - float or double
  16314. are what it's designed for. Integer types will work in a basic way, but some methods
  16315. that perform mathematical operations may not compile, or they may not produce
  16316. sensible results.
  16317. @see Point, Rectangle, Path, Graphics::drawLine
  16318. */
  16319. template <typename ValueType>
  16320. class Line
  16321. {
  16322. public:
  16323. /** Creates a line, using (0, 0) as its start and end points. */
  16324. Line() throw() {}
  16325. /** Creates a copy of another line. */
  16326. Line (const Line& other) throw()
  16327. : start (other.start),
  16328. end (other.end)
  16329. {
  16330. }
  16331. /** Creates a line based on the co-ordinates of its start and end points. */
  16332. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  16333. : start (startX, startY),
  16334. end (endX, endY)
  16335. {
  16336. }
  16337. /** Creates a line from its start and end points. */
  16338. Line (const Point<ValueType>& startPoint,
  16339. const Point<ValueType>& endPoint) throw()
  16340. : start (startPoint),
  16341. end (endPoint)
  16342. {
  16343. }
  16344. /** Copies a line from another one. */
  16345. Line& operator= (const Line& other) throw()
  16346. {
  16347. start = other.start;
  16348. end = other.end;
  16349. return *this;
  16350. }
  16351. /** Destructor. */
  16352. ~Line() throw() {}
  16353. /** Returns the x co-ordinate of the line's start point. */
  16354. inline ValueType getStartX() const throw() { return start.getX(); }
  16355. /** Returns the y co-ordinate of the line's start point. */
  16356. inline ValueType getStartY() const throw() { return start.getY(); }
  16357. /** Returns the x co-ordinate of the line's end point. */
  16358. inline ValueType getEndX() const throw() { return end.getX(); }
  16359. /** Returns the y co-ordinate of the line's end point. */
  16360. inline ValueType getEndY() const throw() { return end.getY(); }
  16361. /** Returns the line's start point. */
  16362. inline const Point<ValueType>& getStart() const throw() { return start; }
  16363. /** Returns the line's end point. */
  16364. inline const Point<ValueType>& getEnd() const throw() { return end; }
  16365. /** Changes this line's start point */
  16366. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  16367. /** Changes this line's end point */
  16368. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  16369. /** Changes this line's start point */
  16370. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  16371. /** Changes this line's end point */
  16372. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  16373. /** Returns a line that is the same as this one, but with the start and end reversed, */
  16374. const Line reversed() const throw() { return Line (end, start); }
  16375. /** Applies an affine transform to the line's start and end points. */
  16376. void applyTransform (const AffineTransform& transform) throw()
  16377. {
  16378. start.applyTransform (transform);
  16379. end.applyTransform (transform);
  16380. }
  16381. /** Returns the length of the line. */
  16382. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  16383. /** Returns true if the line's start and end x co-ordinates are the same. */
  16384. bool isVertical() const throw() { return start.getX() == end.getX(); }
  16385. /** Returns true if the line's start and end y co-ordinates are the same. */
  16386. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  16387. /** Returns the line's angle.
  16388. This value is the number of radians clockwise from the 3 o'clock direction,
  16389. where the line's start point is considered to be at the centre.
  16390. */
  16391. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  16392. /** Compares two lines. */
  16393. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  16394. /** Compares two lines. */
  16395. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  16396. /** Finds the intersection between two lines.
  16397. @param line the other line
  16398. @param intersection the position of the point where the lines meet (or
  16399. where they would meet if they were infinitely long)
  16400. the intersection (if the lines intersect). If the lines
  16401. are parallel, this will just be set to the position
  16402. of one of the line's endpoints.
  16403. @returns true if the line segments intersect; false if they dont. Even if they
  16404. don't intersect, the intersection co-ordinates returned will still
  16405. be valid
  16406. */
  16407. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  16408. {
  16409. return findIntersection (start, end, line.start, line.end, intersection);
  16410. }
  16411. /** Finds the intersection between two lines.
  16412. @param line the line to intersect with
  16413. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  16414. */
  16415. const Point<ValueType> getIntersection (const Line& line) const throw()
  16416. {
  16417. Point<ValueType> p;
  16418. findIntersection (start, end, line.start, line.end, p);
  16419. return p;
  16420. }
  16421. /** Returns the location of the point which is a given distance along this line.
  16422. @param distanceFromStart the distance to move along the line from its
  16423. start point. This value can be negative or longer
  16424. than the line itself
  16425. @see getPointAlongLineProportionally
  16426. */
  16427. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  16428. {
  16429. return start + (end - start) * (distanceFromStart / getLength());
  16430. }
  16431. /** Returns a point which is a certain distance along and to the side of this line.
  16432. This effectively moves a given distance along the line, then another distance
  16433. perpendicularly to this, and returns the resulting position.
  16434. @param distanceFromStart the distance to move along the line from its
  16435. start point. This value can be negative or longer
  16436. than the line itself
  16437. @param perpendicularDistance how far to move sideways from the line. If you're
  16438. looking along the line from its start towards its
  16439. end, then a positive value here will move to the
  16440. right, negative value move to the left.
  16441. */
  16442. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  16443. ValueType perpendicularDistance) const throw()
  16444. {
  16445. const Point<ValueType> delta (end - start);
  16446. const double length = juce_hypot ((double) delta.getX(),
  16447. (double) delta.getY());
  16448. if (length == 0)
  16449. return start;
  16450. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  16451. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  16452. }
  16453. /** Returns the location of the point which is a given distance along this line
  16454. proportional to the line's length.
  16455. @param proportionOfLength the distance to move along the line from its
  16456. start point, in multiples of the line's length.
  16457. So a value of 0.0 will return the line's start point
  16458. and a value of 1.0 will return its end point. (This value
  16459. can be negative or greater than 1.0).
  16460. @see getPointAlongLine
  16461. */
  16462. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  16463. {
  16464. return start + (end - start) * proportionOfLength;
  16465. }
  16466. /** Returns the smallest distance between this line segment and a given point.
  16467. So if the point is close to the line, this will return the perpendicular
  16468. distance from the line; if the point is a long way beyond one of the line's
  16469. end-point's, it'll return the straight-line distance to the nearest end-point.
  16470. pointOnLine receives the position of the point that is found.
  16471. @returns the point's distance from the line
  16472. @see getPositionAlongLineOfNearestPoint
  16473. */
  16474. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  16475. Point<ValueType>& pointOnLine) const throw()
  16476. {
  16477. const Point<ValueType> delta (end - start);
  16478. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  16479. if (length > 0)
  16480. {
  16481. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  16482. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  16483. if (prop >= 0 && prop <= 1.0)
  16484. {
  16485. pointOnLine = start + delta * (ValueType) prop;
  16486. return targetPoint.getDistanceFrom (pointOnLine);
  16487. }
  16488. }
  16489. const float fromStart = targetPoint.getDistanceFrom (start);
  16490. const float fromEnd = targetPoint.getDistanceFrom (end);
  16491. if (fromStart < fromEnd)
  16492. {
  16493. pointOnLine = start;
  16494. return fromStart;
  16495. }
  16496. else
  16497. {
  16498. pointOnLine = end;
  16499. return fromEnd;
  16500. }
  16501. }
  16502. /** Finds the point on this line which is nearest to a given point, and
  16503. returns its position as a proportional position along the line.
  16504. @returns a value 0 to 1.0 which is the distance along this line from the
  16505. line's start to the point which is nearest to the point passed-in. To
  16506. turn this number into a position, use getPointAlongLineProportionally().
  16507. @see getDistanceFromPoint, getPointAlongLineProportionally
  16508. */
  16509. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  16510. {
  16511. const Point<ValueType> delta (end - start);
  16512. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  16513. return length <= 0 ? 0
  16514. : jlimit ((ValueType) 0, (ValueType) 1,
  16515. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  16516. + (point.getY() - start.getY()) * delta.getY()) / length));
  16517. }
  16518. /** Finds the point on this line which is nearest to a given point.
  16519. @see getDistanceFromPoint, findNearestProportionalPositionTo
  16520. */
  16521. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  16522. {
  16523. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  16524. }
  16525. /** Returns true if the given point lies above this line.
  16526. The return value is true if the point's y coordinate is less than the y
  16527. coordinate of this line at the given x (assuming the line extends infinitely
  16528. in both directions).
  16529. */
  16530. bool isPointAbove (const Point<ValueType>& point) const throw()
  16531. {
  16532. return start.getX() != end.getX()
  16533. && point.getY() < ((end.getY() - start.getY())
  16534. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  16535. }
  16536. /** Returns a shortened copy of this line.
  16537. This will chop off part of the start of this line by a certain amount, (leaving the
  16538. end-point the same), and return the new line.
  16539. */
  16540. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  16541. {
  16542. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  16543. }
  16544. /** Returns a shortened copy of this line.
  16545. This will chop off part of the end of this line by a certain amount, (leaving the
  16546. start-point the same), and return the new line.
  16547. */
  16548. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  16549. {
  16550. const ValueType length = getLength();
  16551. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  16552. }
  16553. private:
  16554. Point<ValueType> start, end;
  16555. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  16556. const Point<ValueType>& p3, const Point<ValueType>& p4,
  16557. Point<ValueType>& intersection) throw()
  16558. {
  16559. if (p2 == p3)
  16560. {
  16561. intersection = p2;
  16562. return true;
  16563. }
  16564. const Point<ValueType> d1 (p2 - p1);
  16565. const Point<ValueType> d2 (p4 - p3);
  16566. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  16567. if (divisor == 0)
  16568. {
  16569. if (! (d1.isOrigin() || d2.isOrigin()))
  16570. {
  16571. if (d1.getY() == 0 && d2.getY() != 0)
  16572. {
  16573. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  16574. intersection = p1.withX (p3.getX() + along * d2.getX());
  16575. return along >= 0 && along <= (ValueType) 1;
  16576. }
  16577. else if (d2.getY() == 0 && d1.getY() != 0)
  16578. {
  16579. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  16580. intersection = p3.withX (p1.getX() + along * d1.getX());
  16581. return along >= 0 && along <= (ValueType) 1;
  16582. }
  16583. else if (d1.getX() == 0 && d2.getX() != 0)
  16584. {
  16585. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  16586. intersection = p1.withY (p3.getY() + along * d2.getY());
  16587. return along >= 0 && along <= (ValueType) 1;
  16588. }
  16589. else if (d2.getX() == 0 && d1.getX() != 0)
  16590. {
  16591. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  16592. intersection = p3.withY (p1.getY() + along * d1.getY());
  16593. return along >= 0 && along <= (ValueType) 1;
  16594. }
  16595. }
  16596. intersection = (p2 + p3) / (ValueType) 2;
  16597. return false;
  16598. }
  16599. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  16600. intersection = p1 + d1 * along1;
  16601. if (along1 < 0 || along1 > (ValueType) 1)
  16602. return false;
  16603. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  16604. return along2 >= 0 && along2 <= (ValueType) 1;
  16605. }
  16606. };
  16607. #endif // __JUCE_LINE_JUCEHEADER__
  16608. /*** End of inlined file: juce_Line.h ***/
  16609. /*** Start of inlined file: juce_Rectangle.h ***/
  16610. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  16611. #define __JUCE_RECTANGLE_JUCEHEADER__
  16612. class RectangleList;
  16613. /**
  16614. Manages a rectangle and allows geometric operations to be performed on it.
  16615. @see RectangleList, Path, Line, Point
  16616. */
  16617. template <typename ValueType>
  16618. class Rectangle
  16619. {
  16620. public:
  16621. /** Creates a rectangle of zero size.
  16622. The default co-ordinates will be (0, 0, 0, 0).
  16623. */
  16624. Rectangle() throw()
  16625. : x (0), y (0), w (0), h (0)
  16626. {
  16627. }
  16628. /** Creates a copy of another rectangle. */
  16629. Rectangle (const Rectangle& other) throw()
  16630. : x (other.x), y (other.y),
  16631. w (other.w), h (other.h)
  16632. {
  16633. }
  16634. /** Creates a rectangle with a given position and size. */
  16635. Rectangle (const ValueType initialX, const ValueType initialY,
  16636. const ValueType width, const ValueType height) throw()
  16637. : x (initialX), y (initialY),
  16638. w (width), h (height)
  16639. {
  16640. }
  16641. /** Creates a rectangle with a given size, and a position of (0, 0). */
  16642. Rectangle (const ValueType width, const ValueType height) throw()
  16643. : x (0), y (0), w (width), h (height)
  16644. {
  16645. }
  16646. /** Creates a Rectangle from the positions of two opposite corners. */
  16647. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  16648. : x (jmin (corner1.getX(), corner2.getX())),
  16649. y (jmin (corner1.getY(), corner2.getY())),
  16650. w (corner1.getX() - corner2.getX()),
  16651. h (corner1.getY() - corner2.getY())
  16652. {
  16653. if (w < 0) w = -w;
  16654. if (h < 0) h = -h;
  16655. }
  16656. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  16657. The right and bottom values must be larger than the left and top ones, or the resulting
  16658. rectangle will have a negative size.
  16659. */
  16660. static const Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  16661. const ValueType right, const ValueType bottom) throw()
  16662. {
  16663. return Rectangle (left, top, right - left, bottom - top);
  16664. }
  16665. Rectangle& operator= (const Rectangle& other) throw()
  16666. {
  16667. x = other.x; y = other.y;
  16668. w = other.w; h = other.h;
  16669. return *this;
  16670. }
  16671. /** Destructor. */
  16672. ~Rectangle() throw() {}
  16673. /** Returns true if the rectangle's width and height are both zero or less */
  16674. bool isEmpty() const throw() { return w <= 0 || h <= 0; }
  16675. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  16676. inline ValueType getX() const throw() { return x; }
  16677. /** Returns the y co-ordinate of the rectangle's top edge. */
  16678. inline ValueType getY() const throw() { return y; }
  16679. /** Returns the width of the rectangle. */
  16680. inline ValueType getWidth() const throw() { return w; }
  16681. /** Returns the height of the rectangle. */
  16682. inline ValueType getHeight() const throw() { return h; }
  16683. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  16684. inline ValueType getRight() const throw() { return x + w; }
  16685. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  16686. inline ValueType getBottom() const throw() { return y + h; }
  16687. /** Returns the x co-ordinate of the rectangle's centre. */
  16688. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  16689. /** Returns the y co-ordinate of the rectangle's centre. */
  16690. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  16691. /** Returns the centre point of the rectangle. */
  16692. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  16693. /** Returns the aspect ratio of the rectangle's width / height.
  16694. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  16695. it returns height / width. */
  16696. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  16697. /** Returns the rectangle's top-left position as a Point. */
  16698. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  16699. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  16700. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  16701. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  16702. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  16703. /** Returns a rectangle with the same size as this one, but a new position. */
  16704. const Rectangle withPosition (const ValueType newX, const ValueType newY) const throw() { return Rectangle (newX, newY, w, h); }
  16705. /** Returns a rectangle with the same size as this one, but a new position. */
  16706. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  16707. /** Returns the rectangle's top-left position as a Point. */
  16708. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  16709. /** Returns the rectangle's top-right position as a Point. */
  16710. const Point<ValueType> getTopRight() const throw() { return Point<ValueType> (x + w, y); }
  16711. /** Returns the rectangle's bottom-left position as a Point. */
  16712. const Point<ValueType> getBottomLeft() const throw() { return Point<ValueType> (x, y + h); }
  16713. /** Returns the rectangle's bottom-right position as a Point. */
  16714. const Point<ValueType> getBottomRight() const throw() { return Point<ValueType> (x + w, y + h); }
  16715. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  16716. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  16717. /** Returns a rectangle with the same position as this one, but a new size. */
  16718. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  16719. /** Changes all the rectangle's co-ordinates. */
  16720. void setBounds (const ValueType newX, const ValueType newY,
  16721. const ValueType newWidth, const ValueType newHeight) throw()
  16722. {
  16723. x = newX; y = newY; w = newWidth; h = newHeight;
  16724. }
  16725. /** Changes the rectangle's X coordinate */
  16726. void setX (const ValueType newX) throw() { x = newX; }
  16727. /** Changes the rectangle's Y coordinate */
  16728. void setY (const ValueType newY) throw() { y = newY; }
  16729. /** Changes the rectangle's width */
  16730. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  16731. /** Changes the rectangle's height */
  16732. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  16733. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  16734. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  16735. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  16736. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  16737. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  16738. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  16739. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  16740. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  16741. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  16742. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  16743. @see withLeft
  16744. */
  16745. void setLeft (const ValueType newLeft) throw()
  16746. {
  16747. w = jmax (ValueType(), x + w - newLeft);
  16748. x = newLeft;
  16749. }
  16750. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  16751. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  16752. @see setLeft
  16753. */
  16754. const Rectangle withLeft (const ValueType newLeft) const throw() { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  16755. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  16756. If the y is moved to be below the current bottom edge, the height will be set to zero.
  16757. @see withTop
  16758. */
  16759. void setTop (const ValueType newTop) throw()
  16760. {
  16761. h = jmax (ValueType(), y + h - newTop);
  16762. y = newTop;
  16763. }
  16764. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  16765. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  16766. @see setTop
  16767. */
  16768. const Rectangle withTop (const ValueType newTop) const throw() { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  16769. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  16770. If the new right is below the current X value, the X will be pushed down to match it.
  16771. @see getRight, withRight
  16772. */
  16773. void setRight (const ValueType newRight) throw()
  16774. {
  16775. x = jmin (x, newRight);
  16776. w = newRight - x;
  16777. }
  16778. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  16779. If the new right edge is below the current left-hand edge, the width will be set to zero.
  16780. @see setRight
  16781. */
  16782. const Rectangle withRight (const ValueType newRight) const throw() { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  16783. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  16784. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  16785. @see getBottom, withBottom
  16786. */
  16787. void setBottom (const ValueType newBottom) throw()
  16788. {
  16789. y = jmin (y, newBottom);
  16790. h = newBottom - y;
  16791. }
  16792. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  16793. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  16794. @see setBottom
  16795. */
  16796. const Rectangle withBottom (const ValueType newBottom) const throw() { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  16797. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  16798. void translate (const ValueType deltaX,
  16799. const ValueType deltaY) throw()
  16800. {
  16801. x += deltaX;
  16802. y += deltaY;
  16803. }
  16804. /** Returns a rectangle which is the same as this one moved by a given amount. */
  16805. const Rectangle translated (const ValueType deltaX,
  16806. const ValueType deltaY) const throw()
  16807. {
  16808. return Rectangle (x + deltaX, y + deltaY, w, h);
  16809. }
  16810. /** Returns a rectangle which is the same as this one moved by a given amount. */
  16811. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  16812. {
  16813. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  16814. }
  16815. /** Moves this rectangle by a given amount. */
  16816. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  16817. {
  16818. x += deltaPosition.getX(); y += deltaPosition.getY();
  16819. return *this;
  16820. }
  16821. /** Returns a rectangle which is the same as this one moved by a given amount. */
  16822. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  16823. {
  16824. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  16825. }
  16826. /** Moves this rectangle by a given amount. */
  16827. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  16828. {
  16829. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  16830. return *this;
  16831. }
  16832. /** Expands the rectangle by a given amount.
  16833. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  16834. @see expanded, reduce, reduced
  16835. */
  16836. void expand (const ValueType deltaX,
  16837. const ValueType deltaY) throw()
  16838. {
  16839. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  16840. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  16841. setBounds (x - deltaX, y - deltaY, nw, nh);
  16842. }
  16843. /** Returns a rectangle that is larger than this one by a given amount.
  16844. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  16845. @see expand, reduce, reduced
  16846. */
  16847. const Rectangle expanded (const ValueType deltaX,
  16848. const ValueType deltaY) const throw()
  16849. {
  16850. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  16851. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  16852. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  16853. }
  16854. /** Shrinks the rectangle by a given amount.
  16855. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  16856. @see reduced, expand, expanded
  16857. */
  16858. void reduce (const ValueType deltaX,
  16859. const ValueType deltaY) throw()
  16860. {
  16861. expand (-deltaX, -deltaY);
  16862. }
  16863. /** Returns a rectangle that is smaller than this one by a given amount.
  16864. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  16865. @see reduce, expand, expanded
  16866. */
  16867. const Rectangle reduced (const ValueType deltaX,
  16868. const ValueType deltaY) const throw()
  16869. {
  16870. return expanded (-deltaX, -deltaY);
  16871. }
  16872. /** Removes a strip from the top of this rectangle, reducing this rectangle
  16873. by the specified amount and returning the section that was removed.
  16874. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  16875. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  16876. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  16877. that value.
  16878. */
  16879. const Rectangle removeFromTop (const ValueType amountToRemove) throw()
  16880. {
  16881. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  16882. y += r.h; h -= r.h;
  16883. return r;
  16884. }
  16885. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  16886. by the specified amount and returning the section that was removed.
  16887. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  16888. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  16889. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  16890. that value.
  16891. */
  16892. const Rectangle removeFromLeft (const ValueType amountToRemove) throw()
  16893. {
  16894. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  16895. x += r.w; w -= r.w;
  16896. return r;
  16897. }
  16898. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  16899. by the specified amount and returning the section that was removed.
  16900. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  16901. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  16902. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  16903. that value.
  16904. */
  16905. const Rectangle removeFromRight (ValueType amountToRemove) throw()
  16906. {
  16907. amountToRemove = jmin (amountToRemove, w);
  16908. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  16909. w -= amountToRemove;
  16910. return r;
  16911. }
  16912. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  16913. by the specified amount and returning the section that was removed.
  16914. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  16915. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  16916. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  16917. that value.
  16918. */
  16919. const Rectangle removeFromBottom (ValueType amountToRemove) throw()
  16920. {
  16921. amountToRemove = jmin (amountToRemove, h);
  16922. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  16923. h -= amountToRemove;
  16924. return r;
  16925. }
  16926. /** Returns true if the two rectangles are identical. */
  16927. bool operator== (const Rectangle& other) const throw()
  16928. {
  16929. return x == other.x && y == other.y
  16930. && w == other.w && h == other.h;
  16931. }
  16932. /** Returns true if the two rectangles are not identical. */
  16933. bool operator!= (const Rectangle& other) const throw()
  16934. {
  16935. return x != other.x || y != other.y
  16936. || w != other.w || h != other.h;
  16937. }
  16938. /** Returns true if this co-ordinate is inside the rectangle. */
  16939. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  16940. {
  16941. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  16942. }
  16943. /** Returns true if this co-ordinate is inside the rectangle. */
  16944. bool contains (const Point<ValueType>& point) const throw()
  16945. {
  16946. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  16947. }
  16948. /** Returns true if this other rectangle is completely inside this one. */
  16949. bool contains (const Rectangle& other) const throw()
  16950. {
  16951. return x <= other.x && y <= other.y
  16952. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  16953. }
  16954. /** Returns the nearest point to the specified point that lies within this rectangle. */
  16955. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  16956. {
  16957. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  16958. jlimit (y, y + h, point.getY()));
  16959. }
  16960. /** Returns true if any part of another rectangle overlaps this one. */
  16961. bool intersects (const Rectangle& other) const throw()
  16962. {
  16963. return x + w > other.x
  16964. && y + h > other.y
  16965. && x < other.x + other.w
  16966. && y < other.y + other.h
  16967. && w > ValueType() && h > ValueType();
  16968. }
  16969. /** Returns the region that is the overlap between this and another rectangle.
  16970. If the two rectangles don't overlap, the rectangle returned will be empty.
  16971. */
  16972. const Rectangle getIntersection (const Rectangle& other) const throw()
  16973. {
  16974. const ValueType nx = jmax (x, other.x);
  16975. const ValueType ny = jmax (y, other.y);
  16976. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  16977. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  16978. if (nw >= ValueType() && nh >= ValueType())
  16979. return Rectangle (nx, ny, nw, nh);
  16980. return Rectangle();
  16981. }
  16982. /** Clips a rectangle so that it lies only within this one.
  16983. This is a non-static version of intersectRectangles().
  16984. Returns false if the two regions didn't overlap.
  16985. */
  16986. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  16987. {
  16988. const int maxX = jmax (otherX, x);
  16989. otherW = jmin (otherX + otherW, x + w) - maxX;
  16990. if (otherW > 0)
  16991. {
  16992. const int maxY = jmax (otherY, y);
  16993. otherH = jmin (otherY + otherH, y + h) - maxY;
  16994. if (otherH > 0)
  16995. {
  16996. otherX = maxX; otherY = maxY;
  16997. return true;
  16998. }
  16999. }
  17000. return false;
  17001. }
  17002. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  17003. If either this or the other rectangle are empty, they will not be counted as
  17004. part of the resulting region.
  17005. */
  17006. const Rectangle getUnion (const Rectangle& other) const throw()
  17007. {
  17008. if (other.isEmpty()) return *this;
  17009. if (isEmpty()) return other;
  17010. const ValueType newX = jmin (x, other.x);
  17011. const ValueType newY = jmin (y, other.y);
  17012. return Rectangle (newX, newY,
  17013. jmax (x + w, other.x + other.w) - newX,
  17014. jmax (y + h, other.y + other.h) - newY);
  17015. }
  17016. /** If this rectangle merged with another one results in a simple rectangle, this
  17017. will set this rectangle to the result, and return true.
  17018. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  17019. or if they form a complex region.
  17020. */
  17021. bool enlargeIfAdjacent (const Rectangle& other) throw()
  17022. {
  17023. if (x == other.x && getRight() == other.getRight()
  17024. && (other.getBottom() >= y && other.y <= getBottom()))
  17025. {
  17026. const ValueType newY = jmin (y, other.y);
  17027. h = jmax (getBottom(), other.getBottom()) - newY;
  17028. y = newY;
  17029. return true;
  17030. }
  17031. else if (y == other.y && getBottom() == other.getBottom()
  17032. && (other.getRight() >= x && other.x <= getRight()))
  17033. {
  17034. const ValueType newX = jmin (x, other.x);
  17035. w = jmax (getRight(), other.getRight()) - newX;
  17036. x = newX;
  17037. return true;
  17038. }
  17039. return false;
  17040. }
  17041. /** If after removing another rectangle from this one the result is a simple rectangle,
  17042. this will set this object's bounds to be the result, and return true.
  17043. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  17044. or if removing the other one would form a complex region.
  17045. */
  17046. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  17047. {
  17048. int inside = 0;
  17049. const int otherR = other.getRight();
  17050. if (x >= other.x && x < otherR) inside = 1;
  17051. const int otherB = other.getBottom();
  17052. if (y >= other.y && y < otherB) inside |= 2;
  17053. const int r = x + w;
  17054. if (r >= other.x && r < otherR) inside |= 4;
  17055. const int b = y + h;
  17056. if (b >= other.y && b < otherB) inside |= 8;
  17057. switch (inside)
  17058. {
  17059. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  17060. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  17061. case 2 + 4 + 8: w = other.x - x; return true;
  17062. case 1 + 4 + 8: h = other.y - y; return true;
  17063. }
  17064. return false;
  17065. }
  17066. /** Returns the smallest rectangle that can contain the shape created by applying
  17067. a transform to this rectangle.
  17068. This should only be used on floating point rectangles.
  17069. */
  17070. const Rectangle transformed (const AffineTransform& transform) const throw()
  17071. {
  17072. float x1 = x, y1 = y;
  17073. float x2 = x + w, y2 = y;
  17074. float x3 = x, y3 = y + h;
  17075. float x4 = x2, y4 = y3;
  17076. transform.transformPoints (x1, y1, x2, y2);
  17077. transform.transformPoints (x3, y3, x4, y4);
  17078. const float rx = jmin (x1, x2, x3, x4);
  17079. const float ry = jmin (y1, y2, y3, y4);
  17080. return Rectangle (rx, ry,
  17081. jmax (x1, x2, x3, x4) - rx,
  17082. jmax (y1, y2, y3, y4) - ry);
  17083. }
  17084. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  17085. This is only relevent for floating-point rectangles, of course.
  17086. @see toFloat()
  17087. */
  17088. const Rectangle<int> getSmallestIntegerContainer() const throw()
  17089. {
  17090. const int x1 = (int) std::floor (static_cast<float> (x));
  17091. const int y1 = (int) std::floor (static_cast<float> (y));
  17092. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  17093. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  17094. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  17095. }
  17096. /** Returns the smallest Rectangle that can contain a set of points. */
  17097. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  17098. {
  17099. if (numPoints == 0)
  17100. return Rectangle();
  17101. ValueType minX (points[0].getX());
  17102. ValueType maxX (minX);
  17103. ValueType minY (points[0].getY());
  17104. ValueType maxY (minY);
  17105. for (int i = 1; i < numPoints; ++i)
  17106. {
  17107. minX = jmin (minX, points[i].getX());
  17108. maxX = jmax (maxX, points[i].getX());
  17109. minY = jmin (minY, points[i].getY());
  17110. maxY = jmax (maxY, points[i].getY());
  17111. }
  17112. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  17113. }
  17114. /** Casts this rectangle to a Rectangle<float>.
  17115. Obviously this is mainly useful for rectangles that use integer types.
  17116. @see getSmallestIntegerContainer
  17117. */
  17118. const Rectangle<float> toFloat() const throw()
  17119. {
  17120. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  17121. static_cast<float> (w), static_cast<float> (h));
  17122. }
  17123. /** Static utility to intersect two sets of rectangular co-ordinates.
  17124. Returns false if the two regions didn't overlap.
  17125. @see intersectRectangle
  17126. */
  17127. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  17128. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  17129. {
  17130. const ValueType x = jmax (x1, x2);
  17131. w1 = jmin (x1 + w1, x2 + w2) - x;
  17132. if (w1 > 0)
  17133. {
  17134. const ValueType y = jmax (y1, y2);
  17135. h1 = jmin (y1 + h1, y2 + h2) - y;
  17136. if (h1 > 0)
  17137. {
  17138. x1 = x; y1 = y;
  17139. return true;
  17140. }
  17141. }
  17142. return false;
  17143. }
  17144. /** Creates a string describing this rectangle.
  17145. The string will be of the form "x y width height", e.g. "100 100 400 200".
  17146. Coupled with the fromString() method, this is very handy for things like
  17147. storing rectangles (particularly component positions) in XML attributes.
  17148. @see fromString
  17149. */
  17150. const String toString() const
  17151. {
  17152. String s;
  17153. s.preallocateStorage (16);
  17154. s << x << ' ' << y << ' ' << w << ' ' << h;
  17155. return s;
  17156. }
  17157. /** Parses a string containing a rectangle's details.
  17158. The string should contain 4 integer tokens, in the form "x y width height". They
  17159. can be comma or whitespace separated.
  17160. This method is intended to go with the toString() method, to form an easy way
  17161. of saving/loading rectangles as strings.
  17162. @see toString
  17163. */
  17164. static const Rectangle fromString (const String& stringVersion)
  17165. {
  17166. StringArray toks;
  17167. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  17168. return Rectangle (toks[0].trim().getIntValue(),
  17169. toks[1].trim().getIntValue(),
  17170. toks[2].trim().getIntValue(),
  17171. toks[3].trim().getIntValue());
  17172. }
  17173. private:
  17174. friend class RectangleList;
  17175. ValueType x, y, w, h;
  17176. };
  17177. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  17178. /*** End of inlined file: juce_Rectangle.h ***/
  17179. /*** Start of inlined file: juce_Justification.h ***/
  17180. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  17181. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  17182. /**
  17183. Represents a type of justification to be used when positioning graphical items.
  17184. e.g. it indicates whether something should be placed top-left, top-right,
  17185. centred, etc.
  17186. It is used in various places wherever this kind of information is needed.
  17187. */
  17188. class JUCE_API Justification
  17189. {
  17190. public:
  17191. /** Creates a Justification object using a combination of flags. */
  17192. inline Justification (int flags_) throw() : flags (flags_) {}
  17193. /** Creates a copy of another Justification object. */
  17194. Justification (const Justification& other) throw();
  17195. /** Copies another Justification object. */
  17196. Justification& operator= (const Justification& other) throw();
  17197. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  17198. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  17199. /** Returns the raw flags that are set for this Justification object. */
  17200. inline int getFlags() const throw() { return flags; }
  17201. /** Tests a set of flags for this object.
  17202. @returns true if any of the flags passed in are set on this object.
  17203. */
  17204. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  17205. /** Returns just the flags from this object that deal with vertical layout. */
  17206. int getOnlyVerticalFlags() const throw();
  17207. /** Returns just the flags from this object that deal with horizontal layout. */
  17208. int getOnlyHorizontalFlags() const throw();
  17209. /** Adjusts the position of a rectangle to fit it into a space.
  17210. The (x, y) position of the rectangle will be updated to position it inside the
  17211. given space according to the justification flags.
  17212. */
  17213. template <typename ValueType>
  17214. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  17215. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const throw()
  17216. {
  17217. x = spaceX;
  17218. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  17219. else if ((flags & right) != 0) x += spaceW - w;
  17220. y = spaceY;
  17221. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  17222. else if ((flags & bottom) != 0) y += spaceH - h;
  17223. }
  17224. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  17225. */
  17226. template <typename ValueType>
  17227. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  17228. const Rectangle<ValueType>& targetSpace) const throw()
  17229. {
  17230. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  17231. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  17232. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  17233. return areaToAdjust.withPosition (x, y);
  17234. }
  17235. /** Flag values that can be combined and used in the constructor. */
  17236. enum
  17237. {
  17238. /** Indicates that the item should be aligned against the left edge of the available space. */
  17239. left = 1,
  17240. /** Indicates that the item should be aligned against the right edge of the available space. */
  17241. right = 2,
  17242. /** Indicates that the item should be placed in the centre between the left and right
  17243. sides of the available space. */
  17244. horizontallyCentred = 4,
  17245. /** Indicates that the item should be aligned against the top edge of the available space. */
  17246. top = 8,
  17247. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  17248. bottom = 16,
  17249. /** Indicates that the item should be placed in the centre between the top and bottom
  17250. sides of the available space. */
  17251. verticallyCentred = 32,
  17252. /** Indicates that lines of text should be spread out to fill the maximum width
  17253. available, so that both margins are aligned vertically.
  17254. */
  17255. horizontallyJustified = 64,
  17256. /** Indicates that the item should be centred vertically and horizontally.
  17257. This is equivalent to (horizontallyCentred | verticallyCentred)
  17258. */
  17259. centred = 36,
  17260. /** Indicates that the item should be centred vertically but placed on the left hand side.
  17261. This is equivalent to (left | verticallyCentred)
  17262. */
  17263. centredLeft = 33,
  17264. /** Indicates that the item should be centred vertically but placed on the right hand side.
  17265. This is equivalent to (right | verticallyCentred)
  17266. */
  17267. centredRight = 34,
  17268. /** Indicates that the item should be centred horizontally and placed at the top.
  17269. This is equivalent to (horizontallyCentred | top)
  17270. */
  17271. centredTop = 12,
  17272. /** Indicates that the item should be centred horizontally and placed at the bottom.
  17273. This is equivalent to (horizontallyCentred | bottom)
  17274. */
  17275. centredBottom = 20,
  17276. /** Indicates that the item should be placed in the top-left corner.
  17277. This is equivalent to (left | top)
  17278. */
  17279. topLeft = 9,
  17280. /** Indicates that the item should be placed in the top-right corner.
  17281. This is equivalent to (right | top)
  17282. */
  17283. topRight = 10,
  17284. /** Indicates that the item should be placed in the bottom-left corner.
  17285. This is equivalent to (left | bottom)
  17286. */
  17287. bottomLeft = 17,
  17288. /** Indicates that the item should be placed in the bottom-left corner.
  17289. This is equivalent to (right | bottom)
  17290. */
  17291. bottomRight = 18
  17292. };
  17293. private:
  17294. int flags;
  17295. };
  17296. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  17297. /*** End of inlined file: juce_Justification.h ***/
  17298. class Image;
  17299. /**
  17300. A path is a sequence of lines and curves that may either form a closed shape
  17301. or be open-ended.
  17302. To use a path, you can create an empty one, then add lines and curves to it
  17303. to create shapes, then it can be rendered by a Graphics context or used
  17304. for geometric operations.
  17305. e.g. @code
  17306. Path myPath;
  17307. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  17308. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  17309. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  17310. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  17311. // add an ellipse as well, which will form a second sub-path within the path..
  17312. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  17313. // double the width of the whole thing..
  17314. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  17315. // and draw it to a graphics context with a 5-pixel thick outline.
  17316. g.strokePath (myPath, PathStrokeType (5.0f));
  17317. @endcode
  17318. A path object can actually contain multiple sub-paths, which may themselves
  17319. be open or closed.
  17320. @see PathFlatteningIterator, PathStrokeType, Graphics
  17321. */
  17322. class JUCE_API Path
  17323. {
  17324. public:
  17325. /** Creates an empty path. */
  17326. Path();
  17327. /** Creates a copy of another path. */
  17328. Path (const Path& other);
  17329. /** Destructor. */
  17330. ~Path();
  17331. /** Copies this path from another one. */
  17332. Path& operator= (const Path& other);
  17333. bool operator== (const Path& other) const throw();
  17334. bool operator!= (const Path& other) const throw();
  17335. /** Returns true if the path doesn't contain any lines or curves. */
  17336. bool isEmpty() const throw();
  17337. /** Returns the smallest rectangle that contains all points within the path.
  17338. */
  17339. const Rectangle<float> getBounds() const throw();
  17340. /** Returns the smallest rectangle that contains all points within the path
  17341. after it's been transformed with the given tranasform matrix.
  17342. */
  17343. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  17344. /** Checks whether a point lies within the path.
  17345. This is only relevent for closed paths (see closeSubPath()), and
  17346. may produce false results if used on a path which has open sub-paths.
  17347. The path's winding rule is taken into account by this method.
  17348. The tolerance parameter is the maximum error allowed when flattening the path,
  17349. so this method could return a false positive when your point is up to this distance
  17350. outside the path's boundary.
  17351. @see closeSubPath, setUsingNonZeroWinding
  17352. */
  17353. bool contains (float x, float y,
  17354. float tolerance = 1.0f) const;
  17355. /** Checks whether a point lies within the path.
  17356. This is only relevent for closed paths (see closeSubPath()), and
  17357. may produce false results if used on a path which has open sub-paths.
  17358. The path's winding rule is taken into account by this method.
  17359. The tolerance parameter is the maximum error allowed when flattening the path,
  17360. so this method could return a false positive when your point is up to this distance
  17361. outside the path's boundary.
  17362. @see closeSubPath, setUsingNonZeroWinding
  17363. */
  17364. bool contains (const Point<float>& point,
  17365. float tolerance = 1.0f) const;
  17366. /** Checks whether a line crosses the path.
  17367. This will return positive if the line crosses any of the paths constituent
  17368. lines or curves. It doesn't take into account whether the line is inside
  17369. or outside the path, or whether the path is open or closed.
  17370. The tolerance parameter is the maximum error allowed when flattening the path,
  17371. so this method could return a false positive when your point is up to this distance
  17372. outside the path's boundary.
  17373. */
  17374. bool intersectsLine (const Line<float>& line,
  17375. float tolerance = 1.0f);
  17376. /** Cuts off parts of a line to keep the parts that are either inside or
  17377. outside this path.
  17378. Note that this isn't smart enough to cope with situations where the
  17379. line would need to be cut into multiple pieces to correctly clip against
  17380. a re-entrant shape.
  17381. @param line the line to clip
  17382. @param keepSectionOutsidePath if true, it's the section outside the path
  17383. that will be kept; if false its the section inside
  17384. the path
  17385. */
  17386. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  17387. /** Returns the length of the path.
  17388. @see getPointAlongPath
  17389. */
  17390. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  17391. /** Returns a point that is the specified distance along the path.
  17392. If the distance is greater than the total length of the path, this will return the
  17393. end point.
  17394. @see getLength
  17395. */
  17396. const Point<float> getPointAlongPath (float distanceFromStart,
  17397. const AffineTransform& transform = AffineTransform::identity) const;
  17398. /** Finds the point along the path which is nearest to a given position.
  17399. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  17400. of the path.
  17401. */
  17402. float getNearestPoint (const Point<float>& targetPoint,
  17403. Point<float>& pointOnPath,
  17404. const AffineTransform& transform = AffineTransform::identity) const;
  17405. /** Removes all lines and curves, resetting the path completely. */
  17406. void clear() throw();
  17407. /** Begins a new subpath with a given starting position.
  17408. This will move the path's current position to the co-ordinates passed in and
  17409. make it ready to draw lines or curves starting from this position.
  17410. After adding whatever lines and curves are needed, you can either
  17411. close the current sub-path using closeSubPath() or call startNewSubPath()
  17412. to move to a new sub-path, leaving the old one open-ended.
  17413. @see lineTo, quadraticTo, cubicTo, closeSubPath
  17414. */
  17415. void startNewSubPath (float startX, float startY);
  17416. /** Begins a new subpath with a given starting position.
  17417. This will move the path's current position to the co-ordinates passed in and
  17418. make it ready to draw lines or curves starting from this position.
  17419. After adding whatever lines and curves are needed, you can either
  17420. close the current sub-path using closeSubPath() or call startNewSubPath()
  17421. to move to a new sub-path, leaving the old one open-ended.
  17422. @see lineTo, quadraticTo, cubicTo, closeSubPath
  17423. */
  17424. void startNewSubPath (const Point<float>& start);
  17425. /** Closes a the current sub-path with a line back to its start-point.
  17426. When creating a closed shape such as a triangle, don't use 3 lineTo()
  17427. calls - instead use two lineTo() calls, followed by a closeSubPath()
  17428. to join the final point back to the start.
  17429. This ensures that closes shapes are recognised as such, and this is
  17430. important for tasks like drawing strokes, which needs to know whether to
  17431. draw end-caps or not.
  17432. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  17433. */
  17434. void closeSubPath();
  17435. /** Adds a line from the shape's last position to a new end-point.
  17436. This will connect the end-point of the last line or curve that was added
  17437. to a new point, using a straight line.
  17438. See the class description for an example of how to add lines and curves to a path.
  17439. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  17440. */
  17441. void lineTo (float endX, float endY);
  17442. /** Adds a line from the shape's last position to a new end-point.
  17443. This will connect the end-point of the last line or curve that was added
  17444. to a new point, using a straight line.
  17445. See the class description for an example of how to add lines and curves to a path.
  17446. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  17447. */
  17448. void lineTo (const Point<float>& end);
  17449. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  17450. This will connect the end-point of the last line or curve that was added
  17451. to a new point, using a quadratic spline with one control-point.
  17452. See the class description for an example of how to add lines and curves to a path.
  17453. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  17454. */
  17455. void quadraticTo (float controlPointX,
  17456. float controlPointY,
  17457. float endPointX,
  17458. float endPointY);
  17459. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  17460. This will connect the end-point of the last line or curve that was added
  17461. to a new point, using a quadratic spline with one control-point.
  17462. See the class description for an example of how to add lines and curves to a path.
  17463. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  17464. */
  17465. void quadraticTo (const Point<float>& controlPoint,
  17466. const Point<float>& endPoint);
  17467. /** Adds a cubic bezier curve from the shape's last position to a new position.
  17468. This will connect the end-point of the last line or curve that was added
  17469. to a new point, using a cubic spline with two control-points.
  17470. See the class description for an example of how to add lines and curves to a path.
  17471. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  17472. */
  17473. void cubicTo (float controlPoint1X,
  17474. float controlPoint1Y,
  17475. float controlPoint2X,
  17476. float controlPoint2Y,
  17477. float endPointX,
  17478. float endPointY);
  17479. /** Adds a cubic bezier curve from the shape's last position to a new position.
  17480. This will connect the end-point of the last line or curve that was added
  17481. to a new point, using a cubic spline with two control-points.
  17482. See the class description for an example of how to add lines and curves to a path.
  17483. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  17484. */
  17485. void cubicTo (const Point<float>& controlPoint1,
  17486. const Point<float>& controlPoint2,
  17487. const Point<float>& endPoint);
  17488. /** Returns the last point that was added to the path by one of the drawing methods.
  17489. */
  17490. const Point<float> getCurrentPosition() const;
  17491. /** Adds a rectangle to the path.
  17492. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  17493. @see addRoundedRectangle, addTriangle
  17494. */
  17495. void addRectangle (float x, float y, float width, float height);
  17496. /** Adds a rectangle to the path.
  17497. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  17498. @see addRoundedRectangle, addTriangle
  17499. */
  17500. template <typename ValueType>
  17501. void addRectangle (const Rectangle<ValueType>& rectangle)
  17502. {
  17503. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  17504. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  17505. }
  17506. /** Adds a rectangle with rounded corners to the path.
  17507. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  17508. @see addRectangle, addTriangle
  17509. */
  17510. void addRoundedRectangle (float x, float y, float width, float height,
  17511. float cornerSize);
  17512. /** Adds a rectangle with rounded corners to the path.
  17513. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  17514. @see addRectangle, addTriangle
  17515. */
  17516. void addRoundedRectangle (float x, float y, float width, float height,
  17517. float cornerSizeX,
  17518. float cornerSizeY);
  17519. /** Adds a rectangle with rounded corners to the path.
  17520. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  17521. @see addRectangle, addTriangle
  17522. */
  17523. template <typename ValueType>
  17524. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  17525. {
  17526. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  17527. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  17528. cornerSizeX, cornerSizeY);
  17529. }
  17530. /** Adds a rectangle with rounded corners to the path.
  17531. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  17532. @see addRectangle, addTriangle
  17533. */
  17534. template <typename ValueType>
  17535. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  17536. {
  17537. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  17538. }
  17539. /** Adds a triangle to the path.
  17540. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  17541. Note that whether the vertices are specified in clockwise or anticlockwise
  17542. order will affect how the triangle is filled when it overlaps other
  17543. shapes (the winding order setting will affect this of course).
  17544. */
  17545. void addTriangle (float x1, float y1,
  17546. float x2, float y2,
  17547. float x3, float y3);
  17548. /** Adds a quadrilateral to the path.
  17549. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  17550. Note that whether the vertices are specified in clockwise or anticlockwise
  17551. order will affect how the quad is filled when it overlaps other
  17552. shapes (the winding order setting will affect this of course).
  17553. */
  17554. void addQuadrilateral (float x1, float y1,
  17555. float x2, float y2,
  17556. float x3, float y3,
  17557. float x4, float y4);
  17558. /** Adds an ellipse to the path.
  17559. The shape is added as a new sub-path. (Any currently open paths will be left open).
  17560. @see addArc
  17561. */
  17562. void addEllipse (float x, float y, float width, float height);
  17563. /** Adds an elliptical arc to the current path.
  17564. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  17565. or anti-clockwise according to whether the end angle is greater than the start. This means
  17566. that sometimes you may need to use values greater than 2*Pi for the end angle.
  17567. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  17568. @param y the top edge of the rectangle in which the elliptical outline fits
  17569. @param width the width of the rectangle in which the elliptical outline fits
  17570. @param height the height of the rectangle in which the elliptical outline fits
  17571. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  17572. top-centre of the ellipse)
  17573. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  17574. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  17575. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  17576. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  17577. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  17578. it will be added to the current sub-path, continuing from the current postition
  17579. @see addCentredArc, arcTo, addPieSegment, addEllipse
  17580. */
  17581. void addArc (float x, float y, float width, float height,
  17582. float fromRadians,
  17583. float toRadians,
  17584. bool startAsNewSubPath = false);
  17585. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  17586. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  17587. or anti-clockwise according to whether the end angle is greater than the start. This means
  17588. that sometimes you may need to use values greater than 2*Pi for the end angle.
  17589. @param centreX the centre x of the ellipse
  17590. @param centreY the centre y of the ellipse
  17591. @param radiusX the horizontal radius of the ellipse
  17592. @param radiusY the vertical radius of the ellipse
  17593. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  17594. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  17595. top-centre of the ellipse)
  17596. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  17597. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  17598. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  17599. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  17600. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  17601. it will be added to the current sub-path, continuing from the current postition
  17602. @see addArc, arcTo
  17603. */
  17604. void addCentredArc (float centreX, float centreY,
  17605. float radiusX, float radiusY,
  17606. float rotationOfEllipse,
  17607. float fromRadians,
  17608. float toRadians,
  17609. bool startAsNewSubPath = false);
  17610. /** Adds a "pie-chart" shape to the path.
  17611. The shape is added as a new sub-path. (Any currently open paths will be
  17612. left open).
  17613. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  17614. or anti-clockwise according to whether the end angle is greater than the start. This means
  17615. that sometimes you may need to use values greater than 2*Pi for the end angle.
  17616. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  17617. @param y the top edge of the rectangle in which the elliptical outline fits
  17618. @param width the width of the rectangle in which the elliptical outline fits
  17619. @param height the height of the rectangle in which the elliptical outline fits
  17620. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  17621. top-centre of the ellipse)
  17622. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  17623. top-centre of the ellipse)
  17624. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  17625. ellipse at its centre, where this value indicates the inner ellipse's size with
  17626. respect to the outer one.
  17627. @see addArc
  17628. */
  17629. void addPieSegment (float x, float y,
  17630. float width, float height,
  17631. float fromRadians,
  17632. float toRadians,
  17633. float innerCircleProportionalSize);
  17634. /** Adds a line with a specified thickness.
  17635. The line is added as a new closed sub-path. (Any currently open paths will be
  17636. left open).
  17637. @see addArrow
  17638. */
  17639. void addLineSegment (const Line<float>& line, float lineThickness);
  17640. /** Adds a line with an arrowhead on the end.
  17641. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  17642. @see PathStrokeType::createStrokeWithArrowheads
  17643. */
  17644. void addArrow (const Line<float>& line,
  17645. float lineThickness,
  17646. float arrowheadWidth,
  17647. float arrowheadLength);
  17648. /** Adds a polygon shape to the path.
  17649. @see addStar
  17650. */
  17651. void addPolygon (const Point<float>& centre,
  17652. int numberOfSides,
  17653. float radius,
  17654. float startAngle = 0.0f);
  17655. /** Adds a star shape to the path.
  17656. @see addPolygon
  17657. */
  17658. void addStar (const Point<float>& centre,
  17659. int numberOfPoints,
  17660. float innerRadius,
  17661. float outerRadius,
  17662. float startAngle = 0.0f);
  17663. /** Adds a speech-bubble shape to the path.
  17664. @param bodyX the left of the main body area of the bubble
  17665. @param bodyY the top of the main body area of the bubble
  17666. @param bodyW the width of the main body area of the bubble
  17667. @param bodyH the height of the main body area of the bubble
  17668. @param cornerSize the amount by which to round off the corners of the main body rectangle
  17669. @param arrowTipX the x position that the tip of the arrow should connect to
  17670. @param arrowTipY the y position that the tip of the arrow should connect to
  17671. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  17672. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  17673. arrow's base should be - this is a proportional distance between 0 and 1.0
  17674. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  17675. */
  17676. void addBubble (float bodyX, float bodyY,
  17677. float bodyW, float bodyH,
  17678. float cornerSize,
  17679. float arrowTipX,
  17680. float arrowTipY,
  17681. int whichSide,
  17682. float arrowPositionAlongEdgeProportional,
  17683. float arrowWidth);
  17684. /** Adds another path to this one.
  17685. The new path is added as a new sub-path. (Any currently open paths in this
  17686. path will be left open).
  17687. @param pathToAppend the path to add
  17688. */
  17689. void addPath (const Path& pathToAppend);
  17690. /** Adds another path to this one, transforming it on the way in.
  17691. The new path is added as a new sub-path, its points being transformed by the given
  17692. matrix before being added.
  17693. @param pathToAppend the path to add
  17694. @param transformToApply an optional transform to apply to the incoming vertices
  17695. */
  17696. void addPath (const Path& pathToAppend,
  17697. const AffineTransform& transformToApply);
  17698. /** Swaps the contents of this path with another one.
  17699. The internal data of the two paths is swapped over, so this is much faster than
  17700. copying it to a temp variable and back.
  17701. */
  17702. void swapWithPath (Path& other) throw();
  17703. /** Applies a 2D transform to all the vertices in the path.
  17704. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  17705. */
  17706. void applyTransform (const AffineTransform& transform) throw();
  17707. /** Rescales this path to make it fit neatly into a given space.
  17708. This is effectively a quick way of calling
  17709. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  17710. @param x the x position of the rectangle to fit the path inside
  17711. @param y the y position of the rectangle to fit the path inside
  17712. @param width the width of the rectangle to fit the path inside
  17713. @param height the height of the rectangle to fit the path inside
  17714. @param preserveProportions if true, it will fit the path into the space without altering its
  17715. horizontal/vertical scale ratio; if false, it will distort the
  17716. path to fill the specified ratio both horizontally and vertically
  17717. @see applyTransform, getTransformToScaleToFit
  17718. */
  17719. void scaleToFit (float x, float y, float width, float height,
  17720. bool preserveProportions) throw();
  17721. /** Returns a transform that can be used to rescale the path to fit into a given space.
  17722. @param x the x position of the rectangle to fit the path inside
  17723. @param y the y position of the rectangle to fit the path inside
  17724. @param width the width of the rectangle to fit the path inside
  17725. @param height the height of the rectangle to fit the path inside
  17726. @param preserveProportions if true, it will fit the path into the space without altering its
  17727. horizontal/vertical scale ratio; if false, it will distort the
  17728. path to fill the specified ratio both horizontally and vertically
  17729. @param justificationType if the proportions are preseved, the resultant path may be smaller
  17730. than the available rectangle, so this describes how it should be
  17731. positioned within the space.
  17732. @returns an appropriate transformation
  17733. @see applyTransform, scaleToFit
  17734. */
  17735. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  17736. bool preserveProportions,
  17737. const Justification& justificationType = Justification::centred) const;
  17738. /** Creates a version of this path where all sharp corners have been replaced by curves.
  17739. Wherever two lines meet at an angle, this will replace the corner with a curve
  17740. of the given radius.
  17741. */
  17742. const Path createPathWithRoundedCorners (float cornerRadius) const;
  17743. /** Changes the winding-rule to be used when filling the path.
  17744. If set to true (which is the default), then the path uses a non-zero-winding rule
  17745. to determine which points are inside the path. If set to false, it uses an
  17746. alternate-winding rule.
  17747. The winding-rule comes into play when areas of the shape overlap other
  17748. areas, and determines whether the overlapping regions are considered to be
  17749. inside or outside.
  17750. Changing this value just sets a flag - it doesn't affect the contents of the
  17751. path.
  17752. @see isUsingNonZeroWinding
  17753. */
  17754. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  17755. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  17756. The default for a new path is true.
  17757. @see setUsingNonZeroWinding
  17758. */
  17759. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  17760. /** Iterates the lines and curves that a path contains.
  17761. @see Path, PathFlatteningIterator
  17762. */
  17763. class JUCE_API Iterator
  17764. {
  17765. public:
  17766. Iterator (const Path& path);
  17767. ~Iterator();
  17768. /** Moves onto the next element in the path.
  17769. If this returns false, there are no more elements. If it returns true,
  17770. the elementType variable will be set to the type of the current element,
  17771. and some of the x and y variables will be filled in with values.
  17772. */
  17773. bool next();
  17774. enum PathElementType
  17775. {
  17776. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  17777. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  17778. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  17779. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  17780. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  17781. };
  17782. PathElementType elementType;
  17783. float x1, y1, x2, y2, x3, y3;
  17784. private:
  17785. const Path& path;
  17786. size_t index;
  17787. JUCE_DECLARE_NON_COPYABLE (Iterator);
  17788. };
  17789. /** Loads a stored path from a data stream.
  17790. The data in the stream must have been written using writePathToStream().
  17791. Note that this will append the stored path to whatever is currently in
  17792. this path, so you might need to call clear() beforehand.
  17793. @see loadPathFromData, writePathToStream
  17794. */
  17795. void loadPathFromStream (InputStream& source);
  17796. /** Loads a stored path from a block of data.
  17797. This is similar to loadPathFromStream(), but just reads from a block
  17798. of data. Useful if you're including stored shapes in your code as a
  17799. block of static data.
  17800. @see loadPathFromStream, writePathToStream
  17801. */
  17802. void loadPathFromData (const void* data, int numberOfBytes);
  17803. /** Stores the path by writing it out to a stream.
  17804. After writing out a path, you can reload it using loadPathFromStream().
  17805. @see loadPathFromStream, loadPathFromData
  17806. */
  17807. void writePathToStream (OutputStream& destination) const;
  17808. /** Creates a string containing a textual representation of this path.
  17809. @see restoreFromString
  17810. */
  17811. const String toString() const;
  17812. /** Restores this path from a string that was created with the toString() method.
  17813. @see toString()
  17814. */
  17815. void restoreFromString (const String& stringVersion);
  17816. private:
  17817. friend class PathFlatteningIterator;
  17818. friend class Path::Iterator;
  17819. ArrayAllocationBase <float, DummyCriticalSection> data;
  17820. size_t numElements;
  17821. float pathXMin, pathXMax, pathYMin, pathYMax;
  17822. bool useNonZeroWinding;
  17823. static const float lineMarker;
  17824. static const float moveMarker;
  17825. static const float quadMarker;
  17826. static const float cubicMarker;
  17827. static const float closeSubPathMarker;
  17828. JUCE_LEAK_DETECTOR (Path);
  17829. };
  17830. #endif // __JUCE_PATH_JUCEHEADER__
  17831. /*** End of inlined file: juce_Path.h ***/
  17832. class Font;
  17833. /** A typeface represents a size-independent font.
  17834. This base class is abstract, but calling createSystemTypefaceFor() will return
  17835. a platform-specific subclass that can be used.
  17836. The CustomTypeface subclass allow you to build your own typeface, and to
  17837. load and save it in the Juce typeface format.
  17838. Normally you should never need to deal directly with Typeface objects - the Font
  17839. class does everything you typically need for rendering text.
  17840. @see CustomTypeface, Font
  17841. */
  17842. class JUCE_API Typeface : public ReferenceCountedObject
  17843. {
  17844. public:
  17845. /** A handy typedef for a pointer to a typeface. */
  17846. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  17847. /** Returns the name of the typeface.
  17848. @see Font::getTypefaceName
  17849. */
  17850. const String getName() const throw() { return name; }
  17851. /** Creates a new system typeface. */
  17852. static const Ptr createSystemTypefaceFor (const Font& font);
  17853. /** Destructor. */
  17854. virtual ~Typeface();
  17855. /** Returns true if this typeface can be used to render the specified font.
  17856. When called, the font will already have been checked to make sure that its name and
  17857. style flags match the typeface.
  17858. */
  17859. virtual bool isSuitableForFont (const Font&) const { return true; }
  17860. /** Returns the ascent of the font, as a proportion of its height.
  17861. The height is considered to always be normalised as 1.0, so this will be a
  17862. value less that 1.0, indicating the proportion of the font that lies above
  17863. its baseline.
  17864. */
  17865. virtual float getAscent() const = 0;
  17866. /** Returns the descent of the font, as a proportion of its height.
  17867. The height is considered to always be normalised as 1.0, so this will be a
  17868. value less that 1.0, indicating the proportion of the font that lies below
  17869. its baseline.
  17870. */
  17871. virtual float getDescent() const = 0;
  17872. /** Measures the width of a line of text.
  17873. The distance returned is based on the font having an normalised height of 1.0.
  17874. You should never need to call this directly! Use Font::getStringWidth() instead!
  17875. */
  17876. virtual float getStringWidth (const String& text) = 0;
  17877. /** Converts a line of text into its glyph numbers and their positions.
  17878. The distances returned are based on the font having an normalised height of 1.0.
  17879. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  17880. */
  17881. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  17882. /** Returns the outline for a glyph.
  17883. The path returned will be normalised to a font height of 1.0.
  17884. */
  17885. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  17886. /** Returns true if the typeface uses hinting. */
  17887. virtual bool isHinted() const { return false; }
  17888. /** Changes the number of fonts that are cached in memory. */
  17889. static void setTypefaceCacheSize (int numFontsToCache);
  17890. protected:
  17891. String name;
  17892. bool isFallbackFont;
  17893. explicit Typeface (const String& name) throw();
  17894. static const Ptr getFallbackTypeface();
  17895. private:
  17896. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  17897. };
  17898. /** A typeface that can be populated with custom glyphs.
  17899. You can create a CustomTypeface if you need one that contains your own glyphs,
  17900. or if you need to load a typeface from a Juce-formatted binary stream.
  17901. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  17902. to copy glyphs into this face.
  17903. @see Typeface, Font
  17904. */
  17905. class JUCE_API CustomTypeface : public Typeface
  17906. {
  17907. public:
  17908. /** Creates a new, empty typeface. */
  17909. CustomTypeface();
  17910. /** Loads a typeface from a previously saved stream.
  17911. The stream must have been created by writeToStream().
  17912. @see writeToStream
  17913. */
  17914. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  17915. /** Destructor. */
  17916. ~CustomTypeface();
  17917. /** Resets this typeface, deleting all its glyphs and settings. */
  17918. void clear();
  17919. /** Sets the vital statistics for the typeface.
  17920. @param name the typeface's name
  17921. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  17922. the value that will be returned by Typeface::getAscent(). The
  17923. descent is assumed to be (1.0 - ascent)
  17924. @param isBold should be true if the typeface is bold
  17925. @param isItalic should be true if the typeface is italic
  17926. @param defaultCharacter the character to be used as a replacement if there's
  17927. no glyph available for the character that's being drawn
  17928. */
  17929. void setCharacteristics (const String& name, float ascent,
  17930. bool isBold, bool isItalic,
  17931. juce_wchar defaultCharacter) throw();
  17932. /** Adds a glyph to the typeface.
  17933. The path that is passed in is normalised so that the font height is 1.0, and its
  17934. origin is the anchor point of the character on its baseline.
  17935. The width is the nominal width of the character, and any extra kerning values that
  17936. are specified will be added to this width.
  17937. */
  17938. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  17939. /** Specifies an extra kerning amount to be used between a pair of characters.
  17940. The amount will be added to the nominal width of the first character when laying out a string.
  17941. */
  17942. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  17943. /** Adds a range of glyphs from another typeface.
  17944. This will attempt to pull in the paths and kerning information from another typeface and
  17945. add it to this one.
  17946. */
  17947. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  17948. /** Saves this typeface as a Juce-formatted font file.
  17949. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  17950. constructor.
  17951. */
  17952. bool writeToStream (OutputStream& outputStream);
  17953. // The following methods implement the basic Typeface behaviour.
  17954. float getAscent() const;
  17955. float getDescent() const;
  17956. float getStringWidth (const String& text);
  17957. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  17958. bool getOutlineForGlyph (int glyphNumber, Path& path);
  17959. int getGlyphForCharacter (juce_wchar character);
  17960. protected:
  17961. juce_wchar defaultCharacter;
  17962. float ascent;
  17963. bool isBold, isItalic;
  17964. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  17965. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  17966. particular character and there's no corresponding glyph, they'll call this
  17967. method so that a subclass can try to add that glyph, returning true if it
  17968. manages to do so.
  17969. */
  17970. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  17971. private:
  17972. class GlyphInfo;
  17973. friend class OwnedArray<GlyphInfo>;
  17974. OwnedArray <GlyphInfo> glyphs;
  17975. short lookupTable [128];
  17976. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  17977. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  17978. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  17979. };
  17980. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  17981. /*** End of inlined file: juce_Typeface.h ***/
  17982. class LowLevelGraphicsContext;
  17983. /**
  17984. Represents a particular font, including its size, style, etc.
  17985. Apart from the typeface to be used, a Font object also dictates whether
  17986. the font is bold, italic, underlined, how big it is, and its kerning and
  17987. horizontal scale factor.
  17988. @see Typeface
  17989. */
  17990. class JUCE_API Font
  17991. {
  17992. public:
  17993. /** A combination of these values is used by the constructor to specify the
  17994. style of font to use.
  17995. */
  17996. enum FontStyleFlags
  17997. {
  17998. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  17999. bold = 1, /**< boldens the font. @see setStyleFlags */
  18000. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  18001. underlined = 4 /**< underlines the font. @see setStyleFlags */
  18002. };
  18003. /** Creates a sans-serif font in a given size.
  18004. @param fontHeight the height in pixels (can be fractional)
  18005. @param styleFlags the style to use - this can be a combination of the
  18006. Font::bold, Font::italic and Font::underlined, or
  18007. just Font::plain for the normal style.
  18008. @see FontStyleFlags, getDefaultSansSerifFontName
  18009. */
  18010. Font (float fontHeight, int styleFlags = plain);
  18011. /** Creates a font with a given typeface and parameters.
  18012. @param typefaceName the name of the typeface to use
  18013. @param fontHeight the height in pixels (can be fractional)
  18014. @param styleFlags the style to use - this can be a combination of the
  18015. Font::bold, Font::italic and Font::underlined, or
  18016. just Font::plain for the normal style.
  18017. @see FontStyleFlags, getDefaultSansSerifFontName
  18018. */
  18019. Font (const String& typefaceName, float fontHeight, int styleFlags);
  18020. /** Creates a copy of another Font object. */
  18021. Font (const Font& other) throw();
  18022. /** Creates a font for a typeface. */
  18023. Font (const Typeface::Ptr& typeface);
  18024. /** Creates a basic sans-serif font at a default height.
  18025. You should use one of the other constructors for creating a font that you're planning
  18026. on drawing with - this constructor is here to help initialise objects before changing
  18027. the font's settings later.
  18028. */
  18029. Font();
  18030. /** Copies this font from another one. */
  18031. Font& operator= (const Font& other) throw();
  18032. bool operator== (const Font& other) const throw();
  18033. bool operator!= (const Font& other) const throw();
  18034. /** Destructor. */
  18035. ~Font() throw();
  18036. /** Changes the name of the typeface family.
  18037. e.g. "Arial", "Courier", etc.
  18038. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  18039. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  18040. but are generic names that are used to represent the various default fonts.
  18041. If you need to know the exact typeface name being used, you can call
  18042. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  18043. If a suitable font isn't found on the machine, it'll just use a default instead.
  18044. */
  18045. void setTypefaceName (const String& faceName);
  18046. /** Returns the name of the typeface family that this font uses.
  18047. e.g. "Arial", "Courier", etc.
  18048. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  18049. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  18050. but are generic names that are used to represent the various default fonts.
  18051. If you need to know the exact typeface name being used, you can call
  18052. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  18053. */
  18054. const String& getTypefaceName() const throw() { return font->typefaceName; }
  18055. /** Returns a typeface name that represents the default sans-serif font.
  18056. This is also the typeface that will be used when a font is created without
  18057. specifying any typeface details.
  18058. Note that this method just returns a generic placeholder string that means "the default
  18059. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  18060. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  18061. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  18062. */
  18063. static const String getDefaultSansSerifFontName();
  18064. /** Returns a typeface name that represents the default sans-serif font.
  18065. Note that this method just returns a generic placeholder string that means "the default
  18066. serif font" - it's not the actual name of this font. To get the actual name, use
  18067. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  18068. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  18069. */
  18070. static const String getDefaultSerifFontName();
  18071. /** Returns a typeface name that represents the default sans-serif font.
  18072. Note that this method just returns a generic placeholder string that means "the default
  18073. monospaced font" - it's not the actual name of this font. To get the actual name, use
  18074. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  18075. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  18076. */
  18077. static const String getDefaultMonospacedFontName();
  18078. /** Returns the typeface names of the default fonts on the current platform. */
  18079. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  18080. /** Returns the total height of this font.
  18081. This is the maximum height, from the top of the ascent to the bottom of the
  18082. descenders.
  18083. @see setHeight, setHeightWithoutChangingWidth, getAscent
  18084. */
  18085. float getHeight() const throw() { return font->height; }
  18086. /** Changes the font's height.
  18087. @see getHeight, setHeightWithoutChangingWidth
  18088. */
  18089. void setHeight (float newHeight);
  18090. /** Changes the font's height without changing its width.
  18091. This alters the horizontal scale to compensate for the change in height.
  18092. */
  18093. void setHeightWithoutChangingWidth (float newHeight);
  18094. /** Returns the height of the font above its baseline.
  18095. This is the maximum height from the baseline to the top.
  18096. @see getHeight, getDescent
  18097. */
  18098. float getAscent() const;
  18099. /** Returns the amount that the font descends below its baseline.
  18100. This is calculated as (getHeight() - getAscent()).
  18101. @see getAscent, getHeight
  18102. */
  18103. float getDescent() const;
  18104. /** Returns the font's style flags.
  18105. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  18106. enum, to describe whether the font is bold, italic, etc.
  18107. @see FontStyleFlags
  18108. */
  18109. int getStyleFlags() const throw() { return font->styleFlags; }
  18110. /** Changes the font's style.
  18111. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  18112. enum, to set the font's properties
  18113. @see FontStyleFlags
  18114. */
  18115. void setStyleFlags (int newFlags);
  18116. /** Makes the font bold or non-bold. */
  18117. void setBold (bool shouldBeBold);
  18118. /** Returns a copy of this font with the bold attribute set. */
  18119. const Font boldened() const;
  18120. /** Returns true if the font is bold. */
  18121. bool isBold() const throw();
  18122. /** Makes the font italic or non-italic. */
  18123. void setItalic (bool shouldBeItalic);
  18124. /** Returns a copy of this font with the italic attribute set. */
  18125. const Font italicised() const;
  18126. /** Returns true if the font is italic. */
  18127. bool isItalic() const throw();
  18128. /** Makes the font underlined or non-underlined. */
  18129. void setUnderline (bool shouldBeUnderlined);
  18130. /** Returns true if the font is underlined. */
  18131. bool isUnderlined() const throw();
  18132. /** Changes the font's horizontal scale factor.
  18133. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  18134. narrower, greater than 1.0 will be stretched out.
  18135. */
  18136. void setHorizontalScale (float scaleFactor);
  18137. /** Returns the font's horizontal scale.
  18138. A value of 1.0 is the normal scale, less than this will be narrower, greater
  18139. than 1.0 will be stretched out.
  18140. @see setHorizontalScale
  18141. */
  18142. float getHorizontalScale() const throw() { return font->horizontalScale; }
  18143. /** Changes the font's kerning.
  18144. @param extraKerning a multiple of the font's height that will be added
  18145. to space between the characters. So a value of zero is
  18146. normal spacing, positive values spread the letters out,
  18147. negative values make them closer together.
  18148. */
  18149. void setExtraKerningFactor (float extraKerning);
  18150. /** Returns the font's kerning.
  18151. This is the extra space added between adjacent characters, as a proportion
  18152. of the font's height.
  18153. A value of zero is normal spacing, positive values will spread the letters
  18154. out more, and negative values make them closer together.
  18155. */
  18156. float getExtraKerningFactor() const throw() { return font->kerning; }
  18157. /** Changes all the font's characteristics with one call. */
  18158. void setSizeAndStyle (float newHeight,
  18159. int newStyleFlags,
  18160. float newHorizontalScale,
  18161. float newKerningAmount);
  18162. /** Returns the total width of a string as it would be drawn using this font.
  18163. For a more accurate floating-point result, use getStringWidthFloat().
  18164. */
  18165. int getStringWidth (const String& text) const;
  18166. /** Returns the total width of a string as it would be drawn using this font.
  18167. @see getStringWidth
  18168. */
  18169. float getStringWidthFloat (const String& text) const;
  18170. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  18171. An extra x offset is added at the end of the run, to indicate where the right hand
  18172. edge of the last character is.
  18173. */
  18174. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  18175. /** Returns the typeface used by this font.
  18176. Note that the object returned may go out of scope if this font is deleted
  18177. or has its style changed.
  18178. */
  18179. Typeface* getTypeface() const;
  18180. /** Creates an array of Font objects to represent all the fonts on the system.
  18181. If you just need the names of the typefaces, you can also use
  18182. findAllTypefaceNames() instead.
  18183. @param results the array to which new Font objects will be added.
  18184. */
  18185. static void findFonts (Array<Font>& results);
  18186. /** Returns a list of all the available typeface names.
  18187. The names returned can be passed into setTypefaceName().
  18188. You can use this instead of findFonts() if you only need their names, and not
  18189. font objects.
  18190. */
  18191. static const StringArray findAllTypefaceNames();
  18192. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  18193. in the requested typeface.
  18194. */
  18195. static const String getFallbackFontName();
  18196. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  18197. available in whatever font you're trying to use.
  18198. */
  18199. static void setFallbackFontName (const String& name);
  18200. /** Creates a string to describe this font.
  18201. The string will contain information to describe the font's typeface, size, and
  18202. style. To recreate the font from this string, use fromString().
  18203. */
  18204. const String toString() const;
  18205. /** Recreates a font from its stringified encoding.
  18206. This method takes a string that was created by toString(), and recreates the
  18207. original font.
  18208. */
  18209. static const Font fromString (const String& fontDescription);
  18210. private:
  18211. friend class FontGlyphAlphaMap;
  18212. friend class TypefaceCache;
  18213. class SharedFontInternal : public ReferenceCountedObject
  18214. {
  18215. public:
  18216. SharedFontInternal (float height, int styleFlags) throw();
  18217. SharedFontInternal (const String& typefaceName, float height, int styleFlags) throw();
  18218. SharedFontInternal (const Typeface::Ptr& typeface) throw();
  18219. SharedFontInternal (const SharedFontInternal& other) throw();
  18220. bool operator== (const SharedFontInternal&) const throw();
  18221. String typefaceName;
  18222. float height, horizontalScale, kerning, ascent;
  18223. int styleFlags;
  18224. Typeface::Ptr typeface;
  18225. };
  18226. ReferenceCountedObjectPtr <SharedFontInternal> font;
  18227. void dupeInternalIfShared();
  18228. JUCE_LEAK_DETECTOR (Font);
  18229. };
  18230. #endif // __JUCE_FONT_JUCEHEADER__
  18231. /*** End of inlined file: juce_Font.h ***/
  18232. /*** Start of inlined file: juce_PathStrokeType.h ***/
  18233. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  18234. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  18235. /**
  18236. Describes a type of stroke used to render a solid outline along a path.
  18237. A PathStrokeType object can be used directly to create the shape of an outline
  18238. around a path, and is used by Graphics::strokePath to specify the type of
  18239. stroke to draw.
  18240. @see Path, Graphics::strokePath
  18241. */
  18242. class JUCE_API PathStrokeType
  18243. {
  18244. public:
  18245. /** The type of shape to use for the corners between two adjacent line segments. */
  18246. enum JointStyle
  18247. {
  18248. mitered, /**< Indicates that corners should be drawn with sharp joints.
  18249. Note that for angles that curve back on themselves, drawing a
  18250. mitre could require extending the point too far away from the
  18251. path, so a mitre limit is imposed and any corners that exceed it
  18252. are drawn as bevelled instead. */
  18253. curved, /**< Indicates that corners should be drawn as rounded-off. */
  18254. beveled /**< Indicates that corners should be drawn with a line flattening their
  18255. outside edge. */
  18256. };
  18257. /** The type shape to use for the ends of lines. */
  18258. enum EndCapStyle
  18259. {
  18260. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  18261. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  18262. the thickness of the stroke. */
  18263. rounded /**< Ends of lines are rounded-off with a circular shape. */
  18264. };
  18265. /** Creates a stroke type.
  18266. @param strokeThickness the width of the line to use
  18267. @param jointStyle the type of joints to use for corners
  18268. @param endStyle the type of end-caps to use for the ends of open paths.
  18269. */
  18270. PathStrokeType (float strokeThickness,
  18271. JointStyle jointStyle = mitered,
  18272. EndCapStyle endStyle = butt) throw();
  18273. /** Createes a copy of another stroke type. */
  18274. PathStrokeType (const PathStrokeType& other) throw();
  18275. /** Copies another stroke onto this one. */
  18276. PathStrokeType& operator= (const PathStrokeType& other) throw();
  18277. /** Destructor. */
  18278. ~PathStrokeType() throw();
  18279. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  18280. @param destPath the resultant stroked outline shape will be copied into this path.
  18281. Note that it's ok for the source and destination Paths to be
  18282. the same object, so you can easily turn a path into a stroked version
  18283. of itself.
  18284. @param sourcePath the path to use as the source
  18285. @param transform an optional transform to apply to the points from the source path
  18286. as they are being used
  18287. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  18288. a higher resolution, which improves the quality if you'll later want
  18289. to enlarge the stroked path. So for example, if you're planning on drawing
  18290. the stroke at 3x the size that you're creating it, you should set this to 3.
  18291. @see createDashedStroke
  18292. */
  18293. void createStrokedPath (Path& destPath,
  18294. const Path& sourcePath,
  18295. const AffineTransform& transform = AffineTransform::identity,
  18296. float extraAccuracy = 1.0f) const;
  18297. /** Applies this stroke type to a path, creating a dashed line.
  18298. This is similar to createStrokedPath, but uses the array passed in to
  18299. break the stroke up into a series of dashes.
  18300. @param destPath the resultant stroked outline shape will be copied into this path.
  18301. Note that it's ok for the source and destination Paths to be
  18302. the same object, so you can easily turn a path into a stroked version
  18303. of itself.
  18304. @param sourcePath the path to use as the source
  18305. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  18306. a line of length 2, then skip a length of 3, then add a line of length 4,
  18307. skip 5, and keep repeating this pattern.
  18308. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  18309. an even number, otherwise the pattern will get out of step as it
  18310. repeats.
  18311. @param transform an optional transform to apply to the points from the source path
  18312. as they are being used
  18313. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  18314. a higher resolution, which improves the quality if you'll later want
  18315. to enlarge the stroked path. So for example, if you're planning on drawing
  18316. the stroke at 3x the size that you're creating it, you should set this to 3.
  18317. */
  18318. void createDashedStroke (Path& destPath,
  18319. const Path& sourcePath,
  18320. const float* dashLengths,
  18321. int numDashLengths,
  18322. const AffineTransform& transform = AffineTransform::identity,
  18323. float extraAccuracy = 1.0f) const;
  18324. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  18325. @param destPath the resultant stroked outline shape will be copied into this path.
  18326. Note that it's ok for the source and destination Paths to be
  18327. the same object, so you can easily turn a path into a stroked version
  18328. of itself.
  18329. @param sourcePath the path to use as the source
  18330. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  18331. @param arrowheadStartLength the length of the arrowhead at the start of the path
  18332. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  18333. @param arrowheadEndLength the length of the arrowhead at the end of the path
  18334. @param transform an optional transform to apply to the points from the source path
  18335. as they are being used
  18336. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  18337. a higher resolution, which improves the quality if you'll later want
  18338. to enlarge the stroked path. So for example, if you're planning on drawing
  18339. the stroke at 3x the size that you're creating it, you should set this to 3.
  18340. @see createDashedStroke
  18341. */
  18342. void createStrokeWithArrowheads (Path& destPath,
  18343. const Path& sourcePath,
  18344. float arrowheadStartWidth, float arrowheadStartLength,
  18345. float arrowheadEndWidth, float arrowheadEndLength,
  18346. const AffineTransform& transform = AffineTransform::identity,
  18347. float extraAccuracy = 1.0f) const;
  18348. /** Returns the stroke thickness. */
  18349. float getStrokeThickness() const throw() { return thickness; }
  18350. /** Sets the stroke thickness. */
  18351. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  18352. /** Returns the joint style. */
  18353. JointStyle getJointStyle() const throw() { return jointStyle; }
  18354. /** Sets the joint style. */
  18355. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  18356. /** Returns the end-cap style. */
  18357. EndCapStyle getEndStyle() const throw() { return endStyle; }
  18358. /** Sets the end-cap style. */
  18359. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  18360. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  18361. bool operator== (const PathStrokeType& other) const throw();
  18362. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  18363. bool operator!= (const PathStrokeType& other) const throw();
  18364. private:
  18365. float thickness;
  18366. JointStyle jointStyle;
  18367. EndCapStyle endStyle;
  18368. JUCE_LEAK_DETECTOR (PathStrokeType);
  18369. };
  18370. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  18371. /*** End of inlined file: juce_PathStrokeType.h ***/
  18372. /*** Start of inlined file: juce_Colours.h ***/
  18373. #ifndef __JUCE_COLOURS_JUCEHEADER__
  18374. #define __JUCE_COLOURS_JUCEHEADER__
  18375. /*** Start of inlined file: juce_Colour.h ***/
  18376. #ifndef __JUCE_COLOUR_JUCEHEADER__
  18377. #define __JUCE_COLOUR_JUCEHEADER__
  18378. /*** Start of inlined file: juce_PixelFormats.h ***/
  18379. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  18380. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  18381. #ifndef DOXYGEN
  18382. #if JUCE_MSVC
  18383. #pragma pack (push, 1)
  18384. #define PACKED
  18385. #elif JUCE_GCC
  18386. #define PACKED __attribute__((packed))
  18387. #else
  18388. #define PACKED
  18389. #endif
  18390. #endif
  18391. class PixelRGB;
  18392. class PixelAlpha;
  18393. /**
  18394. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  18395. operations with it.
  18396. This is used internally by the imaging classes.
  18397. @see PixelRGB
  18398. */
  18399. class JUCE_API PixelARGB
  18400. {
  18401. public:
  18402. /** Creates a pixel without defining its colour. */
  18403. PixelARGB() throw() {}
  18404. ~PixelARGB() throw() {}
  18405. /** Creates a pixel from a 32-bit argb value.
  18406. */
  18407. PixelARGB (const uint32 argb_) throw()
  18408. : argb (argb_)
  18409. {
  18410. }
  18411. forcedinline uint32 getARGB() const throw() { return argb; }
  18412. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  18413. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  18414. forcedinline uint8 getAlpha() const throw() { return components.a; }
  18415. forcedinline uint8 getRed() const throw() { return components.r; }
  18416. forcedinline uint8 getGreen() const throw() { return components.g; }
  18417. forcedinline uint8 getBlue() const throw() { return components.b; }
  18418. /** Blends another pixel onto this one.
  18419. This takes into account the opacity of the pixel being overlaid, and blends
  18420. it accordingly.
  18421. */
  18422. forcedinline void blend (const PixelARGB& src) throw()
  18423. {
  18424. uint32 sargb = src.getARGB();
  18425. const uint32 alpha = 0x100 - (sargb >> 24);
  18426. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  18427. sargb += 0xff00ff00 & (getAG() * alpha);
  18428. argb = sargb;
  18429. }
  18430. /** Blends another pixel onto this one.
  18431. This takes into account the opacity of the pixel being overlaid, and blends
  18432. it accordingly.
  18433. */
  18434. forcedinline void blend (const PixelAlpha& src) throw();
  18435. /** Blends another pixel onto this one.
  18436. This takes into account the opacity of the pixel being overlaid, and blends
  18437. it accordingly.
  18438. */
  18439. forcedinline void blend (const PixelRGB& src) throw();
  18440. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  18441. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  18442. being used, so this can blend semi-transparently from a PixelRGB argument.
  18443. */
  18444. template <class Pixel>
  18445. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  18446. {
  18447. ++extraAlpha;
  18448. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  18449. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  18450. const uint32 alpha = 0x100 - (sargb >> 24);
  18451. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  18452. sargb += 0xff00ff00 & (getAG() * alpha);
  18453. argb = sargb;
  18454. }
  18455. /** Blends another pixel with this one, creating a colour that is somewhere
  18456. between the two, as specified by the amount.
  18457. */
  18458. template <class Pixel>
  18459. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  18460. {
  18461. uint32 drb = getRB();
  18462. drb += (((src.getRB() - drb) * amount) >> 8);
  18463. drb &= 0x00ff00ff;
  18464. uint32 dag = getAG();
  18465. dag += (((src.getAG() - dag) * amount) >> 8);
  18466. dag &= 0x00ff00ff;
  18467. dag <<= 8;
  18468. dag |= drb;
  18469. argb = dag;
  18470. }
  18471. /** Copies another pixel colour over this one.
  18472. This doesn't blend it - this colour is simply replaced by the other one.
  18473. */
  18474. template <class Pixel>
  18475. forcedinline void set (const Pixel& src) throw()
  18476. {
  18477. argb = src.getARGB();
  18478. }
  18479. /** Replaces the colour's alpha value with another one. */
  18480. forcedinline void setAlpha (const uint8 newAlpha) throw()
  18481. {
  18482. components.a = newAlpha;
  18483. }
  18484. /** Multiplies the colour's alpha value with another one. */
  18485. forcedinline void multiplyAlpha (int multiplier) throw()
  18486. {
  18487. ++multiplier;
  18488. argb = ((multiplier * getAG()) & 0xff00ff00)
  18489. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  18490. }
  18491. forcedinline void multiplyAlpha (const float multiplier) throw()
  18492. {
  18493. multiplyAlpha ((int) (multiplier * 256.0f));
  18494. }
  18495. /** Sets the pixel's colour from individual components. */
  18496. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  18497. {
  18498. components.b = b;
  18499. components.g = g;
  18500. components.r = r;
  18501. components.a = a;
  18502. }
  18503. /** Premultiplies the pixel's RGB values by its alpha. */
  18504. forcedinline void premultiply() throw()
  18505. {
  18506. const uint32 alpha = components.a;
  18507. if (alpha < 0xff)
  18508. {
  18509. if (alpha == 0)
  18510. {
  18511. components.b = 0;
  18512. components.g = 0;
  18513. components.r = 0;
  18514. }
  18515. else
  18516. {
  18517. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  18518. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  18519. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  18520. }
  18521. }
  18522. }
  18523. /** Unpremultiplies the pixel's RGB values. */
  18524. forcedinline void unpremultiply() throw()
  18525. {
  18526. const uint32 alpha = components.a;
  18527. if (alpha < 0xff)
  18528. {
  18529. if (alpha == 0)
  18530. {
  18531. components.b = 0;
  18532. components.g = 0;
  18533. components.r = 0;
  18534. }
  18535. else
  18536. {
  18537. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  18538. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  18539. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  18540. }
  18541. }
  18542. }
  18543. forcedinline void desaturate() throw()
  18544. {
  18545. if (components.a < 0xff && components.a > 0)
  18546. {
  18547. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  18548. components.r = components.g = components.b
  18549. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  18550. }
  18551. else
  18552. {
  18553. components.r = components.g = components.b
  18554. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  18555. }
  18556. }
  18557. /** The indexes of the different components in the byte layout of this type of colour. */
  18558. #if JUCE_BIG_ENDIAN
  18559. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  18560. #else
  18561. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  18562. #endif
  18563. private:
  18564. union
  18565. {
  18566. uint32 argb;
  18567. struct
  18568. {
  18569. #if JUCE_BIG_ENDIAN
  18570. uint8 a : 8, r : 8, g : 8, b : 8;
  18571. #else
  18572. uint8 b, g, r, a;
  18573. #endif
  18574. } PACKED components;
  18575. };
  18576. }
  18577. #ifndef DOXYGEN
  18578. PACKED
  18579. #endif
  18580. ;
  18581. /**
  18582. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  18583. This is used internally by the imaging classes.
  18584. @see PixelARGB
  18585. */
  18586. class JUCE_API PixelRGB
  18587. {
  18588. public:
  18589. /** Creates a pixel without defining its colour. */
  18590. PixelRGB() throw() {}
  18591. ~PixelRGB() throw() {}
  18592. /** Creates a pixel from a 32-bit argb value.
  18593. (The argb format is that used by PixelARGB)
  18594. */
  18595. PixelRGB (const uint32 argb) throw()
  18596. {
  18597. r = (uint8) (argb >> 16);
  18598. g = (uint8) (argb >> 8);
  18599. b = (uint8) (argb);
  18600. }
  18601. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  18602. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  18603. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  18604. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  18605. forcedinline uint8 getRed() const throw() { return r; }
  18606. forcedinline uint8 getGreen() const throw() { return g; }
  18607. forcedinline uint8 getBlue() const throw() { return b; }
  18608. /** Blends another pixel onto this one.
  18609. This takes into account the opacity of the pixel being overlaid, and blends
  18610. it accordingly.
  18611. */
  18612. forcedinline void blend (const PixelARGB& src) throw()
  18613. {
  18614. uint32 sargb = src.getARGB();
  18615. const uint32 alpha = 0x100 - (sargb >> 24);
  18616. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  18617. sargb += 0x0000ff00 & (g * alpha);
  18618. r = (uint8) (sargb >> 16);
  18619. g = (uint8) (sargb >> 8);
  18620. b = (uint8) sargb;
  18621. }
  18622. forcedinline void blend (const PixelRGB& src) throw()
  18623. {
  18624. set (src);
  18625. }
  18626. forcedinline void blend (const PixelAlpha& src) throw();
  18627. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  18628. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  18629. being used, so this can blend semi-transparently from a PixelRGB argument.
  18630. */
  18631. template <class Pixel>
  18632. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  18633. {
  18634. ++extraAlpha;
  18635. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  18636. const uint32 sag = extraAlpha * src.getAG();
  18637. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  18638. const uint32 alpha = 0x100 - (sargb >> 24);
  18639. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  18640. sargb += 0x0000ff00 & (g * alpha);
  18641. b = (uint8) sargb;
  18642. g = (uint8) (sargb >> 8);
  18643. r = (uint8) (sargb >> 16);
  18644. }
  18645. /** Blends another pixel with this one, creating a colour that is somewhere
  18646. between the two, as specified by the amount.
  18647. */
  18648. template <class Pixel>
  18649. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  18650. {
  18651. uint32 drb = getRB();
  18652. drb += (((src.getRB() - drb) * amount) >> 8);
  18653. uint32 dag = getAG();
  18654. dag += (((src.getAG() - dag) * amount) >> 8);
  18655. b = (uint8) drb;
  18656. g = (uint8) dag;
  18657. r = (uint8) (drb >> 16);
  18658. }
  18659. /** Copies another pixel colour over this one.
  18660. This doesn't blend it - this colour is simply replaced by the other one.
  18661. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  18662. is thrown away.
  18663. */
  18664. template <class Pixel>
  18665. forcedinline void set (const Pixel& src) throw()
  18666. {
  18667. b = src.getBlue();
  18668. g = src.getGreen();
  18669. r = src.getRed();
  18670. }
  18671. /** This method is included for compatibility with the PixelARGB class. */
  18672. forcedinline void setAlpha (const uint8) throw() {}
  18673. /** Multiplies the colour's alpha value with another one. */
  18674. forcedinline void multiplyAlpha (int) throw() {}
  18675. /** Sets the pixel's colour from individual components. */
  18676. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  18677. {
  18678. r = r_;
  18679. g = g_;
  18680. b = b_;
  18681. }
  18682. /** Premultiplies the pixel's RGB values by its alpha. */
  18683. forcedinline void premultiply() throw() {}
  18684. /** Unpremultiplies the pixel's RGB values. */
  18685. forcedinline void unpremultiply() throw() {}
  18686. forcedinline void desaturate() throw()
  18687. {
  18688. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  18689. }
  18690. /** The indexes of the different components in the byte layout of this type of colour. */
  18691. #if JUCE_MAC
  18692. enum { indexR = 0, indexG = 1, indexB = 2 };
  18693. #else
  18694. enum { indexR = 2, indexG = 1, indexB = 0 };
  18695. #endif
  18696. private:
  18697. #if JUCE_MAC
  18698. uint8 r, g, b;
  18699. #else
  18700. uint8 b, g, r;
  18701. #endif
  18702. }
  18703. #ifndef DOXYGEN
  18704. PACKED
  18705. #endif
  18706. ;
  18707. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  18708. {
  18709. set (src);
  18710. }
  18711. /**
  18712. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  18713. This is used internally by the imaging classes.
  18714. @see PixelARGB, PixelRGB
  18715. */
  18716. class JUCE_API PixelAlpha
  18717. {
  18718. public:
  18719. /** Creates a pixel without defining its colour. */
  18720. PixelAlpha() throw() {}
  18721. ~PixelAlpha() throw() {}
  18722. /** Creates a pixel from a 32-bit argb value.
  18723. (The argb format is that used by PixelARGB)
  18724. */
  18725. PixelAlpha (const uint32 argb) throw()
  18726. {
  18727. a = (uint8) (argb >> 24);
  18728. }
  18729. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  18730. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  18731. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  18732. forcedinline uint8 getAlpha() const throw() { return a; }
  18733. forcedinline uint8 getRed() const throw() { return 0; }
  18734. forcedinline uint8 getGreen() const throw() { return 0; }
  18735. forcedinline uint8 getBlue() const throw() { return 0; }
  18736. /** Blends another pixel onto this one.
  18737. This takes into account the opacity of the pixel being overlaid, and blends
  18738. it accordingly.
  18739. */
  18740. template <class Pixel>
  18741. forcedinline void blend (const Pixel& src) throw()
  18742. {
  18743. const int srcA = src.getAlpha();
  18744. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  18745. }
  18746. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  18747. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  18748. being used, so this can blend semi-transparently from a PixelRGB argument.
  18749. */
  18750. template <class Pixel>
  18751. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  18752. {
  18753. ++extraAlpha;
  18754. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  18755. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  18756. }
  18757. /** Blends another pixel with this one, creating a colour that is somewhere
  18758. between the two, as specified by the amount.
  18759. */
  18760. template <class Pixel>
  18761. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  18762. {
  18763. a += ((src,getAlpha() - a) * amount) >> 8;
  18764. }
  18765. /** Copies another pixel colour over this one.
  18766. This doesn't blend it - this colour is simply replaced by the other one.
  18767. */
  18768. template <class Pixel>
  18769. forcedinline void set (const Pixel& src) throw()
  18770. {
  18771. a = src.getAlpha();
  18772. }
  18773. /** Replaces the colour's alpha value with another one. */
  18774. forcedinline void setAlpha (const uint8 newAlpha) throw()
  18775. {
  18776. a = newAlpha;
  18777. }
  18778. /** Multiplies the colour's alpha value with another one. */
  18779. forcedinline void multiplyAlpha (int multiplier) throw()
  18780. {
  18781. ++multiplier;
  18782. a = (uint8) ((a * multiplier) >> 8);
  18783. }
  18784. forcedinline void multiplyAlpha (const float multiplier) throw()
  18785. {
  18786. a = (uint8) (a * multiplier);
  18787. }
  18788. /** Sets the pixel's colour from individual components. */
  18789. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  18790. {
  18791. a = a_;
  18792. }
  18793. /** Premultiplies the pixel's RGB values by its alpha. */
  18794. forcedinline void premultiply() throw()
  18795. {
  18796. }
  18797. /** Unpremultiplies the pixel's RGB values. */
  18798. forcedinline void unpremultiply() throw()
  18799. {
  18800. }
  18801. forcedinline void desaturate() throw()
  18802. {
  18803. }
  18804. /** The indexes of the different components in the byte layout of this type of colour. */
  18805. enum { indexA = 0 };
  18806. private:
  18807. uint8 a : 8;
  18808. }
  18809. #ifndef DOXYGEN
  18810. PACKED
  18811. #endif
  18812. ;
  18813. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  18814. {
  18815. blend (PixelARGB (src.getARGB()));
  18816. }
  18817. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  18818. {
  18819. uint32 sargb = src.getARGB();
  18820. const uint32 alpha = 0x100 - (sargb >> 24);
  18821. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  18822. sargb += 0xff00ff00 & (getAG() * alpha);
  18823. argb = sargb;
  18824. }
  18825. #if JUCE_MSVC
  18826. #pragma pack (pop)
  18827. #endif
  18828. #undef PACKED
  18829. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  18830. /*** End of inlined file: juce_PixelFormats.h ***/
  18831. /**
  18832. Represents a colour, also including a transparency value.
  18833. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  18834. */
  18835. class JUCE_API Colour
  18836. {
  18837. public:
  18838. /** Creates a transparent black colour. */
  18839. Colour() throw();
  18840. /** Creates a copy of another Colour object. */
  18841. Colour (const Colour& other) throw();
  18842. /** Creates a colour from a 32-bit ARGB value.
  18843. The format of this number is:
  18844. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  18845. All components in the range 0x00 to 0xff.
  18846. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  18847. @see getPixelARGB
  18848. */
  18849. explicit Colour (uint32 argb) throw();
  18850. /** Creates an opaque colour using 8-bit red, green and blue values */
  18851. Colour (uint8 red,
  18852. uint8 green,
  18853. uint8 blue) throw();
  18854. /** Creates an opaque colour using 8-bit red, green and blue values */
  18855. static const Colour fromRGB (uint8 red,
  18856. uint8 green,
  18857. uint8 blue) throw();
  18858. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  18859. Colour (uint8 red,
  18860. uint8 green,
  18861. uint8 blue,
  18862. uint8 alpha) throw();
  18863. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  18864. static const Colour fromRGBA (uint8 red,
  18865. uint8 green,
  18866. uint8 blue,
  18867. uint8 alpha) throw();
  18868. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  18869. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  18870. Values outside the valid range will be clipped.
  18871. */
  18872. Colour (uint8 red,
  18873. uint8 green,
  18874. uint8 blue,
  18875. float alpha) throw();
  18876. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  18877. static const Colour fromRGBAFloat (uint8 red,
  18878. uint8 green,
  18879. uint8 blue,
  18880. float alpha) throw();
  18881. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  18882. The floating point values must be between 0.0 and 1.0.
  18883. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  18884. Values outside the valid range will be clipped.
  18885. */
  18886. Colour (float hue,
  18887. float saturation,
  18888. float brightness,
  18889. uint8 alpha) throw();
  18890. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  18891. All values must be between 0.0 and 1.0.
  18892. Numbers outside the valid range will be clipped.
  18893. */
  18894. Colour (float hue,
  18895. float saturation,
  18896. float brightness,
  18897. float alpha) throw();
  18898. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  18899. The floating point values must be between 0.0 and 1.0.
  18900. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  18901. Values outside the valid range will be clipped.
  18902. */
  18903. static const Colour fromHSV (float hue,
  18904. float saturation,
  18905. float brightness,
  18906. float alpha) throw();
  18907. /** Destructor. */
  18908. ~Colour() throw();
  18909. /** Copies another Colour object. */
  18910. Colour& operator= (const Colour& other) throw();
  18911. /** Compares two colours. */
  18912. bool operator== (const Colour& other) const throw();
  18913. /** Compares two colours. */
  18914. bool operator!= (const Colour& other) const throw();
  18915. /** Returns the red component of this colour.
  18916. @returns a value between 0x00 and 0xff.
  18917. */
  18918. uint8 getRed() const throw() { return argb.getRed(); }
  18919. /** Returns the green component of this colour.
  18920. @returns a value between 0x00 and 0xff.
  18921. */
  18922. uint8 getGreen() const throw() { return argb.getGreen(); }
  18923. /** Returns the blue component of this colour.
  18924. @returns a value between 0x00 and 0xff.
  18925. */
  18926. uint8 getBlue() const throw() { return argb.getBlue(); }
  18927. /** Returns the red component of this colour as a floating point value.
  18928. @returns a value between 0.0 and 1.0
  18929. */
  18930. float getFloatRed() const throw();
  18931. /** Returns the green component of this colour as a floating point value.
  18932. @returns a value between 0.0 and 1.0
  18933. */
  18934. float getFloatGreen() const throw();
  18935. /** Returns the blue component of this colour as a floating point value.
  18936. @returns a value between 0.0 and 1.0
  18937. */
  18938. float getFloatBlue() const throw();
  18939. /** Returns a premultiplied ARGB pixel object that represents this colour.
  18940. */
  18941. const PixelARGB getPixelARGB() const throw();
  18942. /** Returns a 32-bit integer that represents this colour.
  18943. The format of this number is:
  18944. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  18945. */
  18946. uint32 getARGB() const throw();
  18947. /** Returns the colour's alpha (opacity).
  18948. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  18949. */
  18950. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  18951. /** Returns the colour's alpha (opacity) as a floating point value.
  18952. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  18953. */
  18954. float getFloatAlpha() const throw();
  18955. /** Returns true if this colour is completely opaque.
  18956. Equivalent to (getAlpha() == 0xff).
  18957. */
  18958. bool isOpaque() const throw();
  18959. /** Returns true if this colour is completely transparent.
  18960. Equivalent to (getAlpha() == 0x00).
  18961. */
  18962. bool isTransparent() const throw();
  18963. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  18964. const Colour withAlpha (uint8 newAlpha) const throw();
  18965. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  18966. const Colour withAlpha (float newAlpha) const throw();
  18967. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  18968. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  18969. */
  18970. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  18971. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  18972. If the foreground colour is semi-transparent, it is blended onto this colour
  18973. accordingly.
  18974. */
  18975. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  18976. /** Returns a colour that lies somewhere between this one and another.
  18977. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  18978. is 1.0, the result is 100% of the other colour.
  18979. */
  18980. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  18981. /** Returns the colour's hue component.
  18982. The value returned is in the range 0.0 to 1.0
  18983. */
  18984. float getHue() const throw();
  18985. /** Returns the colour's saturation component.
  18986. The value returned is in the range 0.0 to 1.0
  18987. */
  18988. float getSaturation() const throw();
  18989. /** Returns the colour's brightness component.
  18990. The value returned is in the range 0.0 to 1.0
  18991. */
  18992. float getBrightness() const throw();
  18993. /** Returns the colour's hue, saturation and brightness components all at once.
  18994. The values returned are in the range 0.0 to 1.0
  18995. */
  18996. void getHSB (float& hue,
  18997. float& saturation,
  18998. float& brightness) const throw();
  18999. /** Returns a copy of this colour with a different hue. */
  19000. const Colour withHue (float newHue) const throw();
  19001. /** Returns a copy of this colour with a different saturation. */
  19002. const Colour withSaturation (float newSaturation) const throw();
  19003. /** Returns a copy of this colour with a different brightness.
  19004. @see brighter, darker, withMultipliedBrightness
  19005. */
  19006. const Colour withBrightness (float newBrightness) const throw();
  19007. /** Returns a copy of this colour with it hue rotated.
  19008. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  19009. @see brighter, darker, withMultipliedBrightness
  19010. */
  19011. const Colour withRotatedHue (float amountToRotate) const throw();
  19012. /** Returns a copy of this colour with its saturation multiplied by the given value.
  19013. The new colour's saturation is (this->getSaturation() * multiplier)
  19014. (the result is clipped to legal limits).
  19015. */
  19016. const Colour withMultipliedSaturation (float multiplier) const throw();
  19017. /** Returns a copy of this colour with its brightness multiplied by the given value.
  19018. The new colour's saturation is (this->getBrightness() * multiplier)
  19019. (the result is clipped to legal limits).
  19020. */
  19021. const Colour withMultipliedBrightness (float amount) const throw();
  19022. /** Returns a brighter version of this colour.
  19023. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  19024. unchanged, and higher values make it brighter
  19025. @see withMultipliedBrightness
  19026. */
  19027. const Colour brighter (float amountBrighter = 0.4f) const throw();
  19028. /** Returns a darker version of this colour.
  19029. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  19030. unchanged, and higher values make it darker
  19031. @see withMultipliedBrightness
  19032. */
  19033. const Colour darker (float amountDarker = 0.4f) const throw();
  19034. /** Returns a colour that will be clearly visible against this colour.
  19035. The amount parameter indicates how contrasting the new colour should
  19036. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  19037. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  19038. return white; Colours::white.contrasting (1.0f) will return black, etc.
  19039. */
  19040. const Colour contrasting (float amount = 1.0f) const throw();
  19041. /** Returns a colour that contrasts against two colours.
  19042. Looks for a colour that contrasts with both of the colours passed-in.
  19043. Handy for things like choosing a highlight colour in text editors, etc.
  19044. */
  19045. static const Colour contrasting (const Colour& colour1,
  19046. const Colour& colour2) throw();
  19047. /** Returns an opaque shade of grey.
  19048. @param brightness the level of grey to return - 0 is black, 1.0 is white
  19049. */
  19050. static const Colour greyLevel (float brightness) throw();
  19051. /** Returns a stringified version of this colour.
  19052. The string can be turned back into a colour using the fromString() method.
  19053. */
  19054. const String toString() const;
  19055. /** Reads the colour from a string that was created with toString().
  19056. */
  19057. static const Colour fromString (const String& encodedColourString);
  19058. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  19059. const String toDisplayString (bool includeAlphaValue) const;
  19060. private:
  19061. PixelARGB argb;
  19062. };
  19063. #endif // __JUCE_COLOUR_JUCEHEADER__
  19064. /*** End of inlined file: juce_Colour.h ***/
  19065. /**
  19066. Contains a set of predefined named colours (mostly standard HTML colours)
  19067. @see Colour, Colours::greyLevel
  19068. */
  19069. class Colours
  19070. {
  19071. public:
  19072. static JUCE_API const Colour
  19073. transparentBlack, /**< ARGB = 0x00000000 */
  19074. transparentWhite, /**< ARGB = 0x00ffffff */
  19075. black, /**< ARGB = 0xff000000 */
  19076. white, /**< ARGB = 0xffffffff */
  19077. blue, /**< ARGB = 0xff0000ff */
  19078. grey, /**< ARGB = 0xff808080 */
  19079. green, /**< ARGB = 0xff008000 */
  19080. red, /**< ARGB = 0xffff0000 */
  19081. yellow, /**< ARGB = 0xffffff00 */
  19082. aliceblue, antiquewhite, aqua, aquamarine,
  19083. azure, beige, bisque, blanchedalmond,
  19084. blueviolet, brown, burlywood, cadetblue,
  19085. chartreuse, chocolate, coral, cornflowerblue,
  19086. cornsilk, crimson, cyan, darkblue,
  19087. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  19088. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  19089. darkorchid, darkred, darksalmon, darkseagreen,
  19090. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  19091. deeppink, deepskyblue, dimgrey, dodgerblue,
  19092. firebrick, floralwhite, forestgreen, fuchsia,
  19093. gainsboro, gold, goldenrod, greenyellow,
  19094. honeydew, hotpink, indianred, indigo,
  19095. ivory, khaki, lavender, lavenderblush,
  19096. lemonchiffon, lightblue, lightcoral, lightcyan,
  19097. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  19098. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  19099. lightsteelblue, lightyellow, lime, limegreen,
  19100. linen, magenta, maroon, mediumaquamarine,
  19101. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  19102. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  19103. midnightblue, mintcream, mistyrose, navajowhite,
  19104. navy, oldlace, olive, olivedrab,
  19105. orange, orangered, orchid, palegoldenrod,
  19106. palegreen, paleturquoise, palevioletred, papayawhip,
  19107. peachpuff, peru, pink, plum,
  19108. powderblue, purple, rosybrown, royalblue,
  19109. saddlebrown, salmon, sandybrown, seagreen,
  19110. seashell, sienna, silver, skyblue,
  19111. slateblue, slategrey, snow, springgreen,
  19112. steelblue, tan, teal, thistle,
  19113. tomato, turquoise, violet, wheat,
  19114. whitesmoke, yellowgreen;
  19115. /** Attempts to look up a string in the list of known colour names, and return
  19116. the appropriate colour.
  19117. A non-case-sensitive search is made of the list of predefined colours, and
  19118. if a match is found, that colour is returned. If no match is found, the
  19119. colour passed in as the defaultColour parameter is returned.
  19120. */
  19121. static JUCE_API const Colour findColourForName (const String& colourName,
  19122. const Colour& defaultColour);
  19123. private:
  19124. // this isn't a class you should ever instantiate - it's just here for the
  19125. // static values in it.
  19126. Colours();
  19127. JUCE_DECLARE_NON_COPYABLE (Colours);
  19128. };
  19129. #endif // __JUCE_COLOURS_JUCEHEADER__
  19130. /*** End of inlined file: juce_Colours.h ***/
  19131. /*** Start of inlined file: juce_ColourGradient.h ***/
  19132. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  19133. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  19134. /**
  19135. Describes the layout and colours that should be used to paint a colour gradient.
  19136. @see Graphics::setGradientFill
  19137. */
  19138. class JUCE_API ColourGradient
  19139. {
  19140. public:
  19141. /** Creates a gradient object.
  19142. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  19143. colour2 should be. In between them there's a gradient.
  19144. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  19145. its centre.
  19146. The alpha transparencies of the colours are used, so note that
  19147. if you blend from transparent to a solid colour, the RGB of the transparent
  19148. colour will become visible in parts of the gradient. e.g. blending
  19149. from Colour::transparentBlack to Colours::white will produce a
  19150. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  19151. will be white all the way across.
  19152. @see ColourGradient
  19153. */
  19154. ColourGradient (const Colour& colour1, float x1, float y1,
  19155. const Colour& colour2, float x2, float y2,
  19156. bool isRadial);
  19157. /** Creates an uninitialised gradient.
  19158. If you use this constructor instead of the other one, be sure to set all the
  19159. object's public member variables before using it!
  19160. */
  19161. ColourGradient() throw();
  19162. /** Destructor */
  19163. ~ColourGradient();
  19164. /** Removes any colours that have been added.
  19165. This will also remove any start and end colours, so the gradient won't work. You'll
  19166. need to add more colours with addColour().
  19167. */
  19168. void clearColours();
  19169. /** Adds a colour at a point along the length of the gradient.
  19170. This allows the gradient to go through a spectrum of colours, instead of just a
  19171. start and end colour.
  19172. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  19173. of the distance along the line between the two points
  19174. at which the colour should occur.
  19175. @param colour the colour that should be used at this point
  19176. @returns the index at which the new point was added
  19177. */
  19178. int addColour (double proportionAlongGradient,
  19179. const Colour& colour);
  19180. /** Removes one of the colours from the gradient. */
  19181. void removeColour (int index);
  19182. /** Multiplies the alpha value of all the colours by the given scale factor */
  19183. void multiplyOpacity (float multiplier) throw();
  19184. /** Returns the number of colour-stops that have been added. */
  19185. int getNumColours() const throw();
  19186. /** Returns the position along the length of the gradient of the colour with this index.
  19187. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  19188. */
  19189. double getColourPosition (int index) const throw();
  19190. /** Returns the colour that was added with a given index.
  19191. The index is from 0 to getNumColours() - 1.
  19192. */
  19193. const Colour getColour (int index) const throw();
  19194. /** Changes the colour at a given index.
  19195. The index is from 0 to getNumColours() - 1.
  19196. */
  19197. void setColour (int index, const Colour& newColour) throw();
  19198. /** Returns the an interpolated colour at any position along the gradient.
  19199. @param position the position along the gradient, between 0 and 1
  19200. */
  19201. const Colour getColourAtPosition (double position) const throw();
  19202. /** Creates a set of interpolated premultiplied ARGB values.
  19203. This will resize the HeapBlock, fill it with the colours, and will return the number of
  19204. colours that it added.
  19205. */
  19206. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  19207. /** Returns true if all colours are opaque. */
  19208. bool isOpaque() const throw();
  19209. /** Returns true if all colours are completely transparent. */
  19210. bool isInvisible() const throw();
  19211. Point<float> point1, point2;
  19212. /** If true, the gradient should be filled circularly, centred around
  19213. point1, with point2 defining a point on the circumference.
  19214. If false, the gradient is linear between the two points.
  19215. */
  19216. bool isRadial;
  19217. bool operator== (const ColourGradient& other) const throw();
  19218. bool operator!= (const ColourGradient& other) const throw();
  19219. private:
  19220. struct ColourPoint
  19221. {
  19222. ColourPoint() throw() {}
  19223. ColourPoint (const double position_, const Colour& colour_) throw()
  19224. : position (position_), colour (colour_)
  19225. {}
  19226. bool operator== (const ColourPoint& other) const throw() { return position == other.position && colour == other.colour; }
  19227. bool operator!= (const ColourPoint& other) const throw() { return position != other.position || colour != other.colour; }
  19228. double position;
  19229. Colour colour;
  19230. };
  19231. Array <ColourPoint> colours;
  19232. JUCE_LEAK_DETECTOR (ColourGradient);
  19233. };
  19234. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  19235. /*** End of inlined file: juce_ColourGradient.h ***/
  19236. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  19237. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  19238. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  19239. /**
  19240. Defines the method used to postion some kind of rectangular object within
  19241. a rectangular viewport.
  19242. Although similar to Justification, this is more specific, and has some extra
  19243. options.
  19244. */
  19245. class JUCE_API RectanglePlacement
  19246. {
  19247. public:
  19248. /** Creates a RectanglePlacement object using a combination of flags. */
  19249. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  19250. /** Creates a copy of another RectanglePlacement object. */
  19251. RectanglePlacement (const RectanglePlacement& other) throw();
  19252. /** Copies another RectanglePlacement object. */
  19253. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  19254. /** Flag values that can be combined and used in the constructor. */
  19255. enum
  19256. {
  19257. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  19258. xLeft = 1,
  19259. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  19260. xRight = 2,
  19261. /** Indicates that the source should be placed in the centre between the left and right
  19262. sides of the available space. */
  19263. xMid = 4,
  19264. /** Indicates that the source's top edge should be aligned with the top edge of the
  19265. destination rectangle. */
  19266. yTop = 8,
  19267. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  19268. destination rectangle. */
  19269. yBottom = 16,
  19270. /** Indicates that the source should be placed in the centre between the top and bottom
  19271. sides of the available space. */
  19272. yMid = 32,
  19273. /** If this flag is set, then the source rectangle will be resized to completely fill
  19274. the destination rectangle, and all other flags are ignored.
  19275. */
  19276. stretchToFit = 64,
  19277. /** If this flag is set, then the source rectangle will be resized so that it is the
  19278. minimum size to completely fill the destination rectangle, without changing its
  19279. aspect ratio. This means that some of the source rectangle may fall outside
  19280. the destination.
  19281. If this flag is not set, the source will be given the maximum size at which none
  19282. of it falls outside the destination rectangle.
  19283. */
  19284. fillDestination = 128,
  19285. /** Indicates that the source rectangle can be reduced in size if required, but should
  19286. never be made larger than its original size.
  19287. */
  19288. onlyReduceInSize = 256,
  19289. /** Indicates that the source rectangle can be enlarged if required, but should
  19290. never be made smaller than its original size.
  19291. */
  19292. onlyIncreaseInSize = 512,
  19293. /** Indicates that the source rectangle's size should be left unchanged.
  19294. */
  19295. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  19296. /** A shorthand value that is equivalent to (xMid | yMid). */
  19297. centred = 4 + 32
  19298. };
  19299. /** Returns the raw flags that are set for this object. */
  19300. inline int getFlags() const throw() { return flags; }
  19301. /** Tests a set of flags for this object.
  19302. @returns true if any of the flags passed in are set on this object.
  19303. */
  19304. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  19305. /** Adjusts the position and size of a rectangle to fit it into a space.
  19306. The source rectangle co-ordinates will be adjusted so that they fit into
  19307. the destination rectangle based on this object's flags.
  19308. */
  19309. void applyTo (double& sourceX,
  19310. double& sourceY,
  19311. double& sourceW,
  19312. double& sourceH,
  19313. double destinationX,
  19314. double destinationY,
  19315. double destinationW,
  19316. double destinationH) const throw();
  19317. /** Returns the transform that should be applied to these source co-ordinates to fit them
  19318. into the destination rectangle using the current flags.
  19319. */
  19320. template <typename ValueType>
  19321. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  19322. const Rectangle<ValueType>& destination) const throw()
  19323. {
  19324. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  19325. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  19326. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  19327. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  19328. static_cast <ValueType> (w), static_cast <ValueType> (h));
  19329. }
  19330. /** Returns the transform that should be applied to these source co-ordinates to fit them
  19331. into the destination rectangle using the current flags.
  19332. */
  19333. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  19334. const Rectangle<float>& destination) const throw();
  19335. private:
  19336. int flags;
  19337. };
  19338. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  19339. /*** End of inlined file: juce_RectanglePlacement.h ***/
  19340. class LowLevelGraphicsContext;
  19341. class Image;
  19342. class FillType;
  19343. class RectangleList;
  19344. /**
  19345. A graphics context, used for drawing a component or image.
  19346. When a Component needs painting, a Graphics context is passed to its
  19347. Component::paint() method, and this you then call methods within this
  19348. object to actually draw the component's content.
  19349. A Graphics can also be created from an image, to allow drawing directly onto
  19350. that image.
  19351. @see Component::paint
  19352. */
  19353. class JUCE_API Graphics
  19354. {
  19355. public:
  19356. /** Creates a Graphics object to draw directly onto the given image.
  19357. The graphics object that is created will be set up to draw onto the image,
  19358. with the context's clipping area being the entire size of the image, and its
  19359. origin being the image's origin. To draw into a subsection of an image, use the
  19360. reduceClipRegion() and setOrigin() methods.
  19361. Obviously you shouldn't delete the image before this context is deleted.
  19362. */
  19363. explicit Graphics (const Image& imageToDrawOnto);
  19364. /** Destructor. */
  19365. ~Graphics();
  19366. /** Changes the current drawing colour.
  19367. This sets the colour that will now be used for drawing operations - it also
  19368. sets the opacity to that of the colour passed-in.
  19369. If a brush is being used when this method is called, the brush will be deselected,
  19370. and any subsequent drawing will be done with a solid colour brush instead.
  19371. @see setOpacity
  19372. */
  19373. void setColour (const Colour& newColour);
  19374. /** Changes the opacity to use with the current colour.
  19375. If a solid colour is being used for drawing, this changes its opacity
  19376. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  19377. If a gradient is being used, this will have no effect on it.
  19378. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  19379. */
  19380. void setOpacity (float newOpacity);
  19381. /** Sets the context to use a gradient for its fill pattern.
  19382. */
  19383. void setGradientFill (const ColourGradient& gradient);
  19384. /** Sets the context to use a tiled image pattern for filling.
  19385. Make sure that you don't delete this image while it's still being used by
  19386. this context!
  19387. */
  19388. void setTiledImageFill (const Image& imageToUse,
  19389. int anchorX, int anchorY,
  19390. float opacity);
  19391. /** Changes the current fill settings.
  19392. @see setColour, setGradientFill, setTiledImageFill
  19393. */
  19394. void setFillType (const FillType& newFill);
  19395. /** Changes the font to use for subsequent text-drawing functions.
  19396. Note there's also a setFont (float, int) method to quickly change the size and
  19397. style of the current font.
  19398. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  19399. */
  19400. void setFont (const Font& newFont);
  19401. /** Changes the size and style of the currently-selected font.
  19402. This is a convenient shortcut that changes the context's current font to a
  19403. different size or style. The typeface won't be changed.
  19404. @see Font
  19405. */
  19406. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  19407. /** Returns the currently selected font. */
  19408. const Font getCurrentFont() const;
  19409. /** Draws a one-line text string.
  19410. This will use the current colour (or brush) to fill the text. The font is the last
  19411. one specified by setFont().
  19412. @param text the string to draw
  19413. @param startX the position to draw the left-hand edge of the text
  19414. @param baselineY the position of the text's baseline
  19415. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  19416. */
  19417. void drawSingleLineText (const String& text,
  19418. int startX, int baselineY) const;
  19419. /** Draws text across multiple lines.
  19420. This will break the text onto a new line where there's a new-line or
  19421. carriage-return character, or at a word-boundary when the text becomes wider
  19422. than the size specified by the maximumLineWidth parameter.
  19423. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  19424. */
  19425. void drawMultiLineText (const String& text,
  19426. int startX, int baselineY,
  19427. int maximumLineWidth) const;
  19428. /** Renders a string of text as a vector path.
  19429. This allows a string to be transformed with an arbitrary AffineTransform and
  19430. rendered using the current colour/brush. It's much slower than the normal text methods
  19431. but more accurate.
  19432. @see setFont
  19433. */
  19434. void drawTextAsPath (const String& text,
  19435. const AffineTransform& transform) const;
  19436. /** Draws a line of text within a specified rectangle.
  19437. The text will be positioned within the rectangle based on the justification
  19438. flags passed-in. If the string is too long to fit inside the rectangle, it will
  19439. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  19440. flag is true).
  19441. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  19442. */
  19443. void drawText (const String& text,
  19444. int x, int y, int width, int height,
  19445. const Justification& justificationType,
  19446. bool useEllipsesIfTooBig) const;
  19447. /** Tries to draw a text string inside a given space.
  19448. This does its best to make the given text readable within the specified rectangle,
  19449. so it useful for labelling things.
  19450. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  19451. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  19452. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  19453. it's been truncated.
  19454. A Justification parameter lets you specify how the text is laid out within the rectangle,
  19455. both horizontally and vertically.
  19456. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  19457. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  19458. can set this value to 1.0f.
  19459. @see GlyphArrangement::addFittedText
  19460. */
  19461. void drawFittedText (const String& text,
  19462. int x, int y, int width, int height,
  19463. const Justification& justificationFlags,
  19464. int maximumNumberOfLines,
  19465. float minimumHorizontalScale = 0.7f) const;
  19466. /** Fills the context's entire clip region with the current colour or brush.
  19467. (See also the fillAll (const Colour&) method which is a quick way of filling
  19468. it with a given colour).
  19469. */
  19470. void fillAll() const;
  19471. /** Fills the context's entire clip region with a given colour.
  19472. This leaves the context's current colour and brush unchanged, it just
  19473. uses the specified colour temporarily.
  19474. */
  19475. void fillAll (const Colour& colourToUse) const;
  19476. /** Fills a rectangle with the current colour or brush.
  19477. @see drawRect, fillRoundedRectangle
  19478. */
  19479. void fillRect (int x, int y, int width, int height) const;
  19480. /** Fills a rectangle with the current colour or brush. */
  19481. void fillRect (const Rectangle<int>& rectangle) const;
  19482. /** Fills a rectangle with the current colour or brush.
  19483. This uses sub-pixel positioning so is slower than the fillRect method which
  19484. takes integer co-ordinates.
  19485. */
  19486. void fillRect (float x, float y, float width, float height) const;
  19487. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  19488. @see drawRoundedRectangle, Path::addRoundedRectangle
  19489. */
  19490. void fillRoundedRectangle (float x, float y, float width, float height,
  19491. float cornerSize) const;
  19492. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  19493. @see drawRoundedRectangle, Path::addRoundedRectangle
  19494. */
  19495. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  19496. float cornerSize) const;
  19497. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  19498. */
  19499. void fillCheckerBoard (const Rectangle<int>& area,
  19500. int checkWidth, int checkHeight,
  19501. const Colour& colour1, const Colour& colour2) const;
  19502. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  19503. The lines are drawn inside the given rectangle, and greater line thicknesses
  19504. extend inwards.
  19505. @see fillRect
  19506. */
  19507. void drawRect (int x, int y, int width, int height,
  19508. int lineThickness = 1) const;
  19509. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  19510. The lines are drawn inside the given rectangle, and greater line thicknesses
  19511. extend inwards.
  19512. @see fillRect
  19513. */
  19514. void drawRect (float x, float y, float width, float height,
  19515. float lineThickness = 1.0f) const;
  19516. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  19517. The lines are drawn inside the given rectangle, and greater line thicknesses
  19518. extend inwards.
  19519. @see fillRect
  19520. */
  19521. void drawRect (const Rectangle<int>& rectangle,
  19522. int lineThickness = 1) const;
  19523. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  19524. @see fillRoundedRectangle, Path::addRoundedRectangle
  19525. */
  19526. void drawRoundedRectangle (float x, float y, float width, float height,
  19527. float cornerSize, float lineThickness) const;
  19528. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  19529. @see fillRoundedRectangle, Path::addRoundedRectangle
  19530. */
  19531. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  19532. float cornerSize, float lineThickness) const;
  19533. /** Draws a 3D raised (or indented) bevel using two colours.
  19534. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  19535. extend inwards.
  19536. The top-left colour is used for the top- and left-hand edges of the
  19537. bevel; the bottom-right colour is used for the bottom- and right-hand
  19538. edges.
  19539. If useGradient is true, then the bevel fades out to make it look more curved
  19540. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  19541. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  19542. the centre edges are sharp and it fades towards the outside.
  19543. */
  19544. void drawBevel (int x, int y, int width, int height,
  19545. int bevelThickness,
  19546. const Colour& topLeftColour = Colours::white,
  19547. const Colour& bottomRightColour = Colours::black,
  19548. bool useGradient = true,
  19549. bool sharpEdgeOnOutside = true) const;
  19550. /** Draws a pixel using the current colour or brush.
  19551. */
  19552. void setPixel (int x, int y) const;
  19553. /** Fills an ellipse with the current colour or brush.
  19554. The ellipse is drawn to fit inside the given rectangle.
  19555. @see drawEllipse, Path::addEllipse
  19556. */
  19557. void fillEllipse (float x, float y, float width, float height) const;
  19558. /** Draws an elliptical stroke using the current colour or brush.
  19559. @see fillEllipse, Path::addEllipse
  19560. */
  19561. void drawEllipse (float x, float y, float width, float height,
  19562. float lineThickness) const;
  19563. /** Draws a line between two points.
  19564. The line is 1 pixel wide and drawn with the current colour or brush.
  19565. */
  19566. void drawLine (float startX, float startY, float endX, float endY) const;
  19567. /** Draws a line between two points with a given thickness.
  19568. @see Path::addLineSegment
  19569. */
  19570. void drawLine (float startX, float startY, float endX, float endY,
  19571. float lineThickness) const;
  19572. /** Draws a line between two points.
  19573. The line is 1 pixel wide and drawn with the current colour or brush.
  19574. */
  19575. void drawLine (const Line<float>& line) const;
  19576. /** Draws a line between two points with a given thickness.
  19577. @see Path::addLineSegment
  19578. */
  19579. void drawLine (const Line<float>& line, float lineThickness) const;
  19580. /** Draws a dashed line using a custom set of dash-lengths.
  19581. @param startX the line's start x co-ordinate
  19582. @param startY the line's start y co-ordinate
  19583. @param endX the line's end x co-ordinate
  19584. @param endY the line's end y co-ordinate
  19585. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  19586. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  19587. draw 6 pixels, skip 7 pixels, and then repeat.
  19588. @param numDashLengths the number of elements in the array (this must be an even number).
  19589. @param lineThickness the thickness of the line to draw
  19590. @see PathStrokeType::createDashedStroke
  19591. */
  19592. void drawDashedLine (float startX, float startY,
  19593. float endX, float endY,
  19594. const float* dashLengths, int numDashLengths,
  19595. float lineThickness = 1.0f) const;
  19596. /** Draws a vertical line of pixels at a given x position.
  19597. The x position is an integer, but the top and bottom of the line can be sub-pixel
  19598. positions, and these will be anti-aliased if necessary.
  19599. */
  19600. void drawVerticalLine (int x, float top, float bottom) const;
  19601. /** Draws a horizontal line of pixels at a given y position.
  19602. The y position is an integer, but the left and right ends of the line can be sub-pixel
  19603. positions, and these will be anti-aliased if necessary.
  19604. */
  19605. void drawHorizontalLine (int y, float left, float right) const;
  19606. /** Fills a path using the currently selected colour or brush.
  19607. */
  19608. void fillPath (const Path& path,
  19609. const AffineTransform& transform = AffineTransform::identity) const;
  19610. /** Draws a path's outline using the currently selected colour or brush.
  19611. */
  19612. void strokePath (const Path& path,
  19613. const PathStrokeType& strokeType,
  19614. const AffineTransform& transform = AffineTransform::identity) const;
  19615. /** Draws a line with an arrowhead at its end.
  19616. @param line the line to draw
  19617. @param lineThickness the thickness of the line
  19618. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  19619. @param arrowheadLength the length of the arrow head (along the length of the line)
  19620. */
  19621. void drawArrow (const Line<float>& line,
  19622. float lineThickness,
  19623. float arrowheadWidth,
  19624. float arrowheadLength) const;
  19625. /** Types of rendering quality that can be specified when drawing images.
  19626. @see blendImage, Graphics::setImageResamplingQuality
  19627. */
  19628. enum ResamplingQuality
  19629. {
  19630. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  19631. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  19632. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  19633. };
  19634. /** Changes the quality that will be used when resampling images.
  19635. By default a Graphics object will be set to mediumRenderingQuality.
  19636. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  19637. */
  19638. void setImageResamplingQuality (const ResamplingQuality newQuality);
  19639. /** Draws an image.
  19640. This will draw the whole of an image, positioning its top-left corner at the
  19641. given co-ordinates, and keeping its size the same. This is the simplest image
  19642. drawing method - the others give more control over the scaling and clipping
  19643. of the images.
  19644. Images are composited using the context's current opacity, so if you
  19645. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  19646. (or setColour() with an opaque colour) before drawing images.
  19647. */
  19648. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  19649. bool fillAlphaChannelWithCurrentBrush = false) const;
  19650. /** Draws part of an image, rescaling it to fit in a given target region.
  19651. The specified area of the source image is rescaled and drawn to fill the
  19652. specifed destination rectangle.
  19653. Images are composited using the context's current opacity, so if you
  19654. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  19655. (or setColour() with an opaque colour) before drawing images.
  19656. @param imageToDraw the image to overlay
  19657. @param destX the left of the destination rectangle
  19658. @param destY the top of the destination rectangle
  19659. @param destWidth the width of the destination rectangle
  19660. @param destHeight the height of the destination rectangle
  19661. @param sourceX the left of the rectangle to copy from the source image
  19662. @param sourceY the top of the rectangle to copy from the source image
  19663. @param sourceWidth the width of the rectangle to copy from the source image
  19664. @param sourceHeight the height of the rectangle to copy from the source image
  19665. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  19666. the source image's alpha channel is used as a mask with
  19667. which to fill the destination using the current colour
  19668. or brush. (If the source is has no alpha channel, then
  19669. it will just fill the target with a solid rectangle)
  19670. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  19671. */
  19672. void drawImage (const Image& imageToDraw,
  19673. int destX, int destY, int destWidth, int destHeight,
  19674. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  19675. bool fillAlphaChannelWithCurrentBrush = false) const;
  19676. /** Draws an image, having applied an affine transform to it.
  19677. This lets you throw the image around in some wacky ways, rotate it, shear,
  19678. scale it, etc.
  19679. Images are composited using the context's current opacity, so if you
  19680. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  19681. (or setColour() with an opaque colour) before drawing images.
  19682. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  19683. are ignored and it is filled with the current brush, masked by its alpha channel.
  19684. If you want to render only a subsection of an image, use Image::getClippedImage() to
  19685. create the section that you need.
  19686. @see setImageResamplingQuality, drawImage
  19687. */
  19688. void drawImageTransformed (const Image& imageToDraw,
  19689. const AffineTransform& transform,
  19690. bool fillAlphaChannelWithCurrentBrush = false) const;
  19691. /** Draws an image to fit within a designated rectangle.
  19692. If the image is too big or too small for the space, it will be rescaled
  19693. to fit as nicely as it can do without affecting its aspect ratio. It will
  19694. then be placed within the target rectangle according to the justification flags
  19695. specified.
  19696. @param imageToDraw the source image to draw
  19697. @param destX top-left of the target rectangle to fit it into
  19698. @param destY top-left of the target rectangle to fit it into
  19699. @param destWidth size of the target rectangle to fit the image into
  19700. @param destHeight size of the target rectangle to fit the image into
  19701. @param placementWithinTarget this specifies how the image should be positioned
  19702. within the target rectangle - see the RectanglePlacement
  19703. class for more details about this.
  19704. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  19705. alpha channel will be used as a mask with which to
  19706. draw with the current brush or colour. This is
  19707. similar to fillAlphaMap(), and see also drawImage()
  19708. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  19709. */
  19710. void drawImageWithin (const Image& imageToDraw,
  19711. int destX, int destY, int destWidth, int destHeight,
  19712. const RectanglePlacement& placementWithinTarget,
  19713. bool fillAlphaChannelWithCurrentBrush = false) const;
  19714. /** Returns the position of the bounding box for the current clipping region.
  19715. @see getClipRegion, clipRegionIntersects
  19716. */
  19717. const Rectangle<int> getClipBounds() const;
  19718. /** Checks whether a rectangle overlaps the context's clipping region.
  19719. If this returns false, no part of the given area can be drawn onto, so this
  19720. method can be used to optimise a component's paint() method, by letting it
  19721. avoid drawing complex objects that aren't within the region being repainted.
  19722. */
  19723. bool clipRegionIntersects (const Rectangle<int>& area) const;
  19724. /** Intersects the current clipping region with another region.
  19725. @returns true if the resulting clipping region is non-zero in size
  19726. @see setOrigin, clipRegionIntersects
  19727. */
  19728. bool reduceClipRegion (int x, int y, int width, int height);
  19729. /** Intersects the current clipping region with another region.
  19730. @returns true if the resulting clipping region is non-zero in size
  19731. @see setOrigin, clipRegionIntersects
  19732. */
  19733. bool reduceClipRegion (const Rectangle<int>& area);
  19734. /** Intersects the current clipping region with a rectangle list region.
  19735. @returns true if the resulting clipping region is non-zero in size
  19736. @see setOrigin, clipRegionIntersects
  19737. */
  19738. bool reduceClipRegion (const RectangleList& clipRegion);
  19739. /** Intersects the current clipping region with a path.
  19740. @returns true if the resulting clipping region is non-zero in size
  19741. @see reduceClipRegion
  19742. */
  19743. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  19744. /** Intersects the current clipping region with an image's alpha-channel.
  19745. The current clipping path is intersected with the area covered by this image's
  19746. alpha-channel, after the image has been transformed by the specified matrix.
  19747. @param image the image whose alpha-channel should be used. If the image doesn't
  19748. have an alpha-channel, it is treated as entirely opaque.
  19749. @param transform a matrix to apply to the image
  19750. @returns true if the resulting clipping region is non-zero in size
  19751. @see reduceClipRegion
  19752. */
  19753. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  19754. /** Excludes a rectangle to stop it being drawn into. */
  19755. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  19756. /** Returns true if no drawing can be done because the clip region is zero. */
  19757. bool isClipEmpty() const;
  19758. /** Saves the current graphics state on an internal stack.
  19759. To restore the state, use restoreState().
  19760. @see ScopedSaveState
  19761. */
  19762. void saveState();
  19763. /** Restores a graphics state that was previously saved with saveState().
  19764. @see ScopedSaveState
  19765. */
  19766. void restoreState();
  19767. /** Uses RAII to save and restore the state of a graphics context.
  19768. On construction, this calls Graphics::saveState(), and on destruction it calls
  19769. Graphics::restoreState() on the Graphics object that you supply.
  19770. */
  19771. class ScopedSaveState
  19772. {
  19773. public:
  19774. ScopedSaveState (Graphics& g);
  19775. ~ScopedSaveState();
  19776. private:
  19777. Graphics& context;
  19778. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  19779. };
  19780. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  19781. context with the given opacity.
  19782. The context uses an internal stack of temporary image layers to do this. When you've
  19783. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  19784. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  19785. by a corresponding call to endTransparencyLayer()!
  19786. This call also saves the current state, and endTransparencyLayer() restores it.
  19787. */
  19788. void beginTransparencyLayer (float layerOpacity);
  19789. /** Completes a drawing operation to a temporary semi-transparent buffer.
  19790. See beginTransparencyLayer() for more details.
  19791. */
  19792. void endTransparencyLayer();
  19793. /** Moves the position of the context's origin.
  19794. This changes the position that the context considers to be (0, 0) to
  19795. the specified position.
  19796. So if you call setOrigin (100, 100), then the position that was previously
  19797. referred to as (100, 100) will subsequently be considered to be (0, 0).
  19798. @see reduceClipRegion, addTransform
  19799. */
  19800. void setOrigin (int newOriginX, int newOriginY);
  19801. /** Adds a transformation which will be performed on all the graphics operations that
  19802. the context subsequently performs.
  19803. After calling this, all the coordinates that are passed into the context will be
  19804. transformed by this matrix.
  19805. @see setOrigin
  19806. */
  19807. void addTransform (const AffineTransform& transform);
  19808. /** Resets the current colour, brush, and font to default settings. */
  19809. void resetToDefaultState();
  19810. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  19811. bool isVectorDevice() const;
  19812. /** Create a graphics that uses a given low-level renderer.
  19813. For internal use only.
  19814. NB. The context will NOT be deleted by this object when it is deleted.
  19815. */
  19816. Graphics (LowLevelGraphicsContext* internalContext) throw();
  19817. /** @internal */
  19818. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  19819. private:
  19820. LowLevelGraphicsContext* const context;
  19821. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  19822. bool saveStatePending;
  19823. void saveStateIfPending();
  19824. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  19825. };
  19826. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  19827. /*** End of inlined file: juce_Graphics.h ***/
  19828. /**
  19829. A graphical effect filter that can be applied to components.
  19830. An ImageEffectFilter can be applied to the image that a component
  19831. paints before it hits the screen.
  19832. This is used for adding effects like shadows, blurs, etc.
  19833. @see Component::setComponentEffect
  19834. */
  19835. class JUCE_API ImageEffectFilter
  19836. {
  19837. public:
  19838. /** Overridden to render the effect.
  19839. The implementation of this method must use the image that is passed in
  19840. as its source, and should render its output to the graphics context passed in.
  19841. @param sourceImage the image that the source component has just rendered with
  19842. its paint() method. The image may or may not have an alpha
  19843. channel, depending on whether the component is opaque.
  19844. @param destContext the graphics context to use to draw the resultant image.
  19845. @param alpha the alpha with which to draw the resultant image to the
  19846. target context
  19847. */
  19848. virtual void applyEffect (Image& sourceImage,
  19849. Graphics& destContext,
  19850. float alpha) = 0;
  19851. /** Destructor. */
  19852. virtual ~ImageEffectFilter() {}
  19853. };
  19854. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  19855. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  19856. /*** Start of inlined file: juce_Image.h ***/
  19857. #ifndef __JUCE_IMAGE_JUCEHEADER__
  19858. #define __JUCE_IMAGE_JUCEHEADER__
  19859. /**
  19860. Holds a fixed-size bitmap.
  19861. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  19862. To draw into an image, create a Graphics object for it.
  19863. e.g. @code
  19864. // create a transparent 500x500 image..
  19865. Image myImage (Image::RGB, 500, 500, true);
  19866. Graphics g (myImage);
  19867. g.setColour (Colours::red);
  19868. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  19869. @endcode
  19870. Other useful ways to create an image are with the ImageCache class, or the
  19871. ImageFileFormat, which provides a way to load common image files.
  19872. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  19873. */
  19874. class JUCE_API Image
  19875. {
  19876. public:
  19877. /**
  19878. */
  19879. enum PixelFormat
  19880. {
  19881. UnknownFormat,
  19882. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  19883. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  19884. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  19885. };
  19886. /**
  19887. */
  19888. enum ImageType
  19889. {
  19890. SoftwareImage = 0,
  19891. NativeImage
  19892. };
  19893. /** Creates a null image. */
  19894. Image();
  19895. /** Creates an image with a specified size and format.
  19896. @param format the number of colour channels in the image
  19897. @param imageWidth the desired width of the image, in pixels - this value must be
  19898. greater than zero (otherwise a width of 1 will be used)
  19899. @param imageHeight the desired width of the image, in pixels - this value must be
  19900. greater than zero (otherwise a height of 1 will be used)
  19901. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  19902. or transparent black (if it's ARGB). If false, the image may contain
  19903. junk initially, so you need to make sure you overwrite it thoroughly.
  19904. @param type the type of image - this lets you specify whether you want a purely
  19905. memory-based image, or one that may be managed by the OS if possible.
  19906. */
  19907. Image (PixelFormat format,
  19908. int imageWidth,
  19909. int imageHeight,
  19910. bool clearImage,
  19911. ImageType type = NativeImage);
  19912. /** Creates a shared reference to another image.
  19913. This won't create a duplicate of the image - when Image objects are copied, they simply
  19914. point to the same shared image data. To make sure that an Image object has its own unique,
  19915. unshared internal data, call duplicateIfShared().
  19916. */
  19917. Image (const Image& other);
  19918. /** Makes this image refer to the same underlying image as another object.
  19919. This won't create a duplicate of the image - when Image objects are copied, they simply
  19920. point to the same shared image data. To make sure that an Image object has its own unique,
  19921. unshared internal data, call duplicateIfShared().
  19922. */
  19923. Image& operator= (const Image&);
  19924. /** Destructor. */
  19925. ~Image();
  19926. /** Returns true if the two images are referring to the same internal, shared image. */
  19927. bool operator== (const Image& other) const throw() { return image == other.image; }
  19928. /** Returns true if the two images are not referring to the same internal, shared image. */
  19929. bool operator!= (const Image& other) const throw() { return image != other.image; }
  19930. /** Returns true if this image isn't null.
  19931. If you create an Image with the default constructor, it has no size or content, and is null
  19932. until you reassign it to an Image which contains some actual data.
  19933. The isNull() method is the opposite of isValid().
  19934. @see isNull
  19935. */
  19936. inline bool isValid() const throw() { return image != 0; }
  19937. /** Returns true if this image is not valid.
  19938. If you create an Image with the default constructor, it has no size or content, and is null
  19939. until you reassign it to an Image which contains some actual data.
  19940. The isNull() method is the opposite of isValid().
  19941. @see isValid
  19942. */
  19943. inline bool isNull() const throw() { return image == 0; }
  19944. /** A null Image object that can be used when you need to return an invalid image.
  19945. This object is the equivalient to an Image created with the default constructor.
  19946. */
  19947. static const Image null;
  19948. /** Returns the image's width (in pixels). */
  19949. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  19950. /** Returns the image's height (in pixels). */
  19951. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  19952. /** Returns a rectangle with the same size as this image.
  19953. The rectangle's origin is always (0, 0).
  19954. */
  19955. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  19956. /** Returns the image's pixel format. */
  19957. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  19958. /** True if the image's format is ARGB. */
  19959. bool isARGB() const throw() { return getFormat() == ARGB; }
  19960. /** True if the image's format is RGB. */
  19961. bool isRGB() const throw() { return getFormat() == RGB; }
  19962. /** True if the image's format is a single-channel alpha map. */
  19963. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  19964. /** True if the image contains an alpha-channel. */
  19965. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  19966. /** Clears a section of the image with a given colour.
  19967. This won't do any alpha-blending - it just sets all pixels in the image to
  19968. the given colour (which may be non-opaque if the image has an alpha channel).
  19969. */
  19970. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  19971. /** Returns a rescaled version of this image.
  19972. A new image is returned which is a copy of this one, rescaled to the given size.
  19973. Note that if the new size is identical to the existing image, this will just return
  19974. a reference to the original image, and won't actually create a duplicate.
  19975. */
  19976. const Image rescaled (int newWidth, int newHeight,
  19977. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  19978. /** Returns a version of this image with a different image format.
  19979. A new image is returned which has been converted to the specified format.
  19980. Note that if the new format is no different to the current one, this will just return
  19981. a reference to the original image, and won't actually create a copy.
  19982. */
  19983. const Image convertedToFormat (PixelFormat newFormat) const;
  19984. /** Makes sure that no other Image objects share the same underlying data as this one.
  19985. If no other Image objects refer to the same shared data as this one, this method has no
  19986. effect. But if there are other references to the data, this will create a new copy of
  19987. the data internally.
  19988. Call this if you want to draw onto the image, but want to make sure that this doesn't
  19989. affect any other code that may be sharing the same data.
  19990. @see getReferenceCount
  19991. */
  19992. void duplicateIfShared();
  19993. /** Returns an image which refers to a subsection of this image.
  19994. This will not make a copy of the original - the new image will keep a reference to it, so that
  19995. if the original image is changed, the contents of the subsection will also change. Likewise if you
  19996. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  19997. you use operator= to make the original Image object refer to something else, the subsection image
  19998. won't pick up this change, it'll remain pointing at the original.
  19999. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  20000. image than the area you asked for, or even a null image if the area was out-of-bounds.
  20001. */
  20002. const Image getClippedImage (const Rectangle<int>& area) const;
  20003. /** Returns the colour of one of the pixels in the image.
  20004. If the co-ordinates given are beyond the image's boundaries, this will
  20005. return Colours::transparentBlack.
  20006. @see setPixelAt, Image::BitmapData::getPixelColour
  20007. */
  20008. const Colour getPixelAt (int x, int y) const;
  20009. /** Sets the colour of one of the image's pixels.
  20010. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  20011. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  20012. with the given one. The colour's opacity will be ignored if this image doesn't have
  20013. an alpha-channel.
  20014. @see getPixelAt, Image::BitmapData::setPixelColour
  20015. */
  20016. void setPixelAt (int x, int y, const Colour& colour);
  20017. /** Changes the opacity of a pixel.
  20018. This only has an effect if the image has an alpha channel and if the
  20019. given co-ordinates are inside the image's boundary.
  20020. The multiplier must be in the range 0 to 1.0, and the current alpha
  20021. at the given co-ordinates will be multiplied by this value.
  20022. @see setPixelAt
  20023. */
  20024. void multiplyAlphaAt (int x, int y, float multiplier);
  20025. /** Changes the overall opacity of the image.
  20026. This will multiply the alpha value of each pixel in the image by the given
  20027. amount (limiting the resulting alpha values between 0 and 255). This allows
  20028. you to make an image more or less transparent.
  20029. If the image doesn't have an alpha channel, this won't have any effect.
  20030. */
  20031. void multiplyAllAlphas (float amountToMultiplyBy);
  20032. /** Changes all the colours to be shades of grey, based on their current luminosity.
  20033. */
  20034. void desaturate();
  20035. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  20036. You should only use this class as a last resort - messing about with the internals of
  20037. an image is only recommended for people who really know what they're doing!
  20038. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  20039. hanging around while the image is being used elsewhere.
  20040. Depending on the way the image class is implemented, this may create a temporary buffer
  20041. which is copied back to the image when the object is deleted, or it may just get a pointer
  20042. directly into the image's raw data.
  20043. You can use the stride and data values in this class directly, but don't alter them!
  20044. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  20045. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  20046. */
  20047. class BitmapData
  20048. {
  20049. public:
  20050. BitmapData (Image& image, int x, int y, int w, int h, bool needsToBeWritable);
  20051. BitmapData (const Image& image, int x, int y, int w, int h);
  20052. BitmapData (const Image& image, bool needsToBeWritable);
  20053. ~BitmapData();
  20054. /** Returns a pointer to the start of a line in the image.
  20055. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  20056. sure it's not out-of-range.
  20057. */
  20058. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  20059. /** Returns a pointer to a pixel in the image.
  20060. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  20061. not out-of-range.
  20062. */
  20063. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  20064. /** Returns the colour of a given pixel.
  20065. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  20066. repsonsibility to make sure they're within the image's size.
  20067. */
  20068. const Colour getPixelColour (int x, int y) const throw();
  20069. /** Sets the colour of a given pixel.
  20070. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  20071. repsonsibility to make sure they're within the image's size.
  20072. */
  20073. void setPixelColour (int x, int y, const Colour& colour) const throw();
  20074. uint8* data;
  20075. const PixelFormat pixelFormat;
  20076. int lineStride, pixelStride, width, height;
  20077. private:
  20078. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  20079. };
  20080. /** Copies some pixel values to a rectangle of the image.
  20081. The format of the pixel data must match that of the image itself, and the
  20082. rectangle supplied must be within the image's bounds.
  20083. */
  20084. void setPixelData (int destX, int destY, int destW, int destH,
  20085. const uint8* sourcePixelData, int sourceLineStride);
  20086. /** Copies a section of the image to somewhere else within itself. */
  20087. void moveImageSection (int destX, int destY,
  20088. int sourceX, int sourceY,
  20089. int width, int height);
  20090. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  20091. of the image.
  20092. @param result the list that will have the area added to it
  20093. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  20094. above this level will be considered opaque
  20095. */
  20096. void createSolidAreaMask (RectangleList& result,
  20097. float alphaThreshold = 0.5f) const;
  20098. /** Returns a NamedValueSet that is attached to the image and which can be used for
  20099. associating custom values with it.
  20100. If this is a null image, this will return a null pointer.
  20101. */
  20102. NamedValueSet* getProperties() const;
  20103. /** Creates a context suitable for drawing onto this image.
  20104. Don't call this method directly! It's used internally by the Graphics class.
  20105. */
  20106. LowLevelGraphicsContext* createLowLevelContext() const;
  20107. /** Returns the number of Image objects which are currently referring to the same internal
  20108. shared image data.
  20109. @see duplicateIfShared
  20110. */
  20111. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  20112. /** This is a base class for task-specific types of image.
  20113. Don't use this class directly! It's used internally by the Image class.
  20114. */
  20115. class SharedImage : public ReferenceCountedObject
  20116. {
  20117. public:
  20118. SharedImage (PixelFormat format, int width, int height);
  20119. ~SharedImage();
  20120. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  20121. virtual SharedImage* clone() = 0;
  20122. virtual ImageType getType() const = 0;
  20123. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  20124. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  20125. const PixelFormat getPixelFormat() const throw() { return format; }
  20126. int getWidth() const throw() { return width; }
  20127. int getHeight() const throw() { return height; }
  20128. int getPixelStride() const throw() { return pixelStride; }
  20129. int getLineStride() const throw() { return lineStride; }
  20130. uint8* getPixelData (int x, int y) const throw();
  20131. protected:
  20132. friend class Image;
  20133. friend class BitmapData;
  20134. const PixelFormat format;
  20135. const int width, height;
  20136. int pixelStride, lineStride;
  20137. uint8* imageData;
  20138. NamedValueSet userData;
  20139. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  20140. };
  20141. /** @internal */
  20142. SharedImage* getSharedImage() const throw() { return image; }
  20143. /** @internal */
  20144. explicit Image (SharedImage* instance);
  20145. private:
  20146. friend class SharedImage;
  20147. friend class BitmapData;
  20148. ReferenceCountedObjectPtr<SharedImage> image;
  20149. JUCE_LEAK_DETECTOR (Image);
  20150. };
  20151. #endif // __JUCE_IMAGE_JUCEHEADER__
  20152. /*** End of inlined file: juce_Image.h ***/
  20153. /*** Start of inlined file: juce_RectangleList.h ***/
  20154. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  20155. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  20156. /**
  20157. Maintains a set of rectangles as a complex region.
  20158. This class allows a set of rectangles to be treated as a solid shape, and can
  20159. add and remove rectangular sections of it, and simplify overlapping or
  20160. adjacent rectangles.
  20161. @see Rectangle
  20162. */
  20163. class JUCE_API RectangleList
  20164. {
  20165. public:
  20166. /** Creates an empty RectangleList */
  20167. RectangleList() throw();
  20168. /** Creates a copy of another list */
  20169. RectangleList (const RectangleList& other);
  20170. /** Creates a list containing just one rectangle. */
  20171. RectangleList (const Rectangle<int>& rect);
  20172. /** Copies this list from another one. */
  20173. RectangleList& operator= (const RectangleList& other);
  20174. /** Destructor. */
  20175. ~RectangleList();
  20176. /** Returns true if the region is empty. */
  20177. bool isEmpty() const throw();
  20178. /** Returns the number of rectangles in the list. */
  20179. int getNumRectangles() const throw() { return rects.size(); }
  20180. /** Returns one of the rectangles at a particular index.
  20181. @returns the rectangle at the index, or an empty rectangle if the
  20182. index is out-of-range.
  20183. */
  20184. const Rectangle<int> getRectangle (int index) const throw();
  20185. /** Removes all rectangles to leave an empty region. */
  20186. void clear();
  20187. /** Merges a new rectangle into the list.
  20188. The rectangle being added will first be clipped to remove any parts of it
  20189. that overlap existing rectangles in the list.
  20190. */
  20191. void add (int x, int y, int width, int height);
  20192. /** Merges a new rectangle into the list.
  20193. The rectangle being added will first be clipped to remove any parts of it
  20194. that overlap existing rectangles in the list, and adjacent rectangles will be
  20195. merged into it.
  20196. */
  20197. void add (const Rectangle<int>& rect);
  20198. /** Dumbly adds a rectangle to the list without checking for overlaps.
  20199. This simply adds the rectangle to the end, it doesn't merge it or remove
  20200. any overlapping bits.
  20201. */
  20202. void addWithoutMerging (const Rectangle<int>& rect);
  20203. /** Merges another rectangle list into this one.
  20204. Any overlaps between the two lists will be clipped, so that the result is
  20205. the union of both lists.
  20206. */
  20207. void add (const RectangleList& other);
  20208. /** Removes a rectangular region from the list.
  20209. Any rectangles in the list which overlap this will be clipped and subdivided
  20210. if necessary.
  20211. */
  20212. void subtract (const Rectangle<int>& rect);
  20213. /** Removes all areas in another RectangleList from this one.
  20214. Any rectangles in the list which overlap this will be clipped and subdivided
  20215. if necessary.
  20216. @returns true if the resulting list is non-empty.
  20217. */
  20218. bool subtract (const RectangleList& otherList);
  20219. /** Removes any areas of the region that lie outside a given rectangle.
  20220. Any rectangles in the list which overlap this will be clipped and subdivided
  20221. if necessary.
  20222. Returns true if the resulting region is not empty, false if it is empty.
  20223. @see getIntersectionWith
  20224. */
  20225. bool clipTo (const Rectangle<int>& rect);
  20226. /** Removes any areas of the region that lie outside a given rectangle list.
  20227. Any rectangles in this object which overlap the specified list will be clipped
  20228. and subdivided if necessary.
  20229. Returns true if the resulting region is not empty, false if it is empty.
  20230. @see getIntersectionWith
  20231. */
  20232. bool clipTo (const RectangleList& other);
  20233. /** Creates a region which is the result of clipping this one to a given rectangle.
  20234. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  20235. resulting region into the list whose reference is passed-in.
  20236. Returns true if the resulting region is not empty, false if it is empty.
  20237. @see clipTo
  20238. */
  20239. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  20240. /** Swaps the contents of this and another list.
  20241. This swaps their internal pointers, so is hugely faster than using copy-by-value
  20242. to swap them.
  20243. */
  20244. void swapWith (RectangleList& otherList) throw();
  20245. /** Checks whether the region contains a given point.
  20246. @returns true if the point lies within one of the rectangles in the list
  20247. */
  20248. bool containsPoint (int x, int y) const throw();
  20249. /** Checks whether the region contains the whole of a given rectangle.
  20250. @returns true all parts of the rectangle passed in lie within the region
  20251. defined by this object
  20252. @see intersectsRectangle, containsPoint
  20253. */
  20254. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  20255. /** Checks whether the region contains any part of a given rectangle.
  20256. @returns true if any part of the rectangle passed in lies within the region
  20257. defined by this object
  20258. @see containsRectangle
  20259. */
  20260. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  20261. /** Checks whether this region intersects any part of another one.
  20262. @see intersectsRectangle
  20263. */
  20264. bool intersects (const RectangleList& other) const throw();
  20265. /** Returns the smallest rectangle that can enclose the whole of this region. */
  20266. const Rectangle<int> getBounds() const throw();
  20267. /** Optimises the list into a minimum number of constituent rectangles.
  20268. This will try to combine any adjacent rectangles into larger ones where
  20269. possible, to simplify lists that might have been fragmented by repeated
  20270. add/subtract calls.
  20271. */
  20272. void consolidate();
  20273. /** Adds an x and y value to all the co-ordinates. */
  20274. void offsetAll (int dx, int dy) throw();
  20275. /** Creates a Path object to represent this region. */
  20276. const Path toPath() const;
  20277. /** An iterator for accessing all the rectangles in a RectangleList. */
  20278. class Iterator
  20279. {
  20280. public:
  20281. Iterator (const RectangleList& list) throw();
  20282. ~Iterator();
  20283. /** Advances to the next rectangle, and returns true if it's not finished.
  20284. Call this before using getRectangle() to find the rectangle that was returned.
  20285. */
  20286. bool next() throw();
  20287. /** Returns the current rectangle. */
  20288. const Rectangle<int>* getRectangle() const throw() { return current; }
  20289. private:
  20290. const Rectangle<int>* current;
  20291. const RectangleList& owner;
  20292. int index;
  20293. JUCE_DECLARE_NON_COPYABLE (Iterator);
  20294. };
  20295. private:
  20296. friend class Iterator;
  20297. Array <Rectangle<int> > rects;
  20298. JUCE_LEAK_DETECTOR (RectangleList);
  20299. };
  20300. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  20301. /*** End of inlined file: juce_RectangleList.h ***/
  20302. /*** Start of inlined file: juce_BorderSize.h ***/
  20303. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  20304. #define __JUCE_BORDERSIZE_JUCEHEADER__
  20305. /**
  20306. Specifies a set of gaps to be left around the sides of a rectangle.
  20307. This is basically the size of the spaces at the top, bottom, left and right of
  20308. a rectangle. It's used by various component classes to specify borders.
  20309. @see Rectangle
  20310. */
  20311. class JUCE_API BorderSize
  20312. {
  20313. public:
  20314. /** Creates a null border.
  20315. All sizes are left as 0.
  20316. */
  20317. BorderSize() throw();
  20318. /** Creates a copy of another border. */
  20319. BorderSize (const BorderSize& other) throw();
  20320. /** Creates a border with the given gaps. */
  20321. BorderSize (int topGap,
  20322. int leftGap,
  20323. int bottomGap,
  20324. int rightGap) throw();
  20325. /** Creates a border with the given gap on all sides. */
  20326. explicit BorderSize (int allGaps) throw();
  20327. /** Destructor. */
  20328. ~BorderSize() throw();
  20329. /** Returns the gap that should be left at the top of the region. */
  20330. int getTop() const throw() { return top; }
  20331. /** Returns the gap that should be left at the top of the region. */
  20332. int getLeft() const throw() { return left; }
  20333. /** Returns the gap that should be left at the top of the region. */
  20334. int getBottom() const throw() { return bottom; }
  20335. /** Returns the gap that should be left at the top of the region. */
  20336. int getRight() const throw() { return right; }
  20337. /** Returns the sum of the top and bottom gaps. */
  20338. int getTopAndBottom() const throw() { return top + bottom; }
  20339. /** Returns the sum of the left and right gaps. */
  20340. int getLeftAndRight() const throw() { return left + right; }
  20341. /** Returns true if this border has no thickness along any edge. */
  20342. bool isEmpty() const throw() { return left + right + top + bottom == 0; }
  20343. /** Changes the top gap. */
  20344. void setTop (int newTopGap) throw();
  20345. /** Changes the left gap. */
  20346. void setLeft (int newLeftGap) throw();
  20347. /** Changes the bottom gap. */
  20348. void setBottom (int newBottomGap) throw();
  20349. /** Changes the right gap. */
  20350. void setRight (int newRightGap) throw();
  20351. /** Returns a rectangle with these borders removed from it. */
  20352. const Rectangle<int> subtractedFrom (const Rectangle<int>& original) const throw();
  20353. /** Removes this border from a given rectangle. */
  20354. void subtractFrom (Rectangle<int>& rectangle) const throw();
  20355. /** Returns a rectangle with these borders added around it. */
  20356. const Rectangle<int> addedTo (const Rectangle<int>& original) const throw();
  20357. /** Adds this border around a given rectangle. */
  20358. void addTo (Rectangle<int>& original) const throw();
  20359. bool operator== (const BorderSize& other) const throw();
  20360. bool operator!= (const BorderSize& other) const throw();
  20361. private:
  20362. int top, left, bottom, right;
  20363. JUCE_LEAK_DETECTOR (BorderSize);
  20364. };
  20365. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  20366. /*** End of inlined file: juce_BorderSize.h ***/
  20367. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  20368. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  20369. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  20370. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  20371. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20372. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20373. /**
  20374. Classes derived from this will be automatically deleted when the application exits.
  20375. After JUCEApplication::shutdown() has been called, any objects derived from
  20376. DeletedAtShutdown which are still in existence will be deleted in the reverse
  20377. order to that in which they were created.
  20378. So if you've got a singleton and don't want to have to explicitly delete it, just
  20379. inherit from this and it'll be taken care of.
  20380. */
  20381. class JUCE_API DeletedAtShutdown
  20382. {
  20383. protected:
  20384. /** Creates a DeletedAtShutdown object. */
  20385. DeletedAtShutdown();
  20386. /** Destructor.
  20387. It's ok to delete these objects explicitly - it's only the ones left
  20388. dangling at the end that will be deleted automatically.
  20389. */
  20390. virtual ~DeletedAtShutdown();
  20391. public:
  20392. /** Deletes all extant objects.
  20393. This shouldn't be used by applications, as it's called automatically
  20394. in the shutdown code of the JUCEApplication class.
  20395. */
  20396. static void deleteAll();
  20397. private:
  20398. static CriticalSection& getLock();
  20399. static Array <DeletedAtShutdown*>& getObjects();
  20400. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  20401. };
  20402. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20403. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  20404. /**
  20405. Manages the system's stack of modal components.
  20406. Normally you'll just use the Component methods to invoke modal states in components,
  20407. and won't have to deal with this class directly, but this is the singleton object that's
  20408. used internally to manage the stack.
  20409. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  20410. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  20411. */
  20412. class JUCE_API ModalComponentManager : public AsyncUpdater,
  20413. public DeletedAtShutdown
  20414. {
  20415. public:
  20416. /** Receives callbacks when a modal component is dismissed.
  20417. You can register a callback using Component::enterModalState() or
  20418. ModalComponentManager::attachCallback().
  20419. */
  20420. class Callback
  20421. {
  20422. public:
  20423. /** */
  20424. Callback() {}
  20425. /** Destructor. */
  20426. virtual ~Callback() {}
  20427. /** Called to indicate that a modal component has been dismissed.
  20428. You can register a callback using Component::enterModalState() or
  20429. ModalComponentManager::attachCallback().
  20430. The returnValue parameter is the value that was passed to Component::exitModalState()
  20431. when the component was dismissed.
  20432. The callback object will be deleted shortly after this method is called.
  20433. */
  20434. virtual void modalStateFinished (int returnValue) = 0;
  20435. };
  20436. /** Returns the number of components currently being shown modally.
  20437. @see getModalComponent
  20438. */
  20439. int getNumModalComponents() const;
  20440. /** Returns one of the components being shown modally.
  20441. An index of 0 is the most recently-shown, topmost component.
  20442. */
  20443. Component* getModalComponent (int index) const;
  20444. /** Returns true if the specified component is in a modal state. */
  20445. bool isModal (Component* component) const;
  20446. /** Returns true if the specified component is currently the topmost modal component. */
  20447. bool isFrontModalComponent (Component* component) const;
  20448. /** Adds a new callback that will be called when the specified modal component is dismissed.
  20449. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  20450. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  20451. called.
  20452. Each component can have any number of callbacks associated with it, and this one is added
  20453. to that list.
  20454. The object that is passed in will be deleted by the manager when it's no longer needed. If
  20455. the given component is not currently modal, the callback object is deleted immediately and
  20456. no action is taken.
  20457. */
  20458. void attachCallback (Component* component, Callback* callback);
  20459. /** Brings any modal components to the front. */
  20460. void bringModalComponentsToFront();
  20461. /** Runs the event loop until the currently topmost modal component is dismissed, and
  20462. returns the exit code for that component.
  20463. */
  20464. int runEventLoopForCurrentComponent();
  20465. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  20466. protected:
  20467. /** Creates a ModalComponentManager.
  20468. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  20469. */
  20470. ModalComponentManager();
  20471. /** Destructor. */
  20472. ~ModalComponentManager();
  20473. /** @internal */
  20474. void handleAsyncUpdate();
  20475. private:
  20476. class ModalItem;
  20477. class ReturnValueRetriever;
  20478. friend class Component;
  20479. friend class OwnedArray <ModalItem>;
  20480. OwnedArray <ModalItem> stack;
  20481. void startModal (Component* component, Callback* callback);
  20482. void endModal (Component* component, int returnValue);
  20483. void endModal (Component* component);
  20484. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  20485. };
  20486. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  20487. /*** End of inlined file: juce_ModalComponentManager.h ***/
  20488. class LookAndFeel;
  20489. class MouseInputSource;
  20490. class MouseInputSourceInternal;
  20491. class ComponentPeer;
  20492. class MarkerList;
  20493. class RelativeRectangle;
  20494. /**
  20495. The base class for all JUCE user-interface objects.
  20496. */
  20497. class JUCE_API Component : public MouseListener
  20498. {
  20499. public:
  20500. /** Creates a component.
  20501. To get it to actually appear, you'll also need to:
  20502. - Either add it to a parent component or use the addToDesktop() method to
  20503. make it a desktop window
  20504. - Set its size and position to something sensible
  20505. - Use setVisible() to make it visible
  20506. And for it to serve any useful purpose, you'll need to write a
  20507. subclass of Component or use one of the other types of component from
  20508. the library.
  20509. */
  20510. Component();
  20511. /** Destructor.
  20512. Note that when a component is deleted, any child components it contains are NOT
  20513. automatically deleted. It's your responsibilty to manage their lifespan - you
  20514. may want to use helper methods like deleteAllChildren(), or less haphazard
  20515. approaches like using ScopedPointers or normal object aggregation to manage them.
  20516. If the component being deleted is currently the child of another one, then during
  20517. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  20518. callback. Any ComponentListener objects that have registered with it will also have their
  20519. ComponentListener::componentBeingDeleted() methods called.
  20520. */
  20521. virtual ~Component();
  20522. /** Creates a component, setting its name at the same time.
  20523. @see getName, setName
  20524. */
  20525. explicit Component (const String& componentName);
  20526. /** Returns the name of this component.
  20527. @see setName
  20528. */
  20529. const String& getName() const throw() { return componentName; }
  20530. /** Sets the name of this component.
  20531. When the name changes, all registered ComponentListeners will receive a
  20532. ComponentListener::componentNameChanged() callback.
  20533. @see getName
  20534. */
  20535. virtual void setName (const String& newName);
  20536. /** Returns the ID string that was set by setComponentID().
  20537. @see setComponentID
  20538. */
  20539. const String& getComponentID() const throw() { return componentID; }
  20540. /** Sets the component's ID string.
  20541. You can retrieve the ID using getComponentID().
  20542. @see getComponentID
  20543. */
  20544. void setComponentID (const String& newID);
  20545. /** Makes the component visible or invisible.
  20546. This method will show or hide the component.
  20547. Note that components default to being non-visible when first created.
  20548. Also note that visible components won't be seen unless all their parent components
  20549. are also visible.
  20550. This method will call visibilityChanged() and also componentVisibilityChanged()
  20551. for any component listeners that are interested in this component.
  20552. @param shouldBeVisible whether to show or hide the component
  20553. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  20554. */
  20555. virtual void setVisible (bool shouldBeVisible);
  20556. /** Tests whether the component is visible or not.
  20557. this doesn't necessarily tell you whether this comp is actually on the screen
  20558. because this depends on whether all the parent components are also visible - use
  20559. isShowing() to find this out.
  20560. @see isShowing, setVisible
  20561. */
  20562. bool isVisible() const throw() { return flags.visibleFlag; }
  20563. /** Called when this component's visiblility changes.
  20564. @see setVisible, isVisible
  20565. */
  20566. virtual void visibilityChanged();
  20567. /** Tests whether this component and all its parents are visible.
  20568. @returns true only if this component and all its parents are visible.
  20569. @see isVisible
  20570. */
  20571. bool isShowing() const;
  20572. /** Makes this component appear as a window on the desktop.
  20573. Note that before calling this, you should make sure that the component's opacity is
  20574. set correctly using setOpaque(). If the component is non-opaque, the windowing
  20575. system will try to create a special transparent window for it, which will generally take
  20576. a lot more CPU to operate (and might not even be possible on some platforms).
  20577. If the component is inside a parent component at the time this method is called, it
  20578. will be first be removed from that parent. Likewise if a component on the desktop
  20579. is subsequently added to another component, it'll be removed from the desktop.
  20580. @param windowStyleFlags a combination of the flags specified in the
  20581. ComponentPeer::StyleFlags enum, which define the
  20582. window's characteristics.
  20583. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  20584. in which the juce component should place itself. On Windows,
  20585. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  20586. supported on all platforms, and best left as 0 unless you know
  20587. what you're doing
  20588. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  20589. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  20590. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  20591. */
  20592. virtual void addToDesktop (int windowStyleFlags,
  20593. void* nativeWindowToAttachTo = 0);
  20594. /** If the component is currently showing on the desktop, this will hide it.
  20595. You can also use setVisible() to hide a desktop window temporarily, but
  20596. removeFromDesktop() will free any system resources that are being used up.
  20597. @see addToDesktop, isOnDesktop
  20598. */
  20599. void removeFromDesktop();
  20600. /** Returns true if this component is currently showing on the desktop.
  20601. @see addToDesktop, removeFromDesktop
  20602. */
  20603. bool isOnDesktop() const throw();
  20604. /** Returns the heavyweight window that contains this component.
  20605. If this component is itself on the desktop, this will return the window
  20606. object that it is using. Otherwise, it will return the window of
  20607. its top-level parent component.
  20608. This may return 0 if there isn't a desktop component.
  20609. @see addToDesktop, isOnDesktop
  20610. */
  20611. ComponentPeer* getPeer() const;
  20612. /** For components on the desktop, this is called if the system wants to close the window.
  20613. This is a signal that either the user or the system wants the window to close. The
  20614. default implementation of this method will trigger an assertion to warn you that your
  20615. component should do something about it, but you can override this to ignore the event
  20616. if you want.
  20617. */
  20618. virtual void userTriedToCloseWindow();
  20619. /** Called for a desktop component which has just been minimised or un-minimised.
  20620. This will only be called for components on the desktop.
  20621. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  20622. */
  20623. virtual void minimisationStateChanged (bool isNowMinimised);
  20624. /** Brings the component to the front of its siblings.
  20625. If some of the component's siblings have had their 'always-on-top' flag set,
  20626. then they will still be kept in front of this one (unless of course this
  20627. one is also 'always-on-top').
  20628. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  20629. to the component (see grabKeyboardFocus() for more details)
  20630. @see toBack, toBehind, setAlwaysOnTop
  20631. */
  20632. void toFront (bool shouldAlsoGainFocus);
  20633. /** Changes this component's z-order to be at the back of all its siblings.
  20634. If the component is set to be 'always-on-top', it will only be moved to the
  20635. back of the other other 'always-on-top' components.
  20636. @see toFront, toBehind, setAlwaysOnTop
  20637. */
  20638. void toBack();
  20639. /** Changes this component's z-order so that it's just behind another component.
  20640. @see toFront, toBack
  20641. */
  20642. void toBehind (Component* other);
  20643. /** Sets whether the component should always be kept at the front of its siblings.
  20644. @see isAlwaysOnTop
  20645. */
  20646. void setAlwaysOnTop (bool shouldStayOnTop);
  20647. /** Returns true if this component is set to always stay in front of its siblings.
  20648. @see setAlwaysOnTop
  20649. */
  20650. bool isAlwaysOnTop() const throw();
  20651. /** Returns the x coordinate of the component's left edge.
  20652. This is a distance in pixels from the left edge of the component's parent.
  20653. Note that if you've used setTransform() to apply a transform, then the component's
  20654. bounds will no longer be a direct reflection of the position at which it appears within
  20655. its parent, as the transform will be applied to its bounding box.
  20656. */
  20657. inline int getX() const throw() { return bounds.getX(); }
  20658. /** Returns the y coordinate of the top of this component.
  20659. This is a distance in pixels from the top edge of the component's parent.
  20660. Note that if you've used setTransform() to apply a transform, then the component's
  20661. bounds will no longer be a direct reflection of the position at which it appears within
  20662. its parent, as the transform will be applied to its bounding box.
  20663. */
  20664. inline int getY() const throw() { return bounds.getY(); }
  20665. /** Returns the component's width in pixels. */
  20666. inline int getWidth() const throw() { return bounds.getWidth(); }
  20667. /** Returns the component's height in pixels. */
  20668. inline int getHeight() const throw() { return bounds.getHeight(); }
  20669. /** Returns the x coordinate of the component's right-hand edge.
  20670. This is a distance in pixels from the left edge of the component's parent.
  20671. Note that if you've used setTransform() to apply a transform, then the component's
  20672. bounds will no longer be a direct reflection of the position at which it appears within
  20673. its parent, as the transform will be applied to its bounding box.
  20674. */
  20675. int getRight() const throw() { return bounds.getRight(); }
  20676. /** Returns the component's top-left position as a Point. */
  20677. const Point<int> getPosition() const throw() { return bounds.getPosition(); }
  20678. /** Returns the y coordinate of the bottom edge of this component.
  20679. This is a distance in pixels from the top edge of the component's parent.
  20680. Note that if you've used setTransform() to apply a transform, then the component's
  20681. bounds will no longer be a direct reflection of the position at which it appears within
  20682. its parent, as the transform will be applied to its bounding box.
  20683. */
  20684. int getBottom() const throw() { return bounds.getBottom(); }
  20685. /** Returns this component's bounding box.
  20686. The rectangle returned is relative to the top-left of the component's parent.
  20687. Note that if you've used setTransform() to apply a transform, then the component's
  20688. bounds will no longer be a direct reflection of the position at which it appears within
  20689. its parent, as the transform will be applied to its bounding box.
  20690. */
  20691. const Rectangle<int>& getBounds() const throw() { return bounds; }
  20692. /** Returns the component's bounds, relative to its own origin.
  20693. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  20694. return a rectangle with position (0, 0), and the same size as this component.
  20695. */
  20696. const Rectangle<int> getLocalBounds() const throw();
  20697. /** Returns the area of this component's parent which this component covers.
  20698. The returned area is relative to the parent's coordinate space.
  20699. If the component has an affine transform specified, then the resulting area will be
  20700. the smallest rectangle that fully covers the component's transformed bounding box.
  20701. If this component has no parent, the return value will simply be the same as getBounds().
  20702. */
  20703. const Rectangle<int> getBoundsInParent() const throw();
  20704. /** Returns the region of this component that's not obscured by other, opaque components.
  20705. The RectangleList that is returned represents the area of this component
  20706. which isn't covered by opaque child components.
  20707. If includeSiblings is true, it will also take into account any siblings
  20708. that may be overlapping the component.
  20709. */
  20710. void getVisibleArea (RectangleList& result,
  20711. bool includeSiblings) const;
  20712. /** Returns this component's x coordinate relative the the screen's top-left origin.
  20713. @see getX, localPointToGlobal
  20714. */
  20715. int getScreenX() const;
  20716. /** Returns this component's y coordinate relative the the screen's top-left origin.
  20717. @see getY, localPointToGlobal
  20718. */
  20719. int getScreenY() const;
  20720. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  20721. @see getScreenBounds
  20722. */
  20723. const Point<int> getScreenPosition() const;
  20724. /** Returns the bounds of this component, relative to the screen's top-left.
  20725. @see getScreenPosition
  20726. */
  20727. const Rectangle<int> getScreenBounds() const;
  20728. /** Converts a point to be relative to this component's coordinate space.
  20729. This takes a point relative to a different component, and returns its position relative to this
  20730. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  20731. screen coordinate.
  20732. */
  20733. const Point<int> getLocalPoint (const Component* sourceComponent,
  20734. const Point<int>& pointRelativeToSourceComponent) const;
  20735. /** Converts a rectangle to be relative to this component's coordinate space.
  20736. This takes a rectangle that is relative to a different component, and returns its position relative
  20737. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  20738. a screen coordinate.
  20739. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  20740. may not actually be rectanglular when converted to the target space, so in that situation this will return
  20741. the smallest rectangle that fully contains the transformed area.
  20742. */
  20743. const Rectangle<int> getLocalArea (const Component* sourceComponent,
  20744. const Rectangle<int>& areaRelativeToSourceComponent) const;
  20745. /** Converts a point relative to this component's top-left into a screen coordinate.
  20746. @see getLocalPoint, localAreaToGlobal
  20747. */
  20748. const Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  20749. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  20750. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  20751. may not actually be rectanglular when converted to the target space, so in that situation this will return
  20752. the smallest rectangle that fully contains the transformed area.
  20753. @see getLocalPoint, localPointToGlobal
  20754. */
  20755. const Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  20756. /** Moves the component to a new position.
  20757. Changes the component's top-left position (without changing its size).
  20758. The position is relative to the top-left of the component's parent.
  20759. If the component actually moves, this method will make a synchronous call to moved().
  20760. Note that if you've used setTransform() to apply a transform, then the component's
  20761. bounds will no longer be a direct reflection of the position at which it appears within
  20762. its parent, as the transform will be applied to whatever bounds you set for it.
  20763. @see setBounds, ComponentListener::componentMovedOrResized
  20764. */
  20765. void setTopLeftPosition (int x, int y);
  20766. /** Moves the component to a new position.
  20767. Changes the position of the component's top-right corner (keeping it the same size).
  20768. The position is relative to the top-left of the component's parent.
  20769. If the component actually moves, this method will make a synchronous call to moved().
  20770. Note that if you've used setTransform() to apply a transform, then the component's
  20771. bounds will no longer be a direct reflection of the position at which it appears within
  20772. its parent, as the transform will be applied to whatever bounds you set for it.
  20773. */
  20774. void setTopRightPosition (int x, int y);
  20775. /** Changes the size of the component.
  20776. A synchronous call to resized() will be occur if the size actually changes.
  20777. Note that if you've used setTransform() to apply a transform, then the component's
  20778. bounds will no longer be a direct reflection of the position at which it appears within
  20779. its parent, as the transform will be applied to whatever bounds you set for it.
  20780. */
  20781. void setSize (int newWidth, int newHeight);
  20782. /** Changes the component's position and size.
  20783. The coordinates are relative to the top-left of the component's parent, or relative
  20784. to the origin of the screen is the component is on the desktop.
  20785. If this method changes the component's top-left position, it will make a synchronous
  20786. call to moved(). If it changes the size, it will also make a call to resized().
  20787. Note that if you've used setTransform() to apply a transform, then the component's
  20788. bounds will no longer be a direct reflection of the position at which it appears within
  20789. its parent, as the transform will be applied to whatever bounds you set for it.
  20790. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  20791. */
  20792. void setBounds (int x, int y, int width, int height);
  20793. /** Changes the component's position and size.
  20794. The coordinates are relative to the top-left of the component's parent, or relative
  20795. to the origin of the screen is the component is on the desktop.
  20796. If this method changes the component's top-left position, it will make a synchronous
  20797. call to moved(). If it changes the size, it will also make a call to resized().
  20798. Note that if you've used setTransform() to apply a transform, then the component's
  20799. bounds will no longer be a direct reflection of the position at which it appears within
  20800. its parent, as the transform will be applied to whatever bounds you set for it.
  20801. @see setBounds
  20802. */
  20803. void setBounds (const Rectangle<int>& newBounds);
  20804. /** Changes the component's position and size.
  20805. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  20806. to set the position, This uses a Component::Positioner to make sure that any dynamic
  20807. expressions are used in the RelativeRectangle will be automatically re-applied to the
  20808. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  20809. for more details.
  20810. When using relative expressions, the following symbols are available:
  20811. - "this.left", "this.right", "this.top", "this.bottom" refer to the position of those
  20812. edges in this component, so e.g. for a component whose width is always 100, you might
  20813. set the right edge to the "this.left + 100".
  20814. - "parent.left", "parent.right", "parent.top", "parent.bottom" refer to the parent component's
  20815. positions, in its own coordinate space, so "parent.left", "parent.right" are always 0, and
  20816. "parent.top", "parent.bottom" will actually be the width and height of the parent. So
  20817. for example to make your component's right-hand edge always 10 pixels away from its parent's
  20818. right-hand edge, you could set it to "parent.right - 10"
  20819. - "[id].left", "[id].right", "[id].top", "[id].bottom", where [id] is the identifier of one of
  20820. this component's siblings. A component's identifier is set with Component::setComponentID().
  20821. So for example if you want your component to always be 50 pixels to the right of the one
  20822. called "xyz", you could set your left edge to be "xyz.right + 50"
  20823. - The name of a marker that is defined in the parent component. For markers to be used, the parent
  20824. component must implement its Component::getMarkers() method, and return at least one
  20825. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  20826. marker called "foobar", you'd set it to "foobar + 10".
  20827. See the Expression class for details about the operators that are supported, but for example
  20828. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  20829. you could express it as:
  20830. @code myComp.setBounds (RelativeBounds ("parent.right / 2 - 50, parent.bottom / 2 - 50, this.left + 100, this.top + 100"));
  20831. @endcode
  20832. ..or an alternative way to achieve the same thing:
  20833. @code myComp.setBounds (RelativeBounds ("this.right - 100, this.bottom - 100, parent.right / 2 + 50, parent.bottom / 2 + 50"));
  20834. @endcode
  20835. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  20836. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  20837. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, this.left + 100, this.top + 100"));
  20838. @endcode
  20839. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  20840. be thrown!
  20841. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  20842. */
  20843. void setBounds (const RelativeRectangle& newBounds);
  20844. /** Changes the component's position and size in terms of fractions of its parent's size.
  20845. The values are factors of the parent's size, so for example
  20846. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  20847. width and height of the parent, with its top-left position 20% of
  20848. the way across and down the parent.
  20849. @see setBounds
  20850. */
  20851. void setBoundsRelative (float proportionalX, float proportionalY,
  20852. float proportionalWidth, float proportionalHeight);
  20853. /** Changes the component's position and size based on the amount of space to leave around it.
  20854. This will position the component within its parent, leaving the specified number of
  20855. pixels around each edge.
  20856. @see setBounds
  20857. */
  20858. void setBoundsInset (const BorderSize& borders);
  20859. /** Positions the component within a given rectangle, keeping its proportions
  20860. unchanged.
  20861. If onlyReduceInSize is false, the component will be resized to fill as much of the
  20862. rectangle as possible without changing its aspect ratio (the component's
  20863. current size is used to determine its aspect ratio, so a zero-size component
  20864. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  20865. too big to fit inside the rectangle.
  20866. It will then be positioned within the rectangle according to the justification flags
  20867. specified.
  20868. @see setBounds
  20869. */
  20870. void setBoundsToFit (int x, int y, int width, int height,
  20871. const Justification& justification,
  20872. bool onlyReduceInSize);
  20873. /** Changes the position of the component's centre.
  20874. Leaves the component's size unchanged, but sets the position of its centre
  20875. relative to its parent's top-left.
  20876. @see setBounds
  20877. */
  20878. void setCentrePosition (int x, int y);
  20879. /** Changes the position of the component's centre.
  20880. Leaves the position unchanged, but positions its centre relative to its
  20881. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  20882. its parent.
  20883. */
  20884. void setCentreRelative (float x, float y);
  20885. /** Changes the component's size and centres it within its parent.
  20886. After changing the size, the component will be moved so that it's
  20887. centred within its parent. If the component is on the desktop (or has no
  20888. parent component), then it'll be centred within the main monitor area.
  20889. */
  20890. void centreWithSize (int width, int height);
  20891. /** Sets a transform matrix to be applied to this component.
  20892. If you set a transform for a component, the component's position will be warped by it, relative to
  20893. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  20894. longer reflect the actual area within the parent that the component covers, as the bounds will be
  20895. transformed and the component will probably end up actually appearing somewhere else within its parent.
  20896. When using transforms you need to be extremely careful when converting coordinates between the
  20897. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  20898. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  20899. convert it between different components (but I'm sure you would never have done that anyway...).
  20900. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  20901. put a component on the desktop.
  20902. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  20903. */
  20904. void setTransform (const AffineTransform& transform);
  20905. /** Returns the transform that is currently being applied to this component.
  20906. For more details about transforms, see setTransform().
  20907. @see setTransform
  20908. */
  20909. const AffineTransform getTransform() const;
  20910. /** Returns true if a non-identity transform is being applied to this component.
  20911. For more details about transforms, see setTransform().
  20912. @see setTransform
  20913. */
  20914. bool isTransformed() const throw();
  20915. /** Returns a proportion of the component's width.
  20916. This is a handy equivalent of (getWidth() * proportion).
  20917. */
  20918. int proportionOfWidth (float proportion) const throw();
  20919. /** Returns a proportion of the component's height.
  20920. This is a handy equivalent of (getHeight() * proportion).
  20921. */
  20922. int proportionOfHeight (float proportion) const throw();
  20923. /** Returns the width of the component's parent.
  20924. If the component has no parent (i.e. if it's on the desktop), this will return
  20925. the width of the screen.
  20926. */
  20927. int getParentWidth() const throw();
  20928. /** Returns the height of the component's parent.
  20929. If the component has no parent (i.e. if it's on the desktop), this will return
  20930. the height of the screen.
  20931. */
  20932. int getParentHeight() const throw();
  20933. /** Returns the screen coordinates of the monitor that contains this component.
  20934. If there's only one monitor, this will return its size - if there are multiple
  20935. monitors, it will return the area of the monitor that contains the component's
  20936. centre.
  20937. */
  20938. const Rectangle<int> getParentMonitorArea() const;
  20939. /** Returns the number of child components that this component contains.
  20940. @see getChildComponent, getIndexOfChildComponent
  20941. */
  20942. int getNumChildComponents() const throw();
  20943. /** Returns one of this component's child components, by it index.
  20944. The component with index 0 is at the back of the z-order, the one at the
  20945. front will have index (getNumChildComponents() - 1).
  20946. If the index is out-of-range, this will return a null pointer.
  20947. @see getNumChildComponents, getIndexOfChildComponent
  20948. */
  20949. Component* getChildComponent (int index) const throw();
  20950. /** Returns the index of this component in the list of child components.
  20951. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  20952. values are further towards the front.
  20953. Returns -1 if the component passed-in is not a child of this component.
  20954. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  20955. */
  20956. int getIndexOfChildComponent (const Component* child) const throw();
  20957. /** Adds a child component to this one.
  20958. Adding a child component does not mean that the component will own or delete the child - it's
  20959. your responsibility to delete the component. Note that it's safe to delete a component
  20960. without first removing it from its parent - doing so will automatically remove it and
  20961. send out the appropriate notifications before the deletion completes.
  20962. If the child is already a child of this component, then no action will be taken, and its
  20963. z-order will be left unchanged.
  20964. @param child the new component to add. If the component passed-in is already
  20965. the child of another component, it'll first be removed from it current parent.
  20966. @param zOrder The index in the child-list at which this component should be inserted.
  20967. A value of -1 will insert it in front of the others, 0 is the back.
  20968. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  20969. */
  20970. void addChildComponent (Component* child, int zOrder = -1);
  20971. /** Adds a child component to this one, and also makes the child visible if it isn't.
  20972. Quite a useful function, this is just the same as calling setVisible (true) on the child
  20973. and then addChildComponent(). See addChildComponent() for more details.
  20974. */
  20975. void addAndMakeVisible (Component* child, int zOrder = -1);
  20976. /** Removes one of this component's child-components.
  20977. If the child passed-in isn't actually a child of this component (either because
  20978. it's invalid or is the child of a different parent), then no action is taken.
  20979. Note that removing a child will not delete it! But it's ok to delete a component
  20980. without first removing it - doing so will automatically remove it and send out the
  20981. appropriate notifications before the deletion completes.
  20982. @see addChildComponent, ComponentListener::componentChildrenChanged
  20983. */
  20984. void removeChildComponent (Component* childToRemove);
  20985. /** Removes one of this component's child-components by index.
  20986. This will return a pointer to the component that was removed, or null if
  20987. the index was out-of-range.
  20988. Note that removing a child will not delete it! But it's ok to delete a component
  20989. without first removing it - doing so will automatically remove it and send out the
  20990. appropriate notifications before the deletion completes.
  20991. @see addChildComponent, ComponentListener::componentChildrenChanged
  20992. */
  20993. Component* removeChildComponent (int childIndexToRemove);
  20994. /** Removes all this component's children.
  20995. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  20996. */
  20997. void removeAllChildren();
  20998. /** Removes all this component's children, and deletes them.
  20999. @see removeAllChildren
  21000. */
  21001. void deleteAllChildren();
  21002. /** Returns the component which this component is inside.
  21003. If this is the highest-level component or hasn't yet been added to
  21004. a parent, this will return null.
  21005. */
  21006. Component* getParentComponent() const throw() { return parentComponent; }
  21007. /** Searches the parent components for a component of a specified class.
  21008. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  21009. component that can be dynamically cast to a MyComp, or will return 0 if none
  21010. of the parents are suitable.
  21011. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  21012. */
  21013. template <class TargetClass>
  21014. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  21015. {
  21016. (void) dummyParameter;
  21017. Component* p = parentComponent;
  21018. while (p != 0)
  21019. {
  21020. TargetClass* target = dynamic_cast <TargetClass*> (p);
  21021. if (target != 0)
  21022. return target;
  21023. p = p->parentComponent;
  21024. }
  21025. return 0;
  21026. }
  21027. /** Returns the highest-level component which contains this one or its parents.
  21028. This will search upwards in the parent-hierarchy from this component, until it
  21029. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  21030. not yet added to a parent), and will return that.
  21031. */
  21032. Component* getTopLevelComponent() const throw();
  21033. /** Checks whether a component is anywhere inside this component or its children.
  21034. This will recursively check through this component's children to see if the
  21035. given component is anywhere inside.
  21036. */
  21037. bool isParentOf (const Component* possibleChild) const throw();
  21038. /** Called to indicate that the component's parents have changed.
  21039. When a component is added or removed from its parent, this method will
  21040. be called on all of its children (recursively - so all children of its
  21041. children will also be called as well).
  21042. Subclasses can override this if they need to react to this in some way.
  21043. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  21044. */
  21045. virtual void parentHierarchyChanged();
  21046. /** Subclasses can use this callback to be told when children are added or removed.
  21047. @see parentHierarchyChanged
  21048. */
  21049. virtual void childrenChanged();
  21050. /** Tests whether a given point inside the component.
  21051. Overriding this method allows you to create components which only intercept
  21052. mouse-clicks within a user-defined area.
  21053. This is called to find out whether a particular x, y coordinate is
  21054. considered to be inside the component or not, and is used by methods such
  21055. as contains() and getComponentAt() to work out which component
  21056. the mouse is clicked on.
  21057. Components with custom shapes will probably want to override it to perform
  21058. some more complex hit-testing.
  21059. The default implementation of this method returns either true or false,
  21060. depending on the value that was set by calling setInterceptsMouseClicks() (true
  21061. is the default return value).
  21062. Note that the hit-test region is not related to the opacity with which
  21063. areas of a component are painted.
  21064. Applications should never call hitTest() directly - instead use the
  21065. contains() method, because this will also test for occlusion by the
  21066. component's parent.
  21067. Note that for components on the desktop, this method will be ignored, because it's
  21068. not always possible to implement this behaviour on all platforms.
  21069. @param x the x coordinate to test, relative to the left hand edge of this
  21070. component. This value is guaranteed to be greater than or equal to
  21071. zero, and less than the component's width
  21072. @param y the y coordinate to test, relative to the top edge of this
  21073. component. This value is guaranteed to be greater than or equal to
  21074. zero, and less than the component's height
  21075. @returns true if the click is considered to be inside the component
  21076. @see setInterceptsMouseClicks, contains
  21077. */
  21078. virtual bool hitTest (int x, int y);
  21079. /** Changes the default return value for the hitTest() method.
  21080. Setting this to false is an easy way to make a component pass its mouse-clicks
  21081. through to the components behind it.
  21082. When a component is created, the default setting for this is true.
  21083. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  21084. return false (or true for child components if allowClicksOnChildComponents
  21085. is true)
  21086. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  21087. components can be clicked on as normal but clicks on this component pass
  21088. straight through; if this is false and allowClicksOnThisComponent
  21089. is false, then neither this component nor any child components can
  21090. be clicked on
  21091. @see hitTest, getInterceptsMouseClicks
  21092. */
  21093. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  21094. bool allowClicksOnChildComponents) throw();
  21095. /** Retrieves the current state of the mouse-click interception flags.
  21096. On return, the two parameters are set to the state used in the last call to
  21097. setInterceptsMouseClicks().
  21098. @see setInterceptsMouseClicks
  21099. */
  21100. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  21101. bool& allowsClicksOnChildComponents) const throw();
  21102. /** Returns true if a given point lies within this component or one of its children.
  21103. Never override this method! Use hitTest to create custom hit regions.
  21104. @param localPoint the coordinate to test, relative to this component's top-left.
  21105. @returns true if the point is within the component's hit-test area, but only if
  21106. that part of the component isn't clipped by its parent component. Note
  21107. that this won't take into account any overlapping sibling components
  21108. which might be in the way - for that, see reallyContains()
  21109. @see hitTest, reallyContains, getComponentAt
  21110. */
  21111. bool contains (const Point<int>& localPoint);
  21112. /** Returns true if a given point lies in this component, taking any overlapping
  21113. siblings into account.
  21114. @param localPoint the coordinate to test, relative to this component's top-left.
  21115. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  21116. this determines whether that is counted as a hit.
  21117. @see contains, getComponentAt
  21118. */
  21119. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  21120. /** Returns the component at a certain point within this one.
  21121. @param x the x coordinate to test, relative to this component's left edge.
  21122. @param y the y coordinate to test, relative to this component's top edge.
  21123. @returns the component that is at this position - which may be 0, this component,
  21124. or one of its children. Note that overlapping siblings that might actually
  21125. be in the way are not taken into account by this method - to account for these,
  21126. instead call getComponentAt on the top-level parent of this component.
  21127. @see hitTest, contains, reallyContains
  21128. */
  21129. Component* getComponentAt (int x, int y);
  21130. /** Returns the component at a certain point within this one.
  21131. @param position the coordinate to test, relative to this component's top-left.
  21132. @returns the component that is at this position - which may be 0, this component,
  21133. or one of its children. Note that overlapping siblings that might actually
  21134. be in the way are not taken into account by this method - to account for these,
  21135. instead call getComponentAt on the top-level parent of this component.
  21136. @see hitTest, contains, reallyContains
  21137. */
  21138. Component* getComponentAt (const Point<int>& position);
  21139. /** Marks the whole component as needing to be redrawn.
  21140. Calling this will not do any repainting immediately, but will mark the component
  21141. as 'dirty'. At some point in the near future the operating system will send a paint
  21142. message, which will redraw all the dirty regions of all components.
  21143. There's no guarantee about how soon after calling repaint() the redraw will actually
  21144. happen, and other queued events may be delivered before a redraw is done.
  21145. If the setBufferedToImage() method has been used to cause this component
  21146. to use a buffer, the repaint() call will invalidate the component's buffer.
  21147. To redraw just a subsection of the component rather than the whole thing,
  21148. use the repaint (int, int, int, int) method.
  21149. @see paint
  21150. */
  21151. void repaint();
  21152. /** Marks a subsection of this component as needing to be redrawn.
  21153. Calling this will not do any repainting immediately, but will mark the given region
  21154. of the component as 'dirty'. At some point in the near future the operating system
  21155. will send a paint message, which will redraw all the dirty regions of all components.
  21156. There's no guarantee about how soon after calling repaint() the redraw will actually
  21157. happen, and other queued events may be delivered before a redraw is done.
  21158. The region that is passed in will be clipped to keep it within the bounds of this
  21159. component.
  21160. @see repaint()
  21161. */
  21162. void repaint (int x, int y, int width, int height);
  21163. /** Marks a subsection of this component as needing to be redrawn.
  21164. Calling this will not do any repainting immediately, but will mark the given region
  21165. of the component as 'dirty'. At some point in the near future the operating system
  21166. will send a paint message, which will redraw all the dirty regions of all components.
  21167. There's no guarantee about how soon after calling repaint() the redraw will actually
  21168. happen, and other queued events may be delivered before a redraw is done.
  21169. The region that is passed in will be clipped to keep it within the bounds of this
  21170. component.
  21171. @see repaint()
  21172. */
  21173. void repaint (const Rectangle<int>& area);
  21174. /** Makes the component use an internal buffer to optimise its redrawing.
  21175. Setting this flag to true will cause the component to allocate an
  21176. internal buffer into which it paints itself, so that when asked to
  21177. redraw itself, it can use this buffer rather than actually calling the
  21178. paint() method.
  21179. The buffer is kept until the repaint() method is called directly on
  21180. this component (or until it is resized), when the image is invalidated
  21181. and then redrawn the next time the component is painted.
  21182. Note that only the drawing that happens within the component's paint()
  21183. method is drawn into the buffer, it's child components are not buffered, and
  21184. nor is the paintOverChildren() method.
  21185. @see repaint, paint, createComponentSnapshot
  21186. */
  21187. void setBufferedToImage (bool shouldBeBuffered);
  21188. /** Generates a snapshot of part of this component.
  21189. This will return a new Image, the size of the rectangle specified,
  21190. containing a snapshot of the specified area of the component and all
  21191. its children.
  21192. The image may or may not have an alpha-channel, depending on whether the
  21193. image is opaque or not.
  21194. If the clipImageToComponentBounds parameter is true and the area is greater than
  21195. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  21196. then parts of the component beyond its bounds can be drawn.
  21197. @see paintEntireComponent
  21198. */
  21199. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  21200. bool clipImageToComponentBounds = true);
  21201. /** Draws this component and all its subcomponents onto the specified graphics
  21202. context.
  21203. You should very rarely have to use this method, it's simply there in case you need
  21204. to draw a component with a custom graphics context for some reason, e.g. for
  21205. creating a snapshot of the component.
  21206. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  21207. on its children in order to render the entire tree.
  21208. The graphics context may be left in an undefined state after this method returns,
  21209. so you may need to reset it if you're going to use it again.
  21210. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  21211. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  21212. an alpha of 1.0 will be used.
  21213. */
  21214. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  21215. /** This allows you to indicate that this component doesn't require its graphics
  21216. context to be clipped when it is being painted.
  21217. Most people will never need to use this setting, but in situations where you have a very large
  21218. number of simple components being rendered, and where they are guaranteed never to do any drawing
  21219. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  21220. the graphics context that gets passed to the component's paint() callback.
  21221. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  21222. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  21223. artifacts. Your component also can't have any child components that may be placed beyond its
  21224. bounds.
  21225. */
  21226. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) throw();
  21227. /** Adds an effect filter to alter the component's appearance.
  21228. When a component has an effect filter set, then this is applied to the
  21229. results of its paint() method. There are a few preset effects, such as
  21230. a drop-shadow or glow, but they can be user-defined as well.
  21231. The effect that is passed in will not be deleted by the component - the
  21232. caller must take care of deleting it.
  21233. To remove an effect from a component, pass a null pointer in as the parameter.
  21234. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  21235. */
  21236. void setComponentEffect (ImageEffectFilter* newEffect);
  21237. /** Returns the current component effect.
  21238. @see setComponentEffect
  21239. */
  21240. ImageEffectFilter* getComponentEffect() const throw() { return effect; }
  21241. /** Finds the appropriate look-and-feel to use for this component.
  21242. If the component hasn't had a look-and-feel explicitly set, this will
  21243. return the parent's look-and-feel, or just the default one if there's no
  21244. parent.
  21245. @see setLookAndFeel, lookAndFeelChanged
  21246. */
  21247. LookAndFeel& getLookAndFeel() const throw();
  21248. /** Sets the look and feel to use for this component.
  21249. This will also change the look and feel for any child components that haven't
  21250. had their look set explicitly.
  21251. The object passed in will not be deleted by the component, so it's the caller's
  21252. responsibility to manage it. It may be used at any time until this component
  21253. has been deleted.
  21254. Calling this method will also invoke the sendLookAndFeelChange() method.
  21255. @see getLookAndFeel, lookAndFeelChanged
  21256. */
  21257. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  21258. /** Called to let the component react to a change in the look-and-feel setting.
  21259. When the look-and-feel is changed for a component, this will be called in
  21260. all its child components, recursively.
  21261. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  21262. an application uses a LookAndFeel class that might have changed internally.
  21263. @see sendLookAndFeelChange, getLookAndFeel
  21264. */
  21265. virtual void lookAndFeelChanged();
  21266. /** Calls the lookAndFeelChanged() method in this component and all its children.
  21267. This will recurse through the children and their children, calling lookAndFeelChanged()
  21268. on them all.
  21269. @see lookAndFeelChanged
  21270. */
  21271. void sendLookAndFeelChange();
  21272. /** Indicates whether any parts of the component might be transparent.
  21273. Components that always paint all of their contents with solid colour and
  21274. thus completely cover any components behind them should use this method
  21275. to tell the repaint system that they are opaque.
  21276. This information is used to optimise drawing, because it means that
  21277. objects underneath opaque windows don't need to be painted.
  21278. By default, components are considered transparent, unless this is used to
  21279. make it otherwise.
  21280. @see isOpaque, getVisibleArea
  21281. */
  21282. void setOpaque (bool shouldBeOpaque);
  21283. /** Returns true if no parts of this component are transparent.
  21284. @returns the value that was set by setOpaque, (the default being false)
  21285. @see setOpaque
  21286. */
  21287. bool isOpaque() const throw();
  21288. /** Indicates whether the component should be brought to the front when clicked.
  21289. Setting this flag to true will cause the component to be brought to the front
  21290. when the mouse is clicked somewhere inside it or its child components.
  21291. Note that a top-level desktop window might still be brought to the front by the
  21292. operating system when it's clicked, depending on how the OS works.
  21293. By default this is set to false.
  21294. @see setMouseClickGrabsKeyboardFocus
  21295. */
  21296. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  21297. /** Indicates whether the component should be brought to the front when clicked-on.
  21298. @see setBroughtToFrontOnMouseClick
  21299. */
  21300. bool isBroughtToFrontOnMouseClick() const throw();
  21301. // Keyboard focus methods
  21302. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  21303. By default components aren't actually interested in gaining the
  21304. focus, but this method can be used to turn this on.
  21305. See the grabKeyboardFocus() method for details about the way a component
  21306. is chosen to receive the focus.
  21307. @see grabKeyboardFocus, getWantsKeyboardFocus
  21308. */
  21309. void setWantsKeyboardFocus (bool wantsFocus) throw();
  21310. /** Returns true if the component is interested in getting keyboard focus.
  21311. This returns the flag set by setWantsKeyboardFocus(). The default
  21312. setting is false.
  21313. @see setWantsKeyboardFocus
  21314. */
  21315. bool getWantsKeyboardFocus() const throw();
  21316. /** Chooses whether a click on this component automatically grabs the focus.
  21317. By default this is set to true, but you might want a component which can
  21318. be focused, but where you don't want the user to be able to affect it directly
  21319. by clicking.
  21320. */
  21321. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  21322. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  21323. See setMouseClickGrabsKeyboardFocus() for more info.
  21324. */
  21325. bool getMouseClickGrabsKeyboardFocus() const throw();
  21326. /** Tries to give keyboard focus to this component.
  21327. When the user clicks on a component or its grabKeyboardFocus()
  21328. method is called, the following procedure is used to work out which
  21329. component should get it:
  21330. - if the component that was clicked on actually wants focus (as indicated
  21331. by calling getWantsKeyboardFocus), it gets it.
  21332. - if the component itself doesn't want focus, it will try to pass it
  21333. on to whichever of its children is the default component, as determined by
  21334. KeyboardFocusTraverser::getDefaultComponent()
  21335. - if none of its children want focus at all, it will pass it up to its
  21336. parent instead, unless it's a top-level component without a parent,
  21337. in which case it just takes the focus itself.
  21338. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  21339. getCurrentlyFocusedComponent, focusGained, focusLost,
  21340. keyPressed, keyStateChanged
  21341. */
  21342. void grabKeyboardFocus();
  21343. /** Returns true if this component currently has the keyboard focus.
  21344. @param trueIfChildIsFocused if this is true, then the method returns true if
  21345. either this component or any of its children (recursively)
  21346. have the focus. If false, the method only returns true if
  21347. this component has the focus.
  21348. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  21349. focusGained, focusLost
  21350. */
  21351. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  21352. /** Returns the component that currently has the keyboard focus.
  21353. @returns the focused component, or null if nothing is focused.
  21354. */
  21355. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  21356. /** Tries to move the keyboard focus to one of this component's siblings.
  21357. This will try to move focus to either the next or previous component. (This
  21358. is the method that is used when shifting focus by pressing the tab key).
  21359. Components for which getWantsKeyboardFocus() returns false are not looked at.
  21360. @param moveToNext if true, the focus will move forwards; if false, it will
  21361. move backwards
  21362. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  21363. */
  21364. void moveKeyboardFocusToSibling (bool moveToNext);
  21365. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  21366. which focus should be passed from this component.
  21367. The default implementation of this method will return a default
  21368. KeyboardFocusTraverser if this component is a focus container (as determined
  21369. by the setFocusContainer() method). If the component isn't a focus
  21370. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  21371. If you overrride this to return a custom KeyboardFocusTraverser, then
  21372. this component and all its sub-components will use the new object to
  21373. make their focusing decisions.
  21374. The method should return a new object, which the caller is required to
  21375. delete when no longer needed.
  21376. */
  21377. virtual KeyboardFocusTraverser* createFocusTraverser();
  21378. /** Returns the focus order of this component, if one has been specified.
  21379. By default components don't have a focus order - in that case, this
  21380. will return 0. Lower numbers indicate that the component will be
  21381. earlier in the focus traversal order.
  21382. To change the order, call setExplicitFocusOrder().
  21383. The focus order may be used by the KeyboardFocusTraverser class as part of
  21384. its algorithm for deciding the order in which components should be traversed.
  21385. See the KeyboardFocusTraverser class for more details on this.
  21386. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  21387. */
  21388. int getExplicitFocusOrder() const;
  21389. /** Sets the index used in determining the order in which focusable components
  21390. should be traversed.
  21391. A value of 0 or less is taken to mean that no explicit order is wanted, and
  21392. that traversal should use other factors, like the component's position.
  21393. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  21394. */
  21395. void setExplicitFocusOrder (int newFocusOrderIndex);
  21396. /** Indicates whether this component is a parent for components that can have
  21397. their focus traversed.
  21398. This flag is used by the default implementation of the createFocusTraverser()
  21399. method, which uses the flag to find the first parent component (of the currently
  21400. focused one) which wants to be a focus container.
  21401. So using this method to set the flag to 'true' causes this component to
  21402. act as the top level within which focus is passed around.
  21403. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  21404. */
  21405. void setFocusContainer (bool shouldBeFocusContainer) throw();
  21406. /** Returns true if this component has been marked as a focus container.
  21407. See setFocusContainer() for more details.
  21408. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  21409. */
  21410. bool isFocusContainer() const throw();
  21411. /** Returns true if the component (and all its parents) are enabled.
  21412. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  21413. what difference this makes to the component depends on the type. E.g. buttons
  21414. and sliders will choose to draw themselves differently, etc.
  21415. Note that if one of this component's parents is disabled, this will always
  21416. return false, even if this component itself is enabled.
  21417. @see setEnabled, enablementChanged
  21418. */
  21419. bool isEnabled() const throw();
  21420. /** Enables or disables this component.
  21421. Disabling a component will also cause all of its child components to become
  21422. disabled.
  21423. Similarly, enabling a component which is inside a disabled parent
  21424. component won't make any difference until the parent is re-enabled.
  21425. @see isEnabled, enablementChanged
  21426. */
  21427. void setEnabled (bool shouldBeEnabled);
  21428. /** Callback to indicate that this component has been enabled or disabled.
  21429. This can be triggered by one of the component's parent components
  21430. being enabled or disabled, as well as changes to the component itself.
  21431. The default implementation of this method does nothing; your class may
  21432. wish to repaint itself or something when this happens.
  21433. @see setEnabled, isEnabled
  21434. */
  21435. virtual void enablementChanged();
  21436. /** Changes the transparency of this component.
  21437. When painted, the entire component and all its children will be rendered
  21438. with this as the overall opacity level, where 0 is completely invisible, and
  21439. 1.0 is fully opaque (i.e. normal).
  21440. @see getAlpha
  21441. */
  21442. void setAlpha (float newAlpha);
  21443. /** Returns the component's current transparancy level.
  21444. See setAlpha() for more details.
  21445. */
  21446. float getAlpha() const;
  21447. /** Changes the mouse cursor shape to use when the mouse is over this component.
  21448. Note that the cursor set by this method can be overridden by the getMouseCursor
  21449. method.
  21450. @see MouseCursor
  21451. */
  21452. void setMouseCursor (const MouseCursor& cursorType);
  21453. /** Returns the mouse cursor shape to use when the mouse is over this component.
  21454. The default implementation will return the cursor that was set by setCursor()
  21455. but can be overridden for more specialised purposes, e.g. returning different
  21456. cursors depending on the mouse position.
  21457. @see MouseCursor
  21458. */
  21459. virtual const MouseCursor getMouseCursor();
  21460. /** Forces the current mouse cursor to be updated.
  21461. If you're overriding the getMouseCursor() method to control which cursor is
  21462. displayed, then this will only be checked each time the user moves the mouse. So
  21463. if you want to force the system to check that the cursor being displayed is
  21464. up-to-date (even if the mouse is just sitting there), call this method.
  21465. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  21466. calling this).
  21467. */
  21468. void updateMouseCursor() const;
  21469. /** Components can override this method to draw their content.
  21470. The paint() method gets called when a region of a component needs redrawing,
  21471. either because the component's repaint() method has been called, or because
  21472. something has happened on the screen that means a section of a window needs
  21473. to be redrawn.
  21474. Any child components will draw themselves over whatever this method draws. If
  21475. you need to paint over the top of your child components, you can also implement
  21476. the paintOverChildren() method to do this.
  21477. If you want to cause a component to redraw itself, this is done asynchronously -
  21478. calling the repaint() method marks a region of the component as "dirty", and the
  21479. paint() method will automatically be called sometime later, by the message thread,
  21480. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  21481. you never redraw something synchronously.
  21482. You should never need to call this method directly - to take a snapshot of the
  21483. component you could use createComponentSnapshot() or paintEntireComponent().
  21484. @param g the graphics context that must be used to do the drawing operations.
  21485. @see repaint, paintOverChildren, Graphics
  21486. */
  21487. virtual void paint (Graphics& g);
  21488. /** Components can override this method to draw over the top of their children.
  21489. For most drawing operations, it's better to use the normal paint() method,
  21490. but if you need to overlay something on top of the children, this can be
  21491. used.
  21492. @see paint, Graphics
  21493. */
  21494. virtual void paintOverChildren (Graphics& g);
  21495. /** Called when the mouse moves inside this component.
  21496. If the mouse button isn't pressed and the mouse moves over a component,
  21497. this will be called to let the component react to this.
  21498. A component will always get a mouseEnter callback before a mouseMove.
  21499. @param e details about the position and status of the mouse event
  21500. @see mouseEnter, mouseExit, mouseDrag, contains
  21501. */
  21502. virtual void mouseMove (const MouseEvent& e);
  21503. /** Called when the mouse first enters this component.
  21504. If the mouse button isn't pressed and the mouse moves into a component,
  21505. this will be called to let the component react to this.
  21506. When the mouse button is pressed and held down while being moved in
  21507. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  21508. mouseDrag messages are sent to the component that the mouse was originally
  21509. clicked on, until the button is released.
  21510. If you're writing a component that needs to repaint itself when the mouse
  21511. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  21512. method.
  21513. @param e details about the position and status of the mouse event
  21514. @see mouseExit, mouseDrag, mouseMove, contains
  21515. */
  21516. virtual void mouseEnter (const MouseEvent& e);
  21517. /** Called when the mouse moves out of this component.
  21518. This will be called when the mouse moves off the edge of this
  21519. component.
  21520. If the mouse button was pressed, and it was then dragged off the
  21521. edge of the component and released, then this callback will happen
  21522. when the button is released, after the mouseUp callback.
  21523. If you're writing a component that needs to repaint itself when the mouse
  21524. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  21525. method.
  21526. @param e details about the position and status of the mouse event
  21527. @see mouseEnter, mouseDrag, mouseMove, contains
  21528. */
  21529. virtual void mouseExit (const MouseEvent& e);
  21530. /** Called when a mouse button is pressed while it's over this component.
  21531. The MouseEvent object passed in contains lots of methods for finding out
  21532. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  21533. were held down at the time.
  21534. Once a button is held down, the mouseDrag method will be called when the
  21535. mouse moves, until the button is released.
  21536. @param e details about the position and status of the mouse event
  21537. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  21538. */
  21539. virtual void mouseDown (const MouseEvent& e);
  21540. /** Called when the mouse is moved while a button is held down.
  21541. When a mouse button is pressed inside a component, that component
  21542. receives mouseDrag callbacks each time the mouse moves, even if the
  21543. mouse strays outside the component's bounds.
  21544. If you want to be able to drag things off the edge of a component
  21545. and have the component scroll when you get to the edges, the
  21546. beginDragAutoRepeat() method might be useful.
  21547. @param e details about the position and status of the mouse event
  21548. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  21549. */
  21550. virtual void mouseDrag (const MouseEvent& e);
  21551. /** Called when a mouse button is released.
  21552. A mouseUp callback is sent to the component in which a button was pressed
  21553. even if the mouse is actually over a different component when the
  21554. button is released.
  21555. The MouseEvent object passed in contains lots of methods for finding out
  21556. which buttons were down just before they were released.
  21557. @param e details about the position and status of the mouse event
  21558. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  21559. */
  21560. virtual void mouseUp (const MouseEvent& e);
  21561. /** Called when a mouse button has been double-clicked in this component.
  21562. The MouseEvent object passed in contains lots of methods for finding out
  21563. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  21564. were held down at the time.
  21565. For altering the time limit used to detect double-clicks,
  21566. see MouseEvent::setDoubleClickTimeout.
  21567. @param e details about the position and status of the mouse event
  21568. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  21569. MouseEvent::getDoubleClickTimeout
  21570. */
  21571. virtual void mouseDoubleClick (const MouseEvent& e);
  21572. /** Called when the mouse-wheel is moved.
  21573. This callback is sent to the component that the mouse is over when the
  21574. wheel is moved.
  21575. If not overridden, the component will forward this message to its parent, so
  21576. that parent components can collect mouse-wheel messages that happen to
  21577. child components which aren't interested in them.
  21578. @param e details about the position and status of the mouse event
  21579. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  21580. value means the wheel has been pushed to the right, negative means it
  21581. was pushed to the left
  21582. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  21583. value means the wheel has been pushed upwards, negative means it
  21584. was pushed downwards
  21585. */
  21586. virtual void mouseWheelMove (const MouseEvent& e,
  21587. float wheelIncrementX,
  21588. float wheelIncrementY);
  21589. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  21590. current mouse-drag operation.
  21591. This allows you to make sure that mouseDrag() events are sent continuously, even
  21592. when the mouse isn't moving. This can be useful for things like auto-scrolling
  21593. components when the mouse is near an edge.
  21594. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  21595. minimum interval between consecutive mouse drag callbacks. The callbacks
  21596. will continue until the mouse is released, and then the interval will be reset,
  21597. so you need to make sure it's called every time you begin a drag event.
  21598. Passing an interval of 0 or less will cancel the auto-repeat.
  21599. @see mouseDrag, Desktop::beginDragAutoRepeat
  21600. */
  21601. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  21602. /** Causes automatic repaints when the mouse enters or exits this component.
  21603. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  21604. on the component, it will trigger a repaint.
  21605. This is handy for things like buttons that need to draw themselves differently when
  21606. the mouse moves over them, and it avoids having to override all the different mouse
  21607. callbacks and call repaint().
  21608. @see mouseEnter, mouseExit, mouseDown, mouseUp
  21609. */
  21610. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  21611. /** Registers a listener to be told when mouse events occur in this component.
  21612. If you need to get informed about mouse events in a component but can't or
  21613. don't want to override its methods, you can attach any number of listeners
  21614. to the component, and these will get told about the events in addition to
  21615. the component's own callbacks being called.
  21616. Note that a MouseListener can also be attached to more than one component.
  21617. @param newListener the listener to register
  21618. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  21619. for events that happen to any child component
  21620. within this component, including deeply-nested
  21621. child components. If false, it will only be
  21622. told about events that this component handles.
  21623. @see MouseListener, removeMouseListener
  21624. */
  21625. void addMouseListener (MouseListener* newListener,
  21626. bool wantsEventsForAllNestedChildComponents);
  21627. /** Deregisters a mouse listener.
  21628. @see addMouseListener, MouseListener
  21629. */
  21630. void removeMouseListener (MouseListener* listenerToRemove);
  21631. /** Adds a listener that wants to hear about keypresses that this component receives.
  21632. The listeners that are registered with a component are called by its keyPressed() or
  21633. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  21634. If you add an object as a key listener, be careful to remove it when the object
  21635. is deleted, or the component will be left with a dangling pointer.
  21636. @see keyPressed, keyStateChanged, removeKeyListener
  21637. */
  21638. void addKeyListener (KeyListener* newListener);
  21639. /** Removes a previously-registered key listener.
  21640. @see addKeyListener
  21641. */
  21642. void removeKeyListener (KeyListener* listenerToRemove);
  21643. /** Called when a key is pressed.
  21644. When a key is pressed, the component that has the keyboard focus will have this
  21645. method called. Remember that a component will only be given the focus if its
  21646. setWantsKeyboardFocus() method has been used to enable this.
  21647. If your implementation returns true, the event will be consumed and not passed
  21648. on to any other listeners. If it returns false, the key will be passed to any
  21649. KeyListeners that have been registered with this component. As soon as one of these
  21650. returns true, the process will stop, but if they all return false, the event will
  21651. be passed upwards to this component's parent, and so on.
  21652. The default implementation of this method does nothing and returns false.
  21653. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  21654. */
  21655. virtual bool keyPressed (const KeyPress& key);
  21656. /** Called when a key is pressed or released.
  21657. Whenever a key on the keyboard is pressed or released (including modifier keys
  21658. like shift and ctrl), this method will be called on the component that currently
  21659. has the keyboard focus. Remember that a component will only be given the focus if
  21660. its setWantsKeyboardFocus() method has been used to enable this.
  21661. If your implementation returns true, the event will be consumed and not passed
  21662. on to any other listeners. If it returns false, then any KeyListeners that have
  21663. been registered with this component will have their keyStateChanged methods called.
  21664. As soon as one of these returns true, the process will stop, but if they all return
  21665. false, the event will be passed upwards to this component's parent, and so on.
  21666. The default implementation of this method does nothing and returns false.
  21667. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  21668. method.
  21669. @param isKeyDown true if a key has been pressed; false if it has been released
  21670. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  21671. */
  21672. virtual bool keyStateChanged (bool isKeyDown);
  21673. /** Called when a modifier key is pressed or released.
  21674. Whenever the shift, control, alt or command keys are pressed or released,
  21675. this method will be called on the component that currently has the keyboard focus.
  21676. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  21677. method has been used to enable this.
  21678. The default implementation of this method actually calls its parent's modifierKeysChanged
  21679. method, so that focused components which aren't interested in this will give their
  21680. parents a chance to act on the event instead.
  21681. @see keyStateChanged, ModifierKeys
  21682. */
  21683. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  21684. /** Enumeration used by the focusChanged() and focusLost() methods. */
  21685. enum FocusChangeType
  21686. {
  21687. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  21688. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  21689. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  21690. };
  21691. /** Called to indicate that this component has just acquired the keyboard focus.
  21692. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  21693. */
  21694. virtual void focusGained (FocusChangeType cause);
  21695. /** Called to indicate that this component has just lost the keyboard focus.
  21696. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  21697. */
  21698. virtual void focusLost (FocusChangeType cause);
  21699. /** Called to indicate that one of this component's children has been focused or unfocused.
  21700. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  21701. changed. It happens when focus moves from one of this component's children (at any depth)
  21702. to a component that isn't contained in this one, (or vice-versa).
  21703. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  21704. */
  21705. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  21706. /** Returns true if the mouse is currently over this component.
  21707. If the mouse isn't over the component, this will return false, even if the
  21708. mouse is currently being dragged - so you can use this in your mouseDrag
  21709. method to find out whether it's really over the component or not.
  21710. Note that when the mouse button is being held down, then the only component
  21711. for which this method will return true is the one that was originally
  21712. clicked on.
  21713. If includeChildren is true, then this will also return true if the mouse is over
  21714. any of the component's children (recursively) as well as the component itself.
  21715. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  21716. */
  21717. bool isMouseOver (bool includeChildren = false) const;
  21718. /** Returns true if the mouse button is currently held down in this component.
  21719. Note that this is a test to see whether the mouse is being pressed in this
  21720. component, so it'll return false if called on component A when the mouse
  21721. is actually being dragged in component B.
  21722. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  21723. */
  21724. bool isMouseButtonDown() const throw();
  21725. /** True if the mouse is over this component, or if it's being dragged in this component.
  21726. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  21727. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  21728. */
  21729. bool isMouseOverOrDragging() const throw();
  21730. /** Returns true if a mouse button is currently down.
  21731. Unlike isMouseButtonDown, this will test the current state of the
  21732. buttons without regard to which component (if any) it has been
  21733. pressed in.
  21734. @see isMouseButtonDown, ModifierKeys
  21735. */
  21736. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  21737. /** Returns the mouse's current position, relative to this component.
  21738. The return value is relative to the component's top-left corner.
  21739. */
  21740. const Point<int> getMouseXYRelative() const;
  21741. /** Called when this component's size has been changed.
  21742. A component can implement this method to do things such as laying out its
  21743. child components when its width or height changes.
  21744. The method is called synchronously as a result of the setBounds or setSize
  21745. methods, so repeatedly changing a components size will repeatedly call its
  21746. resized method (unlike things like repainting, where multiple calls to repaint
  21747. are coalesced together).
  21748. If the component is a top-level window on the desktop, its size could also
  21749. be changed by operating-system factors beyond the application's control.
  21750. @see moved, setSize
  21751. */
  21752. virtual void resized();
  21753. /** Called when this component's position has been changed.
  21754. This is called when the position relative to its parent changes, not when
  21755. its absolute position on the screen changes (so it won't be called for
  21756. all child components when a parent component is moved).
  21757. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  21758. or any of the other repositioning methods, and like resized(), it will be
  21759. called each time those methods are called.
  21760. If the component is a top-level window on the desktop, its position could also
  21761. be changed by operating-system factors beyond the application's control.
  21762. @see resized, setBounds
  21763. */
  21764. virtual void moved();
  21765. /** Called when one of this component's children is moved or resized.
  21766. If the parent wants to know about changes to its immediate children (not
  21767. to children of its children), this is the method to override.
  21768. @see moved, resized, parentSizeChanged
  21769. */
  21770. virtual void childBoundsChanged (Component* child);
  21771. /** Called when this component's immediate parent has been resized.
  21772. If the component is a top-level window, this indicates that the screen size
  21773. has changed.
  21774. @see childBoundsChanged, moved, resized
  21775. */
  21776. virtual void parentSizeChanged();
  21777. /** Called when this component has been moved to the front of its siblings.
  21778. The component may have been brought to the front by the toFront() method, or
  21779. by the operating system if it's a top-level window.
  21780. @see toFront
  21781. */
  21782. virtual void broughtToFront();
  21783. /** Adds a listener to be told about changes to the component hierarchy or position.
  21784. Component listeners get called when this component's size, position or children
  21785. change - see the ComponentListener class for more details.
  21786. @param newListener the listener to register - if this is already registered, it
  21787. will be ignored.
  21788. @see ComponentListener, removeComponentListener
  21789. */
  21790. void addComponentListener (ComponentListener* newListener);
  21791. /** Removes a component listener.
  21792. @see addComponentListener
  21793. */
  21794. void removeComponentListener (ComponentListener* listenerToRemove);
  21795. /** Dispatches a numbered message to this component.
  21796. This is a quick and cheap way of allowing simple asynchronous messages to
  21797. be sent to components. It's also safe, because if the component that you
  21798. send the message to is a null or dangling pointer, this won't cause an error.
  21799. The command ID is later delivered to the component's handleCommandMessage() method by
  21800. the application's message queue.
  21801. @see handleCommandMessage
  21802. */
  21803. void postCommandMessage (int commandId);
  21804. /** Called to handle a command that was sent by postCommandMessage().
  21805. This is called by the message thread when a command message arrives, and
  21806. the component can override this method to process it in any way it needs to.
  21807. @see postCommandMessage
  21808. */
  21809. virtual void handleCommandMessage (int commandId);
  21810. /** Runs a component modally, waiting until the loop terminates.
  21811. This method first makes the component visible, brings it to the front and
  21812. gives it the keyboard focus.
  21813. It then runs a loop, dispatching messages from the system message queue, but
  21814. blocking all mouse or keyboard messages from reaching any components other
  21815. than this one and its children.
  21816. This loop continues until the component's exitModalState() method is called (or
  21817. the component is deleted), and then this method returns, returning the value
  21818. passed into exitModalState().
  21819. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  21820. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  21821. */
  21822. int runModalLoop();
  21823. /** Puts the component into a modal state.
  21824. This makes the component modal, so that messages are blocked from reaching
  21825. any components other than this one and its children, but unlike runModalLoop(),
  21826. this method returns immediately.
  21827. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  21828. get the focus, which is usually what you'll want it to do. If not, it will leave
  21829. the focus unchanged.
  21830. The callback is an optional object which will receive a callback when the modal
  21831. component loses its modal status, either by being hidden or when exitModalState()
  21832. is called. If you pass an object in here, the system will take care of deleting it
  21833. later, after making the callback
  21834. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  21835. */
  21836. void enterModalState (bool takeKeyboardFocus = true,
  21837. ModalComponentManager::Callback* callback = 0);
  21838. /** Ends a component's modal state.
  21839. If this component is currently modal, this will turn of its modalness, and return
  21840. a value to the runModalLoop() method that might have be running its modal loop.
  21841. @see runModalLoop, enterModalState, isCurrentlyModal
  21842. */
  21843. void exitModalState (int returnValue);
  21844. /** Returns true if this component is the modal one.
  21845. It's possible to have nested modal components, e.g. a pop-up dialog box
  21846. that launches another pop-up, but this will only return true for
  21847. the one at the top of the stack.
  21848. @see getCurrentlyModalComponent
  21849. */
  21850. bool isCurrentlyModal() const throw();
  21851. /** Returns the number of components that are currently in a modal state.
  21852. @see getCurrentlyModalComponent
  21853. */
  21854. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  21855. /** Returns one of the components that are currently modal.
  21856. The index specifies which of the possible modal components to return. The order
  21857. of the components in this list is the reverse of the order in which they became
  21858. modal - so the component at index 0 is always the active component, and the others
  21859. are progressively earlier ones that are themselves now blocked by later ones.
  21860. @returns the modal component, or null if no components are modal (or if the
  21861. index is out of range)
  21862. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  21863. */
  21864. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  21865. /** Checks whether there's a modal component somewhere that's stopping this one
  21866. from receiving messages.
  21867. If there is a modal component, its canModalEventBeSentToComponent() method
  21868. will be called to see if it will still allow this component to receive events.
  21869. @see runModalLoop, getCurrentlyModalComponent
  21870. */
  21871. bool isCurrentlyBlockedByAnotherModalComponent() const;
  21872. /** When a component is modal, this callback allows it to choose which other
  21873. components can still receive events.
  21874. When a modal component is active and the user clicks on a non-modal component,
  21875. this method is called on the modal component, and if it returns true, the
  21876. event is allowed to reach its target. If it returns false, the event is blocked
  21877. and the inputAttemptWhenModal() callback is made.
  21878. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  21879. implementation just returns false in all cases.
  21880. */
  21881. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  21882. /** Called when the user tries to click on a component that is blocked by another
  21883. modal component.
  21884. When a component is modal and the user clicks on one of the other components,
  21885. the modal component will receive this callback.
  21886. The default implementation of this method will play a beep, and bring the currently
  21887. modal component to the front, but it can be overridden to do other tasks.
  21888. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  21889. */
  21890. virtual void inputAttemptWhenModal();
  21891. /** Returns the set of properties that belong to this component.
  21892. Each component has a NamedValueSet object which you can use to attach arbitrary
  21893. items of data to it.
  21894. */
  21895. NamedValueSet& getProperties() throw() { return properties; }
  21896. /** Returns the set of properties that belong to this component.
  21897. Each component has a NamedValueSet object which you can use to attach arbitrary
  21898. items of data to it.
  21899. */
  21900. const NamedValueSet& getProperties() const throw() { return properties; }
  21901. /** Looks for a colour that has been registered with the given colour ID number.
  21902. If a colour has been set for this ID number using setColour(), then it is
  21903. returned. If none has been set, the method will try calling the component's
  21904. LookAndFeel class's findColour() method. If none has been registered with the
  21905. look-and-feel either, it will just return black.
  21906. The colour IDs for various purposes are stored as enums in the components that
  21907. they are relevent to - for an example, see Slider::ColourIds,
  21908. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  21909. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  21910. */
  21911. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  21912. /** Registers a colour to be used for a particular purpose.
  21913. Changing a colour will cause a synchronous callback to the colourChanged()
  21914. method, which your component can override if it needs to do something when
  21915. colours are altered.
  21916. For more details about colour IDs, see the comments for findColour().
  21917. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  21918. */
  21919. void setColour (int colourId, const Colour& colour);
  21920. /** If a colour has been set with setColour(), this will remove it.
  21921. This allows you to make a colour revert to its default state.
  21922. */
  21923. void removeColour (int colourId);
  21924. /** Returns true if the specified colour ID has been explicitly set for this
  21925. component using the setColour() method.
  21926. */
  21927. bool isColourSpecified (int colourId) const;
  21928. /** This looks for any colours that have been specified for this component,
  21929. and copies them to the specified target component.
  21930. */
  21931. void copyAllExplicitColoursTo (Component& target) const;
  21932. /** This method is called when a colour is changed by the setColour() method.
  21933. @see setColour, findColour
  21934. */
  21935. virtual void colourChanged();
  21936. /** Components can implement this method to provide a MarkerList.
  21937. The default implementation of this method returns 0, but you can override it to
  21938. return a pointer to the component's marker list. If xAxis is true, it should
  21939. return the X marker list; if false, it should return the Y markers.
  21940. */
  21941. virtual MarkerList* getMarkers (bool xAxis);
  21942. /** Returns the underlying native window handle for this component.
  21943. This is platform-dependent and strictly for power-users only!
  21944. */
  21945. void* getWindowHandle() const;
  21946. /** Holds a pointer to some type of Component, which automatically becomes null if
  21947. the component is deleted.
  21948. If you're using a component which may be deleted by another event that's outside
  21949. of your control, use a SafePointer instead of a normal pointer to refer to it,
  21950. and you can test whether it's null before using it to see if something has deleted
  21951. it.
  21952. The ComponentType typedef must be Component, or some subclass of Component.
  21953. You may also want to use a WeakReference<Component> object for the same purpose.
  21954. */
  21955. template <class ComponentType>
  21956. class SafePointer
  21957. {
  21958. public:
  21959. /** Creates a null SafePointer. */
  21960. SafePointer() throw() {}
  21961. /** Creates a SafePointer that points at the given component. */
  21962. SafePointer (ComponentType* const component) : weakRef (component) {}
  21963. /** Creates a copy of another SafePointer. */
  21964. SafePointer (const SafePointer& other) throw() : weakRef (other.weakRef) {}
  21965. /** Copies another pointer to this one. */
  21966. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  21967. /** Copies another pointer to this one. */
  21968. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  21969. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  21970. ComponentType* getComponent() const throw() { return dynamic_cast <ComponentType*> (weakRef.get()); }
  21971. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  21972. operator ComponentType*() const throw() { return getComponent(); }
  21973. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  21974. ComponentType* operator->() throw() { return getComponent(); }
  21975. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  21976. const ComponentType* operator->() const throw() { return getComponent(); }
  21977. /** If the component is valid, this deletes it and sets this pointer to null. */
  21978. void deleteAndZero() { delete getComponent(); jassert (getComponent() == 0); }
  21979. bool operator== (ComponentType* component) const throw() { return weakRef == component; }
  21980. bool operator!= (ComponentType* component) const throw() { return weakRef != component; }
  21981. private:
  21982. WeakReference<Component> weakRef;
  21983. };
  21984. /** A class to keep an eye on a component and check for it being deleted.
  21985. This is designed for use with the ListenerList::callChecked() methods, to allow
  21986. the list iterator to stop cleanly if the component is deleted by a listener callback
  21987. while the list is still being iterated.
  21988. */
  21989. class JUCE_API BailOutChecker
  21990. {
  21991. public:
  21992. /** Creates a checker that watches one component. */
  21993. BailOutChecker (Component* component);
  21994. /** Returns true if either of the two components have been deleted since this object was created. */
  21995. bool shouldBailOut() const throw();
  21996. private:
  21997. const WeakReference<Component> safePointer;
  21998. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  21999. };
  22000. /**
  22001. Base class for objects that can be used to automatically position a component according to
  22002. some kind of algorithm.
  22003. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  22004. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  22005. it might choose to watch some kind of value and move the component when the value changes).
  22006. */
  22007. class JUCE_API Positioner
  22008. {
  22009. public:
  22010. /** Creates a Positioner which can control the specified component. */
  22011. explicit Positioner (Component& component) throw();
  22012. /** Destructor. */
  22013. virtual ~Positioner() {}
  22014. /** Returns the component that this positioner controls. */
  22015. Component& getComponent() const throw() { return component; }
  22016. private:
  22017. Component& component;
  22018. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  22019. };
  22020. /** Returns the Positioner object that has been set for this component.
  22021. @see setPositioner()
  22022. */
  22023. Positioner* getPositioner() const throw();
  22024. /** Sets a new Positioner object for this component.
  22025. If there's currently another positioner set, it will be deleted. The object that is passed in
  22026. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  22027. to clear the current positioner.
  22028. @see getPositioner()
  22029. */
  22030. void setPositioner (Positioner* newPositioner);
  22031. #ifndef DOXYGEN
  22032. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  22033. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  22034. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  22035. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  22036. #endif
  22037. private:
  22038. friend class ComponentPeer;
  22039. friend class MouseInputSource;
  22040. friend class MouseInputSourceInternal;
  22041. #ifndef DOXYGEN
  22042. static Component* currentlyFocusedComponent;
  22043. String componentName, componentID;
  22044. Component* parentComponent;
  22045. Rectangle<int> bounds;
  22046. ScopedPointer <Positioner> positioner;
  22047. ScopedPointer <AffineTransform> affineTransform;
  22048. Array <Component*> childComponentList;
  22049. LookAndFeel* lookAndFeel;
  22050. MouseCursor cursor;
  22051. ImageEffectFilter* effect;
  22052. Image bufferedImage;
  22053. class MouseListenerList;
  22054. friend class MouseListenerList;
  22055. friend class ScopedPointer <MouseListenerList>;
  22056. ScopedPointer <MouseListenerList> mouseListeners;
  22057. ScopedPointer <Array <KeyListener*> > keyListeners;
  22058. ListenerList <ComponentListener> componentListeners;
  22059. NamedValueSet properties;
  22060. friend class WeakReference<Component>;
  22061. WeakReference<Component>::Master weakReferenceMaster;
  22062. const WeakReference<Component>::SharedRef& getWeakReference();
  22063. struct ComponentFlags
  22064. {
  22065. bool hasHeavyweightPeerFlag : 1;
  22066. bool visibleFlag : 1;
  22067. bool opaqueFlag : 1;
  22068. bool ignoresMouseClicksFlag : 1;
  22069. bool allowChildMouseClicksFlag : 1;
  22070. bool wantsFocusFlag : 1;
  22071. bool isFocusContainerFlag : 1;
  22072. bool dontFocusOnMouseClickFlag : 1;
  22073. bool alwaysOnTopFlag : 1;
  22074. bool bufferToImageFlag : 1;
  22075. bool bringToFrontOnClickFlag : 1;
  22076. bool repaintOnMouseActivityFlag : 1;
  22077. bool mouseDownFlag : 1;
  22078. bool mouseOverFlag : 1;
  22079. bool mouseInsideFlag : 1;
  22080. bool currentlyModalFlag : 1;
  22081. bool isDisabledFlag : 1;
  22082. bool childCompFocusedFlag : 1;
  22083. bool dontClipGraphicsFlag : 1;
  22084. #if JUCE_DEBUG
  22085. bool isInsidePaintCall : 1;
  22086. #endif
  22087. };
  22088. union
  22089. {
  22090. uint32 componentFlags;
  22091. ComponentFlags flags;
  22092. };
  22093. uint8 componentTransparency;
  22094. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  22095. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  22096. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  22097. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  22098. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  22099. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  22100. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  22101. void internalBroughtToFront();
  22102. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  22103. void internalFocusGain (const FocusChangeType cause);
  22104. void internalFocusLoss (const FocusChangeType cause);
  22105. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  22106. void internalModalInputAttempt();
  22107. void internalModifierKeysChanged();
  22108. void internalChildrenChanged();
  22109. void internalHierarchyChanged();
  22110. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  22111. void moveChildInternal (int sourceIndex, int destIndex);
  22112. void paintComponentAndChildren (Graphics& g);
  22113. void paintComponent (Graphics& g);
  22114. void paintWithinParentContext (Graphics& g);
  22115. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  22116. void repaintParent();
  22117. void sendFakeMouseMove() const;
  22118. void takeKeyboardFocus (const FocusChangeType cause);
  22119. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  22120. static void giveAwayFocus (bool sendFocusLossEvent);
  22121. void sendEnablementChangeMessage();
  22122. void sendVisibilityChangeMessage();
  22123. class ComponentHelpers;
  22124. friend class ComponentHelpers;
  22125. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  22126. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  22127. */
  22128. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  22129. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  22130. // This is included here just to cause a compile error if your code is still handling
  22131. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  22132. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  22133. // implement its methods instead of this Component method).
  22134. virtual void filesDropped (const StringArray&, int, int) {}
  22135. // This is included here to cause an error if you use or overload it - it has been deprecated in
  22136. // favour of contains (const Point<int>&)
  22137. void contains (int, int);
  22138. #endif
  22139. protected:
  22140. /** @internal */
  22141. virtual void internalRepaint (int x, int y, int w, int h);
  22142. /** @internal */
  22143. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  22144. #endif
  22145. };
  22146. #endif // __JUCE_COMPONENT_JUCEHEADER__
  22147. /*** End of inlined file: juce_Component.h ***/
  22148. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  22149. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  22150. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  22151. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  22152. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  22153. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  22154. /** A type used to hold the unique ID for an application command.
  22155. This is a numeric type, so it can be stored as an integer.
  22156. @see ApplicationCommandInfo, ApplicationCommandManager,
  22157. ApplicationCommandTarget, KeyPressMappingSet
  22158. */
  22159. typedef int CommandID;
  22160. /** A set of general-purpose application command IDs.
  22161. Because these commands are likely to be used in most apps, they're defined
  22162. here to help different apps to use the same numeric values for them.
  22163. Of course you don't have to use these, but some of them are used internally by
  22164. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  22165. @see ApplicationCommandInfo, ApplicationCommandManager,
  22166. ApplicationCommandTarget, KeyPressMappingSet
  22167. */
  22168. namespace StandardApplicationCommandIDs
  22169. {
  22170. /** This command ID should be used to send a "Quit the App" command.
  22171. This command is recognised by the JUCEApplication class, so if it is invoked
  22172. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  22173. object will catch it and call JUCEApplication::systemRequestedQuit().
  22174. */
  22175. static const CommandID quit = 0x1001;
  22176. /** The command ID that should be used to send a "Delete" command. */
  22177. static const CommandID del = 0x1002;
  22178. /** The command ID that should be used to send a "Cut" command. */
  22179. static const CommandID cut = 0x1003;
  22180. /** The command ID that should be used to send a "Copy to clipboard" command. */
  22181. static const CommandID copy = 0x1004;
  22182. /** The command ID that should be used to send a "Paste from clipboard" command. */
  22183. static const CommandID paste = 0x1005;
  22184. /** The command ID that should be used to send a "Select all" command. */
  22185. static const CommandID selectAll = 0x1006;
  22186. /** The command ID that should be used to send a "Deselect all" command. */
  22187. static const CommandID deselectAll = 0x1007;
  22188. }
  22189. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  22190. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  22191. /**
  22192. Holds information describing an application command.
  22193. This object is used to pass information about a particular command, such as its
  22194. name, description and other usage flags.
  22195. When an ApplicationCommandTarget is asked to provide information about the commands
  22196. it can perform, this is the structure gets filled-in to describe each one.
  22197. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  22198. ApplicationCommandManager
  22199. */
  22200. struct JUCE_API ApplicationCommandInfo
  22201. {
  22202. explicit ApplicationCommandInfo (CommandID commandID) throw();
  22203. /** Sets a number of the structures values at once.
  22204. The meanings of each of the parameters is described below, in the appropriate
  22205. member variable's description.
  22206. */
  22207. void setInfo (const String& shortName,
  22208. const String& description,
  22209. const String& categoryName,
  22210. int flags) throw();
  22211. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  22212. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  22213. is false, the bit is set.
  22214. */
  22215. void setActive (bool isActive) throw();
  22216. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  22217. */
  22218. void setTicked (bool isTicked) throw();
  22219. /** Handy method for adding a keypress to the defaultKeypresses array.
  22220. This is just so you can write things like:
  22221. @code
  22222. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  22223. @endcode
  22224. instead of
  22225. @code
  22226. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  22227. @endcode
  22228. */
  22229. void addDefaultKeypress (int keyCode,
  22230. const ModifierKeys& modifiers) throw();
  22231. /** The command's unique ID number.
  22232. */
  22233. CommandID commandID;
  22234. /** A short name to describe the command.
  22235. This should be suitable for use in menus, on buttons that trigger the command, etc.
  22236. You can use the setInfo() method to quickly set this and some of the command's
  22237. other properties.
  22238. */
  22239. String shortName;
  22240. /** A longer description of the command.
  22241. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  22242. pop-up tooltip describing what the command does.
  22243. You can use the setInfo() method to quickly set this and some of the command's
  22244. other properties.
  22245. */
  22246. String description;
  22247. /** A named category that the command fits into.
  22248. You can give your commands any category you like, and these will be displayed in
  22249. contexts such as the KeyMappingEditorComponent, where the category is used to group
  22250. commands together.
  22251. You can use the setInfo() method to quickly set this and some of the command's
  22252. other properties.
  22253. */
  22254. String categoryName;
  22255. /** A list of zero or more keypresses that should be used as the default keys for
  22256. this command.
  22257. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  22258. this list to initialise the default set of key-to-command mappings.
  22259. @see addDefaultKeypress
  22260. */
  22261. Array <KeyPress> defaultKeypresses;
  22262. /** Flags describing the ways in which this command should be used.
  22263. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  22264. variable.
  22265. */
  22266. enum CommandFlags
  22267. {
  22268. /** Indicates that the command can't currently be performed.
  22269. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  22270. not currently permissable to perform the command. If the flag is set, then
  22271. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  22272. command or show themselves as not being enabled.
  22273. @see ApplicationCommandInfo::setActive
  22274. */
  22275. isDisabled = 1 << 0,
  22276. /** Indicates that the command should have a tick next to it on a menu.
  22277. If your command is shown on a menu and this is set, it'll show a tick next to
  22278. it. Other components such as buttons may also use this flag to indicate that it
  22279. is a value that can be toggled, and is currently in the 'on' state.
  22280. @see ApplicationCommandInfo::setTicked
  22281. */
  22282. isTicked = 1 << 1,
  22283. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  22284. it will call the command twice, once on key-down and again on key-up.
  22285. @see ApplicationCommandTarget::InvocationInfo
  22286. */
  22287. wantsKeyUpDownCallbacks = 1 << 2,
  22288. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  22289. command in its list.
  22290. */
  22291. hiddenFromKeyEditor = 1 << 3,
  22292. /** If this flag is present, then a KeyMappingEditorComponent will display the
  22293. command in its list, but won't allow the assigned keypress to be changed.
  22294. */
  22295. readOnlyInKeyEditor = 1 << 4,
  22296. /** If this flag is present and the command is invoked from a keypress, then any
  22297. buttons or menus that are also connected to the command will not flash to
  22298. indicate that they've been triggered.
  22299. */
  22300. dontTriggerVisualFeedback = 1 << 5
  22301. };
  22302. /** A bitwise-OR of the values specified in the CommandFlags enum.
  22303. You can use the setInfo() method to quickly set this and some of the command's
  22304. other properties.
  22305. */
  22306. int flags;
  22307. };
  22308. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  22309. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  22310. /*** Start of inlined file: juce_MessageListener.h ***/
  22311. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  22312. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  22313. /**
  22314. MessageListener subclasses can post and receive Message objects.
  22315. @see Message, MessageManager, ActionListener, ChangeListener
  22316. */
  22317. class JUCE_API MessageListener
  22318. {
  22319. protected:
  22320. /** Creates a MessageListener. */
  22321. MessageListener() throw();
  22322. public:
  22323. /** Destructor.
  22324. When a MessageListener is deleted, it removes itself from a global list
  22325. of registered listeners, so that the isValidMessageListener() method
  22326. will no longer return true.
  22327. */
  22328. virtual ~MessageListener();
  22329. /** This is the callback method that receives incoming messages.
  22330. This is called by the MessageManager from its dispatch loop.
  22331. @see postMessage
  22332. */
  22333. virtual void handleMessage (const Message& message) = 0;
  22334. /** Sends a message to the message queue, for asynchronous delivery to this listener
  22335. later on.
  22336. This method can be called safely by any thread.
  22337. @param message the message object to send - this will be deleted
  22338. automatically by the message queue, so don't keep any
  22339. references to it after calling this method.
  22340. @see handleMessage
  22341. */
  22342. void postMessage (Message* message) const throw();
  22343. /** Checks whether this MessageListener has been deleted.
  22344. Although not foolproof, this method is safe to call on dangling or null
  22345. pointers. A list of active MessageListeners is kept internally, so this
  22346. checks whether the object is on this list or not.
  22347. Note that it's possible to get a false-positive here, if an object is
  22348. deleted and another is subsequently created that happens to be at the
  22349. exact same memory location, but I can't think of a good way of avoiding
  22350. this.
  22351. */
  22352. bool isValidMessageListener() const throw();
  22353. };
  22354. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  22355. /*** End of inlined file: juce_MessageListener.h ***/
  22356. /**
  22357. A command target publishes a list of command IDs that it can perform.
  22358. An ApplicationCommandManager despatches commands to targets, which must be
  22359. able to provide information about what commands they can handle.
  22360. To create a target, you'll need to inherit from this class, implementing all of
  22361. its pure virtual methods.
  22362. For info about how a target is chosen to receive a command, see
  22363. ApplicationCommandManager::getFirstCommandTarget().
  22364. @see ApplicationCommandManager, ApplicationCommandInfo
  22365. */
  22366. class JUCE_API ApplicationCommandTarget
  22367. {
  22368. public:
  22369. /** Creates a command target. */
  22370. ApplicationCommandTarget();
  22371. /** Destructor. */
  22372. virtual ~ApplicationCommandTarget();
  22373. /**
  22374. */
  22375. struct JUCE_API InvocationInfo
  22376. {
  22377. InvocationInfo (const CommandID commandID);
  22378. /** The UID of the command that should be performed. */
  22379. CommandID commandID;
  22380. /** The command's flags.
  22381. See ApplicationCommandInfo for a description of these flag values.
  22382. */
  22383. int commandFlags;
  22384. /** The types of context in which the command might be called. */
  22385. enum InvocationMethod
  22386. {
  22387. direct = 0, /**< The command is being invoked directly by a piece of code. */
  22388. fromKeyPress, /**< The command is being invoked by a key-press. */
  22389. fromMenu, /**< The command is being invoked by a menu selection. */
  22390. fromButton /**< The command is being invoked by a button click. */
  22391. };
  22392. /** The type of event that triggered this command. */
  22393. InvocationMethod invocationMethod;
  22394. /** If triggered by a keypress or menu, this will be the component that had the
  22395. keyboard focus at the time.
  22396. If triggered by a button, it may be set to that component, or it may be null.
  22397. */
  22398. Component* originatingComponent;
  22399. /** The keypress that was used to invoke it.
  22400. Note that this will be an invalid keypress if the command was invoked
  22401. by some other means than a keyboard shortcut.
  22402. */
  22403. KeyPress keyPress;
  22404. /** True if the callback is being invoked when the key is pressed,
  22405. false if the key is being released.
  22406. @see KeyPressMappingSet::addCommand()
  22407. */
  22408. bool isKeyDown;
  22409. /** If the key is being released, this indicates how long it had been held
  22410. down for.
  22411. (Only relevant if isKeyDown is false.)
  22412. */
  22413. int millisecsSinceKeyPressed;
  22414. };
  22415. /** This must return the next target to try after this one.
  22416. When a command is being sent, and the first target can't handle
  22417. that command, this method is used to determine the next target that should
  22418. be tried.
  22419. It may return 0 if it doesn't know of another target.
  22420. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  22421. method to return a parent component that might want to handle it.
  22422. @see invoke
  22423. */
  22424. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  22425. /** This must return a complete list of commands that this target can handle.
  22426. Your target should add all the command IDs that it handles to the array that is
  22427. passed-in.
  22428. */
  22429. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  22430. /** This must provide details about one of the commands that this target can perform.
  22431. This will be called with one of the command IDs that the target provided in its
  22432. getAllCommands() methods.
  22433. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  22434. suitable information about the command. (The commandID field will already have been filled-in
  22435. by the caller).
  22436. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  22437. set all the fields at once.
  22438. If the command is currently inactive for some reason, this method must use
  22439. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  22440. bit of the ApplicationCommandInfo::flags field).
  22441. Any default key-presses for the command should be appended to the
  22442. ApplicationCommandInfo::defaultKeypresses field.
  22443. Note that if you change something that affects the status of the commands
  22444. that would be returned by this method (e.g. something that makes some commands
  22445. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  22446. to cause the manager to refresh its status.
  22447. */
  22448. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  22449. /** This must actually perform the specified command.
  22450. If this target is able to perform the command specified by the commandID field of the
  22451. InvocationInfo structure, then it should do so, and must return true.
  22452. If it can't handle this command, it should return false, which tells the caller to pass
  22453. the command on to the next target in line.
  22454. @see invoke, ApplicationCommandManager::invoke
  22455. */
  22456. virtual bool perform (const InvocationInfo& info) = 0;
  22457. /** Makes this target invoke a command.
  22458. Your code can call this method to invoke a command on this target, but normally
  22459. you'd call it indirectly via ApplicationCommandManager::invoke() or
  22460. ApplicationCommandManager::invokeDirectly().
  22461. If this target can perform the given command, it will call its perform() method to
  22462. do so. If not, then getNextCommandTarget() will be used to determine the next target
  22463. to try, and the command will be passed along to it.
  22464. @param invocationInfo this must be correctly filled-in, describing the context for
  22465. the invocation.
  22466. @param asynchronously if false, the command will be performed before this method returns.
  22467. If true, a message will be posted so that the command will be performed
  22468. later on the message thread, and this method will return immediately.
  22469. @see perform, ApplicationCommandManager::invoke
  22470. */
  22471. bool invoke (const InvocationInfo& invocationInfo,
  22472. const bool asynchronously);
  22473. /** Invokes a given command directly on this target.
  22474. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  22475. structure.
  22476. */
  22477. bool invokeDirectly (const CommandID commandID,
  22478. const bool asynchronously);
  22479. /** Searches this target and all subsequent ones for the first one that can handle
  22480. the specified command.
  22481. This will use getNextCommandTarget() to determine the chain of targets to try
  22482. after this one.
  22483. */
  22484. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  22485. /** Checks whether this command can currently be performed by this target.
  22486. This will return true only if a call to getCommandInfo() doesn't set the
  22487. isDisabled flag to indicate that the command is inactive.
  22488. */
  22489. bool isCommandActive (const CommandID commandID);
  22490. /** If this object is a Component, this method will seach upwards in its current
  22491. UI hierarchy for the next parent component that implements the
  22492. ApplicationCommandTarget class.
  22493. If your target is a Component, this is a very handy method to use in your
  22494. getNextCommandTarget() implementation.
  22495. */
  22496. ApplicationCommandTarget* findFirstTargetParentComponent();
  22497. private:
  22498. // (for async invocation of commands)
  22499. class CommandTargetMessageInvoker : public MessageListener
  22500. {
  22501. public:
  22502. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  22503. ~CommandTargetMessageInvoker();
  22504. void handleMessage (const Message& message);
  22505. private:
  22506. ApplicationCommandTarget* const owner;
  22507. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  22508. };
  22509. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  22510. friend class CommandTargetMessageInvoker;
  22511. bool tryToInvoke (const InvocationInfo& info, bool async);
  22512. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  22513. };
  22514. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  22515. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  22516. /*** Start of inlined file: juce_ActionListener.h ***/
  22517. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  22518. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  22519. /**
  22520. Receives callbacks to indicate that some kind of event has occurred.
  22521. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  22522. about something that's happened.
  22523. @see ActionBroadcaster, ChangeListener
  22524. */
  22525. class JUCE_API ActionListener
  22526. {
  22527. public:
  22528. /** Destructor. */
  22529. virtual ~ActionListener() {}
  22530. /** Overridden by your subclass to receive the callback.
  22531. @param message the string that was specified when the event was triggered
  22532. by a call to ActionBroadcaster::sendActionMessage()
  22533. */
  22534. virtual void actionListenerCallback (const String& message) = 0;
  22535. };
  22536. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  22537. /*** End of inlined file: juce_ActionListener.h ***/
  22538. /**
  22539. An instance of this class is used to specify initialisation and shutdown
  22540. code for the application.
  22541. An application that wants to run in the JUCE framework needs to declare a
  22542. subclass of JUCEApplication and implement its various pure virtual methods.
  22543. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  22544. to declare an instance of this class and generate a suitable platform-specific
  22545. main() function.
  22546. e.g. @code
  22547. class MyJUCEApp : public JUCEApplication
  22548. {
  22549. public:
  22550. MyJUCEApp()
  22551. {
  22552. }
  22553. ~MyJUCEApp()
  22554. {
  22555. }
  22556. void initialise (const String& commandLine)
  22557. {
  22558. myMainWindow = new MyApplicationWindow();
  22559. myMainWindow->setBounds (100, 100, 400, 500);
  22560. myMainWindow->setVisible (true);
  22561. }
  22562. void shutdown()
  22563. {
  22564. myMainWindow = 0;
  22565. }
  22566. const String getApplicationName()
  22567. {
  22568. return "Super JUCE-o-matic";
  22569. }
  22570. const String getApplicationVersion()
  22571. {
  22572. return "1.0";
  22573. }
  22574. private:
  22575. ScopedPointer <MyApplicationWindow> myMainWindow;
  22576. };
  22577. // this creates wrapper code to actually launch the app properly.
  22578. START_JUCE_APPLICATION (MyJUCEApp)
  22579. @endcode
  22580. @see MessageManager, DeletedAtShutdown
  22581. */
  22582. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  22583. private ActionListener
  22584. {
  22585. protected:
  22586. /** Constructs a JUCE app object.
  22587. If subclasses implement a constructor or destructor, they shouldn't call any
  22588. JUCE code in there - put your startup/shutdown code in initialise() and
  22589. shutdown() instead.
  22590. */
  22591. JUCEApplication();
  22592. public:
  22593. /** Destructor.
  22594. If subclasses implement a constructor or destructor, they shouldn't call any
  22595. JUCE code in there - put your startup/shutdown code in initialise() and
  22596. shutdown() instead.
  22597. */
  22598. virtual ~JUCEApplication();
  22599. /** Returns the global instance of the application object being run. */
  22600. static JUCEApplication* getInstance() throw() { return appInstance; }
  22601. /** Called when the application starts.
  22602. This will be called once to let the application do whatever initialisation
  22603. it needs, create its windows, etc.
  22604. After the method returns, the normal event-dispatch loop will be run,
  22605. until the quit() method is called, at which point the shutdown()
  22606. method will be called to let the application clear up anything it needs
  22607. to delete.
  22608. If during the initialise() method, the application decides not to start-up
  22609. after all, it can just call the quit() method and the event loop won't be run.
  22610. @param commandLineParameters the line passed in does not include the
  22611. name of the executable, just the parameter list.
  22612. @see shutdown, quit
  22613. */
  22614. virtual void initialise (const String& commandLineParameters) = 0;
  22615. /** Returns true if the application hasn't yet completed its initialise() method
  22616. and entered the main event loop.
  22617. This is handy for things like splash screens to know when the app's up-and-running
  22618. properly.
  22619. */
  22620. bool isInitialising() const throw() { return stillInitialising; }
  22621. /* Called to allow the application to clear up before exiting.
  22622. After JUCEApplication::quit() has been called, the event-dispatch loop will
  22623. terminate, and this method will get called to allow the app to sort itself
  22624. out.
  22625. Be careful that nothing happens in this method that might rely on messages
  22626. being sent, or any kind of window activity, because the message loop is no
  22627. longer running at this point.
  22628. @see DeletedAtShutdown
  22629. */
  22630. virtual void shutdown() = 0;
  22631. /** Returns the application's name.
  22632. An application must implement this to name itself.
  22633. */
  22634. virtual const String getApplicationName() = 0;
  22635. /** Returns the application's version number.
  22636. */
  22637. virtual const String getApplicationVersion() = 0;
  22638. /** Checks whether multiple instances of the app are allowed.
  22639. If you application class returns true for this, more than one instance is
  22640. permitted to run (except on the Mac where this isn't possible).
  22641. If it's false, the second instance won't start, but it you will still get a
  22642. callback to anotherInstanceStarted() to tell you about this - which
  22643. gives you a chance to react to what the user was trying to do.
  22644. */
  22645. virtual bool moreThanOneInstanceAllowed();
  22646. /** Indicates that the user has tried to start up another instance of the app.
  22647. This will get called even if moreThanOneInstanceAllowed() is false.
  22648. */
  22649. virtual void anotherInstanceStarted (const String& commandLine);
  22650. /** Called when the operating system is trying to close the application.
  22651. The default implementation of this method is to call quit(), but it may
  22652. be overloaded to ignore the request or do some other special behaviour
  22653. instead. For example, you might want to offer the user the chance to save
  22654. their changes before quitting, and give them the chance to cancel.
  22655. If you want to send a quit signal to your app, this is the correct method
  22656. to call, because it means that requests that come from the system get handled
  22657. in the same way as those from your own application code. So e.g. you'd
  22658. call this method from a "quit" item on a menu bar.
  22659. */
  22660. virtual void systemRequestedQuit();
  22661. /** If any unhandled exceptions make it through to the message dispatch loop, this
  22662. callback will be triggered, in case you want to log them or do some other
  22663. type of error-handling.
  22664. If the type of exception is derived from the std::exception class, the pointer
  22665. passed-in will be valid. If the exception is of unknown type, this pointer
  22666. will be null.
  22667. */
  22668. virtual void unhandledException (const std::exception* e,
  22669. const String& sourceFilename,
  22670. int lineNumber);
  22671. /** Signals that the main message loop should stop and the application should terminate.
  22672. This isn't synchronous, it just posts a quit message to the main queue, and
  22673. when this message arrives, the message loop will stop, the shutdown() method
  22674. will be called, and the app will exit.
  22675. Note that this will cause an unconditional quit to happen, so if you need an
  22676. extra level before this, e.g. to give the user the chance to save their work
  22677. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  22678. method - see that method's help for more info.
  22679. @see MessageManager, DeletedAtShutdown
  22680. */
  22681. static void quit();
  22682. /** Sets the value that should be returned as the application's exit code when the
  22683. app quits.
  22684. This is the value that's returned by the main() function. Normally you'd leave this
  22685. as 0 unless you want to indicate an error code.
  22686. @see getApplicationReturnValue
  22687. */
  22688. void setApplicationReturnValue (int newReturnValue) throw();
  22689. /** Returns the value that has been set as the application's exit code.
  22690. @see setApplicationReturnValue
  22691. */
  22692. int getApplicationReturnValue() const throw() { return appReturnValue; }
  22693. /** Returns the application's command line params.
  22694. */
  22695. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  22696. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  22697. /** @internal */
  22698. static int main (const String& commandLine);
  22699. /** @internal */
  22700. static int main (int argc, const char* argv[]);
  22701. /** @internal */
  22702. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  22703. /** Returns true if this executable is running as an app (as opposed to being a plugin
  22704. or other kind of shared library. */
  22705. static inline bool isStandaloneApp() throw() { return createInstance != 0; }
  22706. /** @internal */
  22707. ApplicationCommandTarget* getNextCommandTarget();
  22708. /** @internal */
  22709. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  22710. /** @internal */
  22711. void getAllCommands (Array <CommandID>& commands);
  22712. /** @internal */
  22713. bool perform (const InvocationInfo& info);
  22714. /** @internal */
  22715. void actionListenerCallback (const String& message);
  22716. /** @internal */
  22717. bool initialiseApp (const String& commandLine);
  22718. /** @internal */
  22719. int shutdownApp();
  22720. /** @internal */
  22721. static void appWillTerminateByForce();
  22722. /** @internal */
  22723. typedef JUCEApplication* (*CreateInstanceFunction)();
  22724. /** @internal */
  22725. static CreateInstanceFunction createInstance;
  22726. private:
  22727. String commandLineParameters;
  22728. int appReturnValue;
  22729. bool stillInitialising;
  22730. ScopedPointer<InterProcessLock> appLock;
  22731. static JUCEApplication* appInstance;
  22732. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  22733. };
  22734. #endif // __JUCE_APPLICATION_JUCEHEADER__
  22735. /*** End of inlined file: juce_Application.h ***/
  22736. #endif
  22737. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  22738. #endif
  22739. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  22740. #endif
  22741. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  22742. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  22743. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  22744. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  22745. /*** Start of inlined file: juce_Desktop.h ***/
  22746. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  22747. #define __JUCE_DESKTOP_JUCEHEADER__
  22748. /*** Start of inlined file: juce_Timer.h ***/
  22749. #ifndef __JUCE_TIMER_JUCEHEADER__
  22750. #define __JUCE_TIMER_JUCEHEADER__
  22751. class InternalTimerThread;
  22752. /**
  22753. Makes repeated callbacks to a virtual method at a specified time interval.
  22754. A Timer's timerCallback() method will be repeatedly called at a given
  22755. interval. When you create a Timer object, it will do nothing until the
  22756. startTimer() method is called, which will cause the message thread to
  22757. start making callbacks at the specified interval, until stopTimer() is called
  22758. or the object is deleted.
  22759. The time interval isn't guaranteed to be precise to any more than maybe
  22760. 10-20ms, and the intervals may end up being much longer than requested if the
  22761. system is busy. Because the callbacks are made by the main message thread,
  22762. anything that blocks the message queue for a period of time will also prevent
  22763. any timers from running until it can carry on.
  22764. If you need to have a single callback that is shared by multiple timers with
  22765. different frequencies, then the MultiTimer class allows you to do that - its
  22766. structure is very similar to the Timer class, but contains multiple timers
  22767. internally, each one identified by an ID number.
  22768. @see MultiTimer
  22769. */
  22770. class JUCE_API Timer
  22771. {
  22772. protected:
  22773. /** Creates a Timer.
  22774. When created, the timer is stopped, so use startTimer() to get it going.
  22775. */
  22776. Timer() throw();
  22777. /** Creates a copy of another timer.
  22778. Note that this timer won't be started, even if the one you're copying
  22779. is running.
  22780. */
  22781. Timer (const Timer& other) throw();
  22782. public:
  22783. /** Destructor. */
  22784. virtual ~Timer();
  22785. /** The user-defined callback routine that actually gets called periodically.
  22786. It's perfectly ok to call startTimer() or stopTimer() from within this
  22787. callback to change the subsequent intervals.
  22788. */
  22789. virtual void timerCallback() = 0;
  22790. /** Starts the timer and sets the length of interval required.
  22791. If the timer is already started, this will reset it, so the
  22792. time between calling this method and the next timer callback
  22793. will not be less than the interval length passed in.
  22794. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  22795. rounded up to 1)
  22796. */
  22797. void startTimer (int intervalInMilliseconds) throw();
  22798. /** Stops the timer.
  22799. No more callbacks will be made after this method returns.
  22800. If this is called from a different thread, any callbacks that may
  22801. be currently executing may be allowed to finish before the method
  22802. returns.
  22803. */
  22804. void stopTimer() throw();
  22805. /** Checks if the timer has been started.
  22806. @returns true if the timer is running.
  22807. */
  22808. bool isTimerRunning() const throw() { return periodMs > 0; }
  22809. /** Returns the timer's interval.
  22810. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  22811. */
  22812. int getTimerInterval() const throw() { return periodMs; }
  22813. private:
  22814. friend class InternalTimerThread;
  22815. int countdownMs, periodMs;
  22816. Timer* previous;
  22817. Timer* next;
  22818. Timer& operator= (const Timer&);
  22819. };
  22820. #endif // __JUCE_TIMER_JUCEHEADER__
  22821. /*** End of inlined file: juce_Timer.h ***/
  22822. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  22823. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  22824. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  22825. /**
  22826. Animates a set of components, moving them to a new position and/or fading their
  22827. alpha levels.
  22828. To animate a component, create a ComponentAnimator instance or (preferably) use the
  22829. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  22830. method to commence the movement.
  22831. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  22832. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  22833. destinations.
  22834. It's ok to delete components while they're being animated - the animator will detect this
  22835. and safely stop using them.
  22836. The class is a ChangeBroadcaster and sends a notification when any components
  22837. start or finish being animated.
  22838. @see Desktop::getAnimator
  22839. */
  22840. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  22841. private Timer
  22842. {
  22843. public:
  22844. /** Creates a ComponentAnimator. */
  22845. ComponentAnimator();
  22846. /** Destructor. */
  22847. ~ComponentAnimator();
  22848. /** Starts a component moving from its current position to a specified position.
  22849. If the component is already in the middle of an animation, that will be abandoned,
  22850. and a new animation will begin, moving the component from its current location.
  22851. The start and end speed parameters let you apply some acceleration to the component's
  22852. movement.
  22853. @param component the component to move
  22854. @param finalBounds the destination bounds to which the component should move. To leave the
  22855. component in the same place, just pass component->getBounds() for this value
  22856. @param finalAlpha the alpha value that the component should have at the end of the animation
  22857. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  22858. @param useProxyComponent if true, this means the component should be replaced by an internally
  22859. managed temporary component which is a snapshot of the original component.
  22860. This avoids the component having to paint itself as it moves, so may
  22861. be more efficient. This option also allows you to delete the original
  22862. component immediately after starting the animation, because the animation
  22863. can proceed without it. If you use a proxy, the original component will be
  22864. made invisible by this call, and then will become visible again at the end
  22865. of the animation. It'll also mean that the proxy component will be temporarily
  22866. added to the component's parent, so avoid it if this might confuse the parent
  22867. component, or if there's a chance the parent might decide to delete its children.
  22868. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  22869. the component will start by accelerating from rest; higher values mean that it
  22870. will have an initial speed greater than zero. If the value if greater than 1, it
  22871. will decelerate towards the middle of its journey. To move the component at a
  22872. constant rate for its entire animation, set both the start and end speeds to 1.0
  22873. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  22874. If this is 0, the component will decelerate to a standstill at its final position;
  22875. higher values mean the component will still be moving when it stops. To move the component
  22876. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  22877. */
  22878. void animateComponent (Component* component,
  22879. const Rectangle<int>& finalBounds,
  22880. float finalAlpha,
  22881. int animationDurationMilliseconds,
  22882. bool useProxyComponent,
  22883. double startSpeed,
  22884. double endSpeed);
  22885. /** Begins a fade-out of this components alpha level.
  22886. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  22887. a proxy. You're safe to delete the component after calling this method, and this won't
  22888. interfere with the animation's progress.
  22889. */
  22890. void fadeOut (Component* component, int millisecondsToTake);
  22891. /** Begins a fade-in of a component.
  22892. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  22893. */
  22894. void fadeIn (Component* component, int millisecondsToTake);
  22895. /** Stops a component if it's currently being animated.
  22896. If moveComponentToItsFinalPosition is true, then the component will
  22897. be immediately moved to its destination position and size. If false, it will be
  22898. left in whatever location it currently occupies.
  22899. */
  22900. void cancelAnimation (Component* component,
  22901. bool moveComponentToItsFinalPosition);
  22902. /** Clears all of the active animations.
  22903. If moveComponentsToTheirFinalPositions is true, all the components will
  22904. be immediately set to their final positions. If false, they will be
  22905. left in whatever locations they currently occupy.
  22906. */
  22907. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  22908. /** Returns the destination position for a component.
  22909. If the component is being animated, this will return the target position that
  22910. was specified when animateComponent() was called.
  22911. If the specified component isn't currently being animated, this method will just
  22912. return its current position.
  22913. */
  22914. const Rectangle<int> getComponentDestination (Component* component);
  22915. /** Returns true if the specified component is currently being animated. */
  22916. bool isAnimating (Component* component) const;
  22917. private:
  22918. class AnimationTask;
  22919. OwnedArray <AnimationTask> tasks;
  22920. uint32 lastTime;
  22921. AnimationTask* findTaskFor (Component* component) const;
  22922. void timerCallback();
  22923. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  22924. };
  22925. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  22926. /*** End of inlined file: juce_ComponentAnimator.h ***/
  22927. class MouseInputSource;
  22928. class MouseInputSourceInternal;
  22929. class MouseListener;
  22930. /**
  22931. Classes can implement this interface and register themselves with the Desktop class
  22932. to receive callbacks when the currently focused component changes.
  22933. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  22934. */
  22935. class JUCE_API FocusChangeListener
  22936. {
  22937. public:
  22938. /** Destructor. */
  22939. virtual ~FocusChangeListener() {}
  22940. /** Callback to indicate that the currently focused component has changed. */
  22941. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  22942. };
  22943. /**
  22944. Describes and controls aspects of the computer's desktop.
  22945. */
  22946. class JUCE_API Desktop : private DeletedAtShutdown,
  22947. private Timer,
  22948. private AsyncUpdater
  22949. {
  22950. public:
  22951. /** There's only one dektop object, and this method will return it.
  22952. */
  22953. static Desktop& JUCE_CALLTYPE getInstance();
  22954. /** Returns a list of the positions of all the monitors available.
  22955. The first rectangle in the list will be the main monitor area.
  22956. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  22957. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  22958. */
  22959. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  22960. /** Returns the position and size of the main monitor.
  22961. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  22962. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  22963. */
  22964. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  22965. /** Returns the position and size of the monitor which contains this co-ordinate.
  22966. If none of the monitors contains the point, this will just return the
  22967. main monitor.
  22968. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  22969. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  22970. */
  22971. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  22972. /** Returns the mouse position.
  22973. The co-ordinates are relative to the top-left of the main monitor.
  22974. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  22975. you should only resort to grabbing the global mouse position if there's really no
  22976. way to get the coordinates via a mouse event callback instead.
  22977. */
  22978. static const Point<int> getMousePosition();
  22979. /** Makes the mouse pointer jump to a given location.
  22980. The co-ordinates are relative to the top-left of the main monitor.
  22981. */
  22982. static void setMousePosition (const Point<int>& newPosition);
  22983. /** Returns the last position at which a mouse button was pressed.
  22984. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  22985. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  22986. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  22987. if possible, and only ever call this as a last resort.
  22988. */
  22989. static const Point<int> getLastMouseDownPosition();
  22990. /** Returns the number of times the mouse button has been clicked since the
  22991. app started.
  22992. Each mouse-down event increments this number by 1.
  22993. */
  22994. static int getMouseButtonClickCounter();
  22995. /** This lets you prevent the screensaver from becoming active.
  22996. Handy if you're running some sort of presentation app where having a screensaver
  22997. appear would be annoying.
  22998. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  22999. won't enable a screensaver unless the user has actually set one up).
  23000. The disablement will only happen while the Juce application is the foreground
  23001. process - if another task is running in front of it, then the screensaver will
  23002. be unaffected.
  23003. @see isScreenSaverEnabled
  23004. */
  23005. static void setScreenSaverEnabled (bool isEnabled);
  23006. /** Returns true if the screensaver has not been turned off.
  23007. This will return the last value passed into setScreenSaverEnabled(). Note that
  23008. it won't tell you whether the user is actually using a screen saver, just
  23009. whether this app is deliberately preventing one from running.
  23010. @see setScreenSaverEnabled
  23011. */
  23012. static bool isScreenSaverEnabled();
  23013. /** Registers a MouseListener that will receive all mouse events that occur on
  23014. any component.
  23015. @see removeGlobalMouseListener
  23016. */
  23017. void addGlobalMouseListener (MouseListener* listener);
  23018. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  23019. method.
  23020. @see addGlobalMouseListener
  23021. */
  23022. void removeGlobalMouseListener (MouseListener* listener);
  23023. /** Registers a MouseListener that will receive a callback whenever the focused
  23024. component changes.
  23025. */
  23026. void addFocusChangeListener (FocusChangeListener* listener);
  23027. /** Unregisters a listener that was added with addFocusChangeListener(). */
  23028. void removeFocusChangeListener (FocusChangeListener* listener);
  23029. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  23030. The component must already be on the desktop for this method to work. It will
  23031. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  23032. etc will be hidden.
  23033. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  23034. the component that's currently being used will be resized back to the size
  23035. and position it was in before being put into this mode.
  23036. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  23037. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  23038. to hide as much on-screen paraphenalia as possible.
  23039. */
  23040. void setKioskModeComponent (Component* componentToUse,
  23041. bool allowMenusAndBars = true);
  23042. /** Returns the component that is currently being used in kiosk-mode.
  23043. This is the component that was last set by setKioskModeComponent(). If none
  23044. has been set, this returns 0.
  23045. */
  23046. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  23047. /** Returns the number of components that are currently active as top-level
  23048. desktop windows.
  23049. @see getComponent, Component::addToDesktop
  23050. */
  23051. int getNumComponents() const throw();
  23052. /** Returns one of the top-level desktop window components.
  23053. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  23054. index is out-of-range.
  23055. @see getNumComponents, Component::addToDesktop
  23056. */
  23057. Component* getComponent (int index) const throw();
  23058. /** Finds the component at a given screen location.
  23059. This will drill down into top-level windows to find the child component at
  23060. the given position.
  23061. Returns 0 if the co-ordinates are inside a non-Juce window.
  23062. */
  23063. Component* findComponentAt (const Point<int>& screenPosition) const;
  23064. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  23065. your animations.
  23066. Having a single shared ComponentAnimator object makes it more efficient when multiple
  23067. components are being moved around simultaneously. It's also more convenient than having
  23068. to manage your own instance of one.
  23069. @see ComponentAnimator
  23070. */
  23071. ComponentAnimator& getAnimator() throw() { return animator; }
  23072. /** Returns the number of MouseInputSource objects the system has at its disposal.
  23073. In a traditional single-mouse system, there might be only one object. On a multi-touch
  23074. system, there could be one input source per potential finger.
  23075. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  23076. @see getMouseSource
  23077. */
  23078. int getNumMouseSources() const throw() { return mouseSources.size(); }
  23079. /** Returns one of the system's MouseInputSource objects.
  23080. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  23081. a null pointer.
  23082. In a traditional single-mouse system, there might be only one object. On a multi-touch
  23083. system, there could be one input source per potential finger.
  23084. */
  23085. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  23086. /** Returns the main mouse input device that the system is using.
  23087. @see getNumMouseSources()
  23088. */
  23089. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  23090. /** Returns the number of mouse-sources that are currently being dragged.
  23091. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  23092. juce component has the button down on it. In a multi-touch system, this could
  23093. be any number from 0 to the number of simultaneous touches that can be detected.
  23094. */
  23095. int getNumDraggingMouseSources() const throw();
  23096. /** Returns one of the mouse sources that's currently being dragged.
  23097. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  23098. out of range, or if no mice or fingers are down, this will return a null pointer.
  23099. */
  23100. MouseInputSource* getDraggingMouseSource (int index) const throw();
  23101. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  23102. current mouse-drag operation.
  23103. This allows you to make sure that mouseDrag() events are sent continuously, even
  23104. when the mouse isn't moving. This can be useful for things like auto-scrolling
  23105. components when the mouse is near an edge.
  23106. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  23107. minimum interval between consecutive mouse drag callbacks. The callbacks
  23108. will continue until the mouse is released, and then the interval will be reset,
  23109. so you need to make sure it's called every time you begin a drag event.
  23110. Passing an interval of 0 or less will cancel the auto-repeat.
  23111. @see mouseDrag
  23112. */
  23113. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  23114. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  23115. enum DisplayOrientation
  23116. {
  23117. upright = 1, /**< Indicates that the display is the normal way up. */
  23118. upsideDown = 2, /**< Indicates that the display is upside-down. */
  23119. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  23120. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  23121. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  23122. };
  23123. /** In a tablet device which can be turned around, this returns the current orientation. */
  23124. DisplayOrientation getCurrentOrientation() const;
  23125. /** Sets which orientations the display is allowed to auto-rotate to.
  23126. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  23127. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  23128. set bit.
  23129. */
  23130. void setOrientationsEnabled (int allowedOrientations);
  23131. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  23132. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  23133. */
  23134. bool isOrientationEnabled (DisplayOrientation orientation) const throw();
  23135. /** Tells this object to refresh its idea of what the screen resolution is.
  23136. (Called internally by the native code).
  23137. */
  23138. void refreshMonitorSizes();
  23139. /** True if the OS supports semitransparent windows */
  23140. static bool canUseSemiTransparentWindows() throw();
  23141. private:
  23142. static Desktop* instance;
  23143. friend class Component;
  23144. friend class ComponentPeer;
  23145. friend class MouseInputSource;
  23146. friend class MouseInputSourceInternal;
  23147. friend class DeletedAtShutdown;
  23148. friend class TopLevelWindowManager;
  23149. OwnedArray <MouseInputSource> mouseSources;
  23150. void createMouseInputSources();
  23151. ListenerList <MouseListener> mouseListeners;
  23152. ListenerList <FocusChangeListener> focusListeners;
  23153. Array <Component*> desktopComponents;
  23154. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  23155. Point<int> lastFakeMouseMove;
  23156. void sendMouseMove();
  23157. int mouseClickCounter;
  23158. void incrementMouseClickCounter() throw();
  23159. ScopedPointer<Timer> dragRepeater;
  23160. Component* kioskModeComponent;
  23161. Rectangle<int> kioskComponentOriginalBounds;
  23162. int allowedOrientations;
  23163. ComponentAnimator animator;
  23164. void timerCallback();
  23165. void resetTimer();
  23166. int getNumDisplayMonitors() const throw();
  23167. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  23168. void addDesktopComponent (Component* c);
  23169. void removeDesktopComponent (Component* c);
  23170. void componentBroughtToFront (Component* c);
  23171. void triggerFocusCallback();
  23172. void handleAsyncUpdate();
  23173. Desktop();
  23174. ~Desktop();
  23175. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  23176. };
  23177. #endif // __JUCE_DESKTOP_JUCEHEADER__
  23178. /*** End of inlined file: juce_Desktop.h ***/
  23179. class KeyPressMappingSet;
  23180. class ApplicationCommandManagerListener;
  23181. /**
  23182. One of these objects holds a list of all the commands your app can perform,
  23183. and despatches these commands when needed.
  23184. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  23185. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  23186. to invoke automatically, which means you don't have to handle the result of a menu
  23187. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  23188. which can choose which events they want to handle.
  23189. This architecture also allows for nested ApplicationCommandTargets, so that for example
  23190. you could have two different objects, one inside the other, both of which can respond to
  23191. a "delete" command. Depending on which one has focus, the command will be sent to the
  23192. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  23193. method.
  23194. To set up your app to use commands, you'll need to do the following:
  23195. - Create a global ApplicationCommandManager to hold the list of all possible
  23196. commands. (This will also manage a set of key-mappings for them).
  23197. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  23198. This allows the object to provide a list of commands that it can perform, and
  23199. to handle them.
  23200. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  23201. or ApplicationCommandManager::registerCommand().
  23202. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  23203. method to access the key-mapper object, which you will need to register as a key-listener
  23204. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  23205. about setting this up.
  23206. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  23207. cause these commands to be invoked automatically.
  23208. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  23209. When a command is invoked, the ApplicationCommandManager will try to choose the best
  23210. ApplicationCommandTarget to receive the specified command. To do this it will use the
  23211. current keyboard focus to see which component might be interested, and will search the
  23212. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  23213. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  23214. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  23215. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  23216. point if the command still hasn't been performed, it will be passed to the current
  23217. JUCEApplication object (which is itself an ApplicationCommandTarget).
  23218. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  23219. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  23220. the object yourself.
  23221. @see ApplicationCommandTarget, ApplicationCommandInfo
  23222. */
  23223. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  23224. private FocusChangeListener
  23225. {
  23226. public:
  23227. /** Creates an ApplicationCommandManager.
  23228. Once created, you'll need to register all your app's commands with it, using
  23229. ApplicationCommandManager::registerAllCommandsForTarget() or
  23230. ApplicationCommandManager::registerCommand().
  23231. */
  23232. ApplicationCommandManager();
  23233. /** Destructor.
  23234. Make sure that you don't delete this if pointers to it are still being used by
  23235. objects such as PopupMenus or Buttons.
  23236. */
  23237. virtual ~ApplicationCommandManager();
  23238. /** Clears the current list of all commands.
  23239. Note that this will also clear the contents of the KeyPressMappingSet.
  23240. */
  23241. void clearCommands();
  23242. /** Adds a command to the list of registered commands.
  23243. @see registerAllCommandsForTarget
  23244. */
  23245. void registerCommand (const ApplicationCommandInfo& newCommand);
  23246. /** Adds all the commands that this target publishes to the manager's list.
  23247. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  23248. to get details about all the commands that this target can do, and will call
  23249. registerCommand() to add each one to the manger's list.
  23250. @see registerCommand
  23251. */
  23252. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  23253. /** Removes the command with a specified ID.
  23254. Note that this will also remove any key mappings that are mapped to the command.
  23255. */
  23256. void removeCommand (CommandID commandID);
  23257. /** This should be called to tell the manager that one of its registered commands may have changed
  23258. its active status.
  23259. Because the command manager only finds out whether a command is active or inactive by querying
  23260. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  23261. allows things like buttons to update their enablement, etc.
  23262. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  23263. for any registered listeners.
  23264. */
  23265. void commandStatusChanged();
  23266. /** Returns the number of commands that have been registered.
  23267. @see registerCommand
  23268. */
  23269. int getNumCommands() const throw() { return commands.size(); }
  23270. /** Returns the details about one of the registered commands.
  23271. The index is between 0 and (getNumCommands() - 1).
  23272. */
  23273. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  23274. /** Returns the details about a given command ID.
  23275. This will search the list of registered commands for one with the given command
  23276. ID number, and return its associated info. If no matching command is found, this
  23277. will return 0.
  23278. */
  23279. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  23280. /** Returns the name field for a command.
  23281. An empty string is returned if no command with this ID has been registered.
  23282. @see getDescriptionOfCommand
  23283. */
  23284. const String getNameOfCommand (CommandID commandID) const throw();
  23285. /** Returns the description field for a command.
  23286. An empty string is returned if no command with this ID has been registered. If the
  23287. command has no description, this will return its short name field instead.
  23288. @see getNameOfCommand
  23289. */
  23290. const String getDescriptionOfCommand (CommandID commandID) const throw();
  23291. /** Returns the list of categories.
  23292. This will go through all registered commands, and return a list of all the distict
  23293. categoryName values from their ApplicationCommandInfo structure.
  23294. @see getCommandsInCategory()
  23295. */
  23296. const StringArray getCommandCategories() const;
  23297. /** Returns a list of all the command UIDs in a particular category.
  23298. @see getCommandCategories()
  23299. */
  23300. const Array <CommandID> getCommandsInCategory (const String& categoryName) const;
  23301. /** Returns the manager's internal set of key mappings.
  23302. This object can be used to edit the keypresses. To actually link this object up
  23303. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  23304. class.
  23305. @see KeyPressMappingSet
  23306. */
  23307. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  23308. /** Invokes the given command directly, sending it to the default target.
  23309. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  23310. structure.
  23311. */
  23312. bool invokeDirectly (CommandID commandID, bool asynchronously);
  23313. /** Sends a command to the default target.
  23314. This will choose a target using getFirstCommandTarget(), and send the specified command
  23315. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  23316. first target can't handle the command, it will be passed on to targets further down the
  23317. chain (see ApplicationCommandTarget::invoke() for more info).
  23318. @param invocationInfo this must be correctly filled-in, describing the context for
  23319. the invocation.
  23320. @param asynchronously if false, the command will be performed before this method returns.
  23321. If true, a message will be posted so that the command will be performed
  23322. later on the message thread, and this method will return immediately.
  23323. @see ApplicationCommandTarget::invoke
  23324. */
  23325. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  23326. bool asynchronously);
  23327. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  23328. Whenever the manager needs to know which target a command should be sent to, it calls
  23329. this method to determine the first one to try.
  23330. By default, this method will return the target that was set by calling setFirstCommandTarget().
  23331. If no target is set, it will return the result of findDefaultComponentTarget().
  23332. If you need to make sure all commands go via your own custom target, then you can
  23333. either use setFirstCommandTarget() to specify a single target, or override this method
  23334. if you need more complex logic to choose one.
  23335. It may return 0 if no targets are available.
  23336. @see getTargetForCommand, invoke, invokeDirectly
  23337. */
  23338. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  23339. /** Sets a target to be returned by getFirstCommandTarget().
  23340. If this is set to 0, then getFirstCommandTarget() will by default return the
  23341. result of findDefaultComponentTarget().
  23342. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  23343. deleting the target object.
  23344. */
  23345. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  23346. /** Tries to find the best target to use to perform a given command.
  23347. This will call getFirstCommandTarget() to find the preferred target, and will
  23348. check whether that target can handle the given command. If it can't, then it'll use
  23349. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  23350. so on until no more are available.
  23351. If no targets are found that can perform the command, this method will return 0.
  23352. If a target is found, then it will get the target to fill-in the upToDateInfo
  23353. structure with the latest info about that command, so that the caller can see
  23354. whether the command is disabled, ticked, etc.
  23355. */
  23356. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  23357. ApplicationCommandInfo& upToDateInfo);
  23358. /** Registers a listener that will be called when various events occur. */
  23359. void addListener (ApplicationCommandManagerListener* listener);
  23360. /** Deregisters a previously-added listener. */
  23361. void removeListener (ApplicationCommandManagerListener* listener);
  23362. /** Looks for a suitable command target based on which Components have the keyboard focus.
  23363. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  23364. but is exposed here in case it's useful.
  23365. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  23366. windows, etc., and using the findTargetForComponent() method.
  23367. */
  23368. static ApplicationCommandTarget* findDefaultComponentTarget();
  23369. /** Examines this component and all its parents in turn, looking for the first one
  23370. which is a ApplicationCommandTarget.
  23371. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  23372. that class.
  23373. */
  23374. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  23375. private:
  23376. OwnedArray <ApplicationCommandInfo> commands;
  23377. ListenerList <ApplicationCommandManagerListener> listeners;
  23378. ScopedPointer <KeyPressMappingSet> keyMappings;
  23379. ApplicationCommandTarget* firstTarget;
  23380. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  23381. void handleAsyncUpdate();
  23382. void globalFocusChanged (Component*);
  23383. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  23384. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  23385. // version of this method.
  23386. virtual short getFirstCommandTarget() { return 0; }
  23387. #endif
  23388. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  23389. };
  23390. /**
  23391. A listener that receives callbacks from an ApplicationCommandManager when
  23392. commands are invoked or the command list is changed.
  23393. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  23394. */
  23395. class JUCE_API ApplicationCommandManagerListener
  23396. {
  23397. public:
  23398. /** Destructor. */
  23399. virtual ~ApplicationCommandManagerListener() {}
  23400. /** Called when an app command is about to be invoked. */
  23401. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  23402. /** Called when commands are registered or deregistered from the
  23403. command manager, or when commands are made active or inactive.
  23404. Note that if you're using this to watch for changes to whether a command is disabled,
  23405. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  23406. whenever the status of your command might have changed.
  23407. */
  23408. virtual void applicationCommandListChanged() = 0;
  23409. };
  23410. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  23411. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  23412. #endif
  23413. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  23414. #endif
  23415. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  23416. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  23417. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  23418. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  23419. /*** Start of inlined file: juce_PropertiesFile.h ***/
  23420. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  23421. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  23422. /** Wrapper on a file that stores a list of key/value data pairs.
  23423. Useful for storing application settings, etc. See the PropertySet class for
  23424. the interfaces that read and write values.
  23425. Not designed for very large amounts of data, as it keeps all the values in
  23426. memory and writes them out to disk lazily when they are changed.
  23427. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  23428. with it, and these will be signalled when a value changes.
  23429. @see PropertySet
  23430. */
  23431. class JUCE_API PropertiesFile : public PropertySet,
  23432. public ChangeBroadcaster,
  23433. private Timer
  23434. {
  23435. public:
  23436. enum FileFormatOptions
  23437. {
  23438. ignoreCaseOfKeyNames = 1,
  23439. storeAsBinary = 2,
  23440. storeAsCompressedBinary = 4,
  23441. storeAsXML = 8
  23442. };
  23443. /**
  23444. Creates a PropertiesFile object.
  23445. @param file the file to use
  23446. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  23447. is changed, the object will wait for this amount
  23448. of time and then save the file. If zero, the file
  23449. will be written to disk immediately on being changed
  23450. (which might be slow, as it'll re-write synchronously
  23451. each time a value-change method is called). If it is
  23452. less than zero, the file won't be saved until
  23453. save() or saveIfNeeded() are explicitly called.
  23454. @param optionFlags a combination of the flags in the FileFormatOptions
  23455. enum, which specify the type of file to save, and other
  23456. options.
  23457. @param processLock an optional InterprocessLock object that will be used to
  23458. prevent multiple threads or processes from writing to the file
  23459. at the same time. The PropertiesFile will keep a pointer to
  23460. this object but will not take ownership of it - the caller is
  23461. responsible for making sure that the lock doesn't get deleted
  23462. before the PropertiesFile has been deleted.
  23463. */
  23464. PropertiesFile (const File& file,
  23465. int millisecondsBeforeSaving,
  23466. int optionFlags,
  23467. InterProcessLock* processLock = 0);
  23468. /** Destructor.
  23469. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  23470. */
  23471. ~PropertiesFile();
  23472. /** Returns true if this file was created from a valid (or non-existent) file.
  23473. If the file failed to load correctly because it was corrupt or had insufficient
  23474. access, this will be false.
  23475. */
  23476. bool isValidFile() const throw() { return loadedOk; }
  23477. /** This will flush all the values to disk if they've changed since the last
  23478. time they were saved.
  23479. Returns false if it fails to write to the file for some reason (maybe because
  23480. it's read-only or the directory doesn't exist or something).
  23481. @see save
  23482. */
  23483. bool saveIfNeeded();
  23484. /** This will force a write-to-disk of the current values, regardless of whether
  23485. anything has changed since the last save.
  23486. Returns false if it fails to write to the file for some reason (maybe because
  23487. it's read-only or the directory doesn't exist or something).
  23488. @see saveIfNeeded
  23489. */
  23490. bool save();
  23491. /** Returns true if the properties have been altered since the last time they were saved.
  23492. The file is flagged as needing to be saved when you change a value, but you can
  23493. explicitly set this flag with setNeedsToBeSaved().
  23494. */
  23495. bool needsToBeSaved() const;
  23496. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  23497. @see needsToBeSaved
  23498. */
  23499. void setNeedsToBeSaved (bool needsToBeSaved);
  23500. /** Returns the file that's being used. */
  23501. const File getFile() const { return file; }
  23502. /** Handy utility to create a properties file in whatever the standard OS-specific
  23503. location is for these things.
  23504. This uses getDefaultAppSettingsFile() to decide what file to create, then
  23505. creates a PropertiesFile object with the specified properties. See
  23506. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  23507. what the parameters do.
  23508. @see getDefaultAppSettingsFile
  23509. */
  23510. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  23511. const String& fileNameSuffix,
  23512. const String& folderName,
  23513. bool commonToAllUsers,
  23514. int millisecondsBeforeSaving,
  23515. int propertiesFileOptions,
  23516. InterProcessLock* processLock = 0);
  23517. /** Handy utility to choose a file in the standard OS-dependent location for application
  23518. settings files.
  23519. So on a Mac, this will return a file called:
  23520. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  23521. On Windows it'll return something like:
  23522. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  23523. On Linux it'll return
  23524. ~/.[folderName]/[applicationName].[fileNameSuffix]
  23525. If you pass an empty string as the folder name, it'll use the app name for this (or
  23526. omit the folder name on the Mac).
  23527. If commonToAllUsers is true, then this will return the same file for all users of the
  23528. computer, regardless of the current user. If it is false, the file will be specific to
  23529. only the current user. Use this to choose whether you're saving settings that are common
  23530. or user-specific.
  23531. */
  23532. static const File getDefaultAppSettingsFile (const String& applicationName,
  23533. const String& fileNameSuffix,
  23534. const String& folderName,
  23535. bool commonToAllUsers);
  23536. protected:
  23537. virtual void propertyChanged();
  23538. private:
  23539. File file;
  23540. int timerInterval;
  23541. const int options;
  23542. bool loadedOk, needsWriting;
  23543. InterProcessLock* processLock;
  23544. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  23545. InterProcessLock::ScopedLockType* createProcessLock() const;
  23546. void timerCallback();
  23547. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  23548. };
  23549. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  23550. /*** End of inlined file: juce_PropertiesFile.h ***/
  23551. /**
  23552. Manages a collection of properties.
  23553. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  23554. as a singleton.
  23555. It holds two different PropertiesFile objects internally, one for user-specific
  23556. settings (stored in your user directory), and one for settings that are common to
  23557. all users (stored in a folder accessible to all users).
  23558. The class manages the creation of these files on-demand, allowing access via the
  23559. getUserSettings() and getCommonSettings() methods. It also has a few handy
  23560. methods like testWriteAccess() to check that the files can be saved.
  23561. If you're using one of these as a singleton, then your app's start-up code should
  23562. first of all call setStorageParameters() to tell it the parameters to use to create
  23563. the properties files.
  23564. @see PropertiesFile
  23565. */
  23566. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  23567. {
  23568. public:
  23569. /**
  23570. Creates an ApplicationProperties object.
  23571. Before using it, you must call setStorageParameters() to give it the info
  23572. it needs to create the property files.
  23573. */
  23574. ApplicationProperties();
  23575. /** Destructor. */
  23576. ~ApplicationProperties();
  23577. juce_DeclareSingleton (ApplicationProperties, false)
  23578. /** Gives the object the information it needs to create the appropriate properties files.
  23579. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  23580. info about how these parameters are used.
  23581. */
  23582. void setStorageParameters (const String& applicationName,
  23583. const String& fileNameSuffix,
  23584. const String& folderName,
  23585. int millisecondsBeforeSaving,
  23586. int propertiesFileOptions,
  23587. InterProcessLock* processLock = 0);
  23588. /** Tests whether the files can be successfully written to, and can show
  23589. an error message if not.
  23590. Returns true if none of the tests fail.
  23591. @param testUserSettings if true, the user settings file will be tested
  23592. @param testCommonSettings if true, the common settings file will be tested
  23593. @param showWarningDialogOnFailure if true, the method will show a helpful error
  23594. message box if either of the tests fail
  23595. */
  23596. bool testWriteAccess (bool testUserSettings,
  23597. bool testCommonSettings,
  23598. bool showWarningDialogOnFailure);
  23599. /** Returns the user settings file.
  23600. The first time this is called, it will create and load the properties file.
  23601. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  23602. the common settings are used as a second-chance place to look. This is done via the
  23603. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  23604. to the fallback for the user settings.
  23605. @see getCommonSettings
  23606. */
  23607. PropertiesFile* getUserSettings();
  23608. /** Returns the common settings file.
  23609. The first time this is called, it will create and load the properties file.
  23610. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  23611. read-only (e.g. because the user doesn't have permission to write
  23612. to shared files), then this will return the user settings instead,
  23613. (like getUserSettings() would do). This is handy if you'd like to
  23614. write a value to the common settings, but if that's no possible,
  23615. then you'd rather write to the user settings than none at all.
  23616. If returnUserPropsIfReadOnly is false, this method will always return
  23617. the common settings, even if any changes to them can't be saved.
  23618. @see getUserSettings
  23619. */
  23620. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  23621. /** Saves both files if they need to be saved.
  23622. @see PropertiesFile::saveIfNeeded
  23623. */
  23624. bool saveIfNeeded();
  23625. /** Flushes and closes both files if they are open.
  23626. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  23627. and closes both files. They will then be re-opened the next time getUserSettings()
  23628. or getCommonSettings() is called.
  23629. */
  23630. void closeFiles();
  23631. private:
  23632. ScopedPointer <PropertiesFile> userProps, commonProps;
  23633. String appName, fileSuffix, folderName;
  23634. int msBeforeSaving, options;
  23635. int commonSettingsAreReadOnly;
  23636. InterProcessLock* processLock;
  23637. void openFiles();
  23638. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  23639. };
  23640. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  23641. /*** End of inlined file: juce_ApplicationProperties.h ***/
  23642. #endif
  23643. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  23644. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  23645. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  23646. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  23647. /*** Start of inlined file: juce_AudioFormat.h ***/
  23648. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  23649. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  23650. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  23651. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23652. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23653. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  23654. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  23655. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  23656. /**
  23657. This class a container which holds all the classes pertaining to the AudioData::Pointer
  23658. audio sample format class.
  23659. @see AudioData::Pointer.
  23660. */
  23661. class JUCE_API AudioData
  23662. {
  23663. public:
  23664. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  23665. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  23666. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  23667. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  23668. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  23669. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  23670. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  23671. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  23672. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  23673. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  23674. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  23675. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  23676. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  23677. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  23678. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  23679. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  23680. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  23681. #ifndef DOXYGEN
  23682. class BigEndian
  23683. {
  23684. public:
  23685. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatBE(); }
  23686. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatBE (newValue); }
  23687. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32BE(); }
  23688. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32BE (newValue); }
  23689. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromBE (source); }
  23690. enum { isBigEndian = 1 };
  23691. };
  23692. class LittleEndian
  23693. {
  23694. public:
  23695. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatLE(); }
  23696. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatLE (newValue); }
  23697. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32LE(); }
  23698. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32LE (newValue); }
  23699. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromLE (source); }
  23700. enum { isBigEndian = 0 };
  23701. };
  23702. #if JUCE_BIG_ENDIAN
  23703. class NativeEndian : public BigEndian {};
  23704. #else
  23705. class NativeEndian : public LittleEndian {};
  23706. #endif
  23707. class Int8
  23708. {
  23709. public:
  23710. inline Int8 (void* data_) throw() : data (static_cast <int8*> (data_)) {}
  23711. inline void advance() throw() { ++data; }
  23712. inline void skip (int numSamples) throw() { data += numSamples; }
  23713. inline float getAsFloatLE() const throw() { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  23714. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  23715. inline void setAsFloatLE (float newValue) throw() { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  23716. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  23717. inline int32 getAsInt32LE() const throw() { return (int) (*data << 24); }
  23718. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  23719. inline void setAsInt32LE (int newValue) throw() { *data = (int8) (newValue >> 24); }
  23720. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  23721. inline void clear() throw() { *data = 0; }
  23722. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  23723. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  23724. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  23725. inline void copyFromSameType (Int8& source) throw() { *data = *source.data; }
  23726. int8* data;
  23727. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  23728. };
  23729. class UInt8
  23730. {
  23731. public:
  23732. inline UInt8 (void* data_) throw() : data (static_cast <uint8*> (data_)) {}
  23733. inline void advance() throw() { ++data; }
  23734. inline void skip (int numSamples) throw() { data += numSamples; }
  23735. inline float getAsFloatLE() const throw() { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  23736. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  23737. inline void setAsFloatLE (float newValue) throw() { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  23738. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  23739. inline int32 getAsInt32LE() const throw() { return (int) ((*data - 128) << 24); }
  23740. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  23741. inline void setAsInt32LE (int newValue) throw() { *data = (uint8) (128 + (newValue >> 24)); }
  23742. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  23743. inline void clear() throw() { *data = 128; }
  23744. inline void clearMultiple (int num) throw() { memset (data, 128, num) ;}
  23745. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  23746. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  23747. inline void copyFromSameType (UInt8& source) throw() { *data = *source.data; }
  23748. uint8* data;
  23749. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  23750. };
  23751. class Int16
  23752. {
  23753. public:
  23754. inline Int16 (void* data_) throw() : data (static_cast <uint16*> (data_)) {}
  23755. inline void advance() throw() { ++data; }
  23756. inline void skip (int numSamples) throw() { data += numSamples; }
  23757. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  23758. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  23759. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int16) -maxValue, (int16) maxValue, (int16) roundToInt (newValue * (1.0 + maxValue)))); }
  23760. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int16) -maxValue, (int16) maxValue, (int16) roundToInt (newValue * (1.0 + maxValue)))); }
  23761. inline int32 getAsInt32LE() const throw() { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  23762. inline int32 getAsInt32BE() const throw() { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  23763. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  23764. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  23765. inline void clear() throw() { *data = 0; }
  23766. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  23767. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  23768. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  23769. inline void copyFromSameType (Int16& source) throw() { *data = *source.data; }
  23770. uint16* data;
  23771. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  23772. };
  23773. class Int24
  23774. {
  23775. public:
  23776. inline Int24 (void* data_) throw() : data (static_cast <char*> (data_)) {}
  23777. inline void advance() throw() { data += 3; }
  23778. inline void skip (int numSamples) throw() { data += 3 * numSamples; }
  23779. inline float getAsFloatLE() const throw() { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  23780. inline float getAsFloatBE() const throw() { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  23781. inline void setAsFloatLE (float newValue) throw() { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  23782. inline void setAsFloatBE (float newValue) throw() { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  23783. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  23784. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  23785. inline void setAsInt32LE (int32 newValue) throw() { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  23786. inline void setAsInt32BE (int32 newValue) throw() { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  23787. inline void clear() throw() { data[0] = 0; data[1] = 0; data[2] = 0; }
  23788. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  23789. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  23790. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  23791. inline void copyFromSameType (Int24& source) throw() { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  23792. char* data;
  23793. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  23794. };
  23795. class Int32
  23796. {
  23797. public:
  23798. inline Int32 (void* data_) throw() : data (static_cast <uint32*> (data_)) {}
  23799. inline void advance() throw() { ++data; }
  23800. inline void skip (int numSamples) throw() { data += numSamples; }
  23801. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  23802. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  23803. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  23804. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  23805. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::swapIfBigEndian (*data); }
  23806. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  23807. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  23808. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  23809. inline void clear() throw() { *data = 0; }
  23810. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  23811. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  23812. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  23813. inline void copyFromSameType (Int32& source) throw() { *data = *source.data; }
  23814. uint32* data;
  23815. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  23816. };
  23817. class Float32
  23818. {
  23819. public:
  23820. inline Float32 (void* data_) throw() : data (static_cast <float*> (data_)) {}
  23821. inline void advance() throw() { ++data; }
  23822. inline void skip (int numSamples) throw() { data += numSamples; }
  23823. #if JUCE_BIG_ENDIAN
  23824. inline float getAsFloatBE() const throw() { return *data; }
  23825. inline void setAsFloatBE (float newValue) throw() { *data = newValue; }
  23826. inline float getAsFloatLE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  23827. inline void setAsFloatLE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  23828. #else
  23829. inline float getAsFloatLE() const throw() { return *data; }
  23830. inline void setAsFloatLE (float newValue) throw() { *data = newValue; }
  23831. inline float getAsFloatBE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  23832. inline void setAsFloatBE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  23833. #endif
  23834. inline int32 getAsInt32LE() const throw() { return (int32) roundToInt (jlimit (-1.0f, 1.0f, getAsFloatLE()) * (1.0 + maxValue)); }
  23835. inline int32 getAsInt32BE() const throw() { return (int32) roundToInt (jlimit (-1.0f, 1.0f, getAsFloatBE()) * (1.0 + maxValue)); }
  23836. inline void setAsInt32LE (int32 newValue) throw() { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  23837. inline void setAsInt32BE (int32 newValue) throw() { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  23838. inline void clear() throw() { *data = 0; }
  23839. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  23840. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsFloatLE (source.getAsFloat()); }
  23841. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsFloatBE (source.getAsFloat()); }
  23842. inline void copyFromSameType (Float32& source) throw() { *data = *source.data; }
  23843. float* data;
  23844. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  23845. };
  23846. class NonInterleaved
  23847. {
  23848. public:
  23849. inline NonInterleaved() throw() {}
  23850. inline NonInterleaved (const NonInterleaved&) throw() {}
  23851. inline NonInterleaved (const int) throw() {}
  23852. inline void copyFrom (const NonInterleaved&) throw() {}
  23853. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.advance(); }
  23854. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numSamples); }
  23855. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { s.clearMultiple (numSamples); }
  23856. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) throw() { return SampleFormatType::bytesPerSample; }
  23857. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  23858. };
  23859. class Interleaved
  23860. {
  23861. public:
  23862. inline Interleaved() throw() : numInterleavedChannels (1) {}
  23863. inline Interleaved (const Interleaved& other) throw() : numInterleavedChannels (other.numInterleavedChannels) {}
  23864. inline Interleaved (const int numInterleavedChannels_) throw() : numInterleavedChannels (numInterleavedChannels_) {}
  23865. inline void copyFrom (const Interleaved& other) throw() { numInterleavedChannels = other.numInterleavedChannels; }
  23866. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.skip (numInterleavedChannels); }
  23867. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numInterleavedChannels * numSamples); }
  23868. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  23869. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const throw() { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  23870. int numInterleavedChannels;
  23871. enum { isInterleavedType = 1 };
  23872. };
  23873. class NonConst
  23874. {
  23875. public:
  23876. typedef void VoidType;
  23877. static inline void* toVoidPtr (VoidType* v) throw() { return v; }
  23878. enum { isConst = 0 };
  23879. };
  23880. class Const
  23881. {
  23882. public:
  23883. typedef const void VoidType;
  23884. static inline void* toVoidPtr (VoidType* v) throw() { return const_cast<void*> (v); }
  23885. enum { isConst = 1 };
  23886. };
  23887. #endif
  23888. /**
  23889. A pointer to a block of audio data with a particular encoding.
  23890. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  23891. the audio format as a series of template parameters, e.g.
  23892. @code
  23893. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  23894. AudioData::Pointer <AudioData::Int16,
  23895. AudioData::LittleEndian,
  23896. AudioData::NonInterleaved,
  23897. AudioData::Const> pointer (someRawAudioData);
  23898. // These methods read the sample that is being pointed to
  23899. float firstSampleAsFloat = pointer.getAsFloat();
  23900. int32 firstSampleAsInt = pointer.getAsInt32();
  23901. ++pointer; // moves the pointer to the next sample.
  23902. pointer += 3; // skips the next 3 samples.
  23903. @endcode
  23904. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  23905. converting its format.
  23906. @see AudioData::Converter
  23907. */
  23908. template <typename SampleFormat,
  23909. typename Endianness,
  23910. typename InterleavingType,
  23911. typename Constness>
  23912. class Pointer
  23913. {
  23914. public:
  23915. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  23916. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  23917. for interleaved formats, use the constructor that also takes a number of channels.
  23918. */
  23919. Pointer (typename Constness::VoidType* sourceData) throw()
  23920. : data (Constness::toVoidPtr (sourceData))
  23921. {
  23922. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  23923. // you should pass NonInterleaved as the template parameter for the interleaving type!
  23924. static_jassert (InterleavingType::isInterleavedType == 0);
  23925. }
  23926. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  23927. For non-interleaved data, use the other constructor.
  23928. */
  23929. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) throw()
  23930. : data (Constness::toVoidPtr (sourceData)),
  23931. interleaving (numInterleavedChannels)
  23932. {
  23933. }
  23934. /** Creates a copy of another pointer. */
  23935. Pointer (const Pointer& other) throw()
  23936. : data (other.data),
  23937. interleaving (other.interleaving)
  23938. {
  23939. }
  23940. Pointer& operator= (const Pointer& other) throw()
  23941. {
  23942. data = other.data;
  23943. interleaving.copyFrom (other.interleaving);
  23944. return *this;
  23945. }
  23946. /** Returns the value of the first sample as a floating point value.
  23947. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  23948. formats, the value could be outside that range, although -1 to 1 is the standard range.
  23949. */
  23950. inline float getAsFloat() const throw() { return Endianness::getAsFloat (data); }
  23951. /** Sets the value of the first sample as a floating point value.
  23952. (This method can only be used if the AudioData::NonConst option was used).
  23953. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  23954. range will be clipped. For floating point formats, any value passed in here will be
  23955. written directly, although -1 to 1 is the standard range.
  23956. */
  23957. inline void setAsFloat (float newValue) throw()
  23958. {
  23959. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  23960. Endianness::setAsFloat (data, newValue);
  23961. }
  23962. /** Returns the value of the first sample as a 32-bit integer.
  23963. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  23964. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  23965. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  23966. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  23967. */
  23968. inline int32 getAsInt32() const throw() { return Endianness::getAsInt32 (data); }
  23969. /** Sets the value of the first sample as a 32-bit integer.
  23970. This will be mapped to the range of the format that is being written - see getAsInt32().
  23971. */
  23972. inline void setAsInt32 (int32 newValue) throw()
  23973. {
  23974. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  23975. Endianness::setAsInt32 (data, newValue);
  23976. }
  23977. /** Moves the pointer along to the next sample. */
  23978. inline Pointer& operator++() throw() { advance(); return *this; }
  23979. /** Moves the pointer back to the previous sample. */
  23980. inline Pointer& operator--() throw() { interleaving.advanceDataBy (data, -1); return *this; }
  23981. /** Adds a number of samples to the pointer's position. */
  23982. Pointer& operator+= (int samplesToJump) throw() { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  23983. /** Writes a stream of samples into this pointer from another pointer.
  23984. This will copy the specified number of samples, converting between formats appropriately.
  23985. */
  23986. void convertSamples (Pointer source, int numSamples) const throw()
  23987. {
  23988. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  23989. Pointer dest (*this);
  23990. while (--numSamples >= 0)
  23991. {
  23992. dest.data.copyFromSameType (source.data);
  23993. dest.advance();
  23994. source.advance();
  23995. }
  23996. }
  23997. /** Writes a stream of samples into this pointer from another pointer.
  23998. This will copy the specified number of samples, converting between formats appropriately.
  23999. */
  24000. template <class OtherPointerType>
  24001. void convertSamples (OtherPointerType source, int numSamples) const throw()
  24002. {
  24003. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  24004. Pointer dest (*this);
  24005. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  24006. {
  24007. while (--numSamples >= 0)
  24008. {
  24009. Endianness::copyFrom (dest.data, source);
  24010. dest.advance();
  24011. ++source;
  24012. }
  24013. }
  24014. else // copy backwards if we're increasing the sample width..
  24015. {
  24016. dest += numSamples;
  24017. source += numSamples;
  24018. while (--numSamples >= 0)
  24019. Endianness::copyFrom ((--dest).data, --source);
  24020. }
  24021. }
  24022. /** Sets a number of samples to zero. */
  24023. void clearSamples (int numSamples) const throw()
  24024. {
  24025. Pointer dest (*this);
  24026. dest.interleaving.clear (dest.data, numSamples);
  24027. }
  24028. /** Returns true if the pointer is using a floating-point format. */
  24029. static bool isFloatingPoint() throw() { return (bool) SampleFormat::isFloat; }
  24030. /** Returns true if the format is big-endian. */
  24031. static bool isBigEndian() throw() { return (bool) Endianness::isBigEndian; }
  24032. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  24033. static int getBytesPerSample() throw() { return (int) SampleFormat::bytesPerSample; }
  24034. /** Returns the number of interleaved channels in the format. */
  24035. int getNumInterleavedChannels() const throw() { return (int) this->numInterleavedChannels; }
  24036. /** Returns the number of bytes between the start address of each sample. */
  24037. int getNumBytesBetweenSamples() const throw() { return interleaving.getNumBytesBetweenSamples (data); }
  24038. /** Returns the accuracy of this format when represented as a 32-bit integer.
  24039. This is the smallest number above 0 that can be represented in the sample format, converted to
  24040. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  24041. its resolution is 0x100.
  24042. */
  24043. static int get32BitResolution() throw() { return (int) SampleFormat::resolution; }
  24044. /** Returns a pointer to the underlying data. */
  24045. const void* getRawData() const throw() { return data.data; }
  24046. private:
  24047. SampleFormat data;
  24048. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  24049. // advantage of EBCO causes an internal compiler error in VC6..
  24050. inline void advance() throw() { interleaving.advanceData (data); }
  24051. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  24052. Pointer operator-- (int);
  24053. };
  24054. /** A base class for objects that are used to convert between two different sample formats.
  24055. The AudioData::ConverterInstance implements this base class and can be templated, so
  24056. you can create an instance that converts between two particular formats, and then
  24057. store this in the abstract base class.
  24058. @see AudioData::ConverterInstance
  24059. */
  24060. class Converter
  24061. {
  24062. public:
  24063. virtual ~Converter() {}
  24064. /** Converts a sequence of samples from the converter's source format into the dest format. */
  24065. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  24066. /** Converts a sequence of samples from the converter's source format into the dest format.
  24067. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  24068. particular sub-channel of the data to be used.
  24069. */
  24070. virtual void convertSamples (void* destSamples, int destSubChannel,
  24071. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  24072. };
  24073. /**
  24074. A class that converts between two templated AudioData::Pointer types, and which
  24075. implements the AudioData::Converter interface.
  24076. This can be used as a concrete instance of the AudioData::Converter abstract class.
  24077. @see AudioData::Converter
  24078. */
  24079. template <class SourceSampleType, class DestSampleType>
  24080. class ConverterInstance : public Converter
  24081. {
  24082. public:
  24083. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  24084. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  24085. {}
  24086. ~ConverterInstance() {}
  24087. void convertSamples (void* dest, const void* source, int numSamples) const
  24088. {
  24089. SourceSampleType s (source, sourceChannels);
  24090. DestSampleType d (dest, destChannels);
  24091. d.convertSamples (s, numSamples);
  24092. }
  24093. void convertSamples (void* dest, int destSubChannel,
  24094. const void* source, int sourceSubChannel, int numSamples) const
  24095. {
  24096. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  24097. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  24098. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  24099. d.convertSamples (s, numSamples);
  24100. }
  24101. private:
  24102. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  24103. const int sourceChannels, destChannels;
  24104. };
  24105. };
  24106. /**
  24107. A set of routines to convert buffers of 32-bit floating point data to and from
  24108. various integer formats.
  24109. Note that these functions are deprecated - the AudioData class provides a much more
  24110. flexible set of conversion classes now.
  24111. */
  24112. class JUCE_API AudioDataConverters
  24113. {
  24114. public:
  24115. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  24116. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  24117. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  24118. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  24119. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  24120. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  24121. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  24122. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  24123. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  24124. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  24125. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  24126. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  24127. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  24128. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  24129. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  24130. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  24131. enum DataFormat
  24132. {
  24133. int16LE,
  24134. int16BE,
  24135. int24LE,
  24136. int24BE,
  24137. int32LE,
  24138. int32BE,
  24139. float32LE,
  24140. float32BE,
  24141. };
  24142. static void convertFloatToFormat (DataFormat destFormat,
  24143. const float* source, void* dest, int numSamples);
  24144. static void convertFormatToFloat (DataFormat sourceFormat,
  24145. const void* source, float* dest, int numSamples);
  24146. static void interleaveSamples (const float** source, float* dest,
  24147. int numSamples, int numChannels);
  24148. static void deinterleaveSamples (const float* source, float** dest,
  24149. int numSamples, int numChannels);
  24150. private:
  24151. AudioDataConverters();
  24152. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  24153. };
  24154. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  24155. /*** End of inlined file: juce_AudioDataConverters.h ***/
  24156. class AudioFormat;
  24157. /**
  24158. Reads samples from an audio file stream.
  24159. A subclass that reads a specific type of audio format will be created by
  24160. an AudioFormat object.
  24161. @see AudioFormat, AudioFormatWriter
  24162. */
  24163. class JUCE_API AudioFormatReader
  24164. {
  24165. protected:
  24166. /** Creates an AudioFormatReader object.
  24167. @param sourceStream the stream to read from - this will be deleted
  24168. by this object when it is no longer needed. (Some
  24169. specialised readers might not use this parameter and
  24170. can leave it as 0).
  24171. @param formatName the description that will be returned by the getFormatName()
  24172. method
  24173. */
  24174. AudioFormatReader (InputStream* sourceStream,
  24175. const String& formatName);
  24176. public:
  24177. /** Destructor. */
  24178. virtual ~AudioFormatReader();
  24179. /** Returns a description of what type of format this is.
  24180. E.g. "AIFF"
  24181. */
  24182. const String getFormatName() const throw() { return formatName; }
  24183. /** Reads samples from the stream.
  24184. @param destSamples an array of buffers into which the sample data for each
  24185. channel will be written.
  24186. If the format is fixed-point, each channel will be written
  24187. as an array of 32-bit signed integers using the full
  24188. range -0x80000000 to 0x7fffffff, regardless of the source's
  24189. bit-depth. If it is a floating-point format, you should cast
  24190. the resulting array to a (float**) to get the values (in the
  24191. range -1.0 to 1.0 or beyond)
  24192. If the format is stereo, then destSamples[0] is the left channel
  24193. data, and destSamples[1] is the right channel.
  24194. The numDestChannels parameter indicates how many pointers this array
  24195. contains, but some of these pointers can be null if you don't want to
  24196. read data for some of the channels
  24197. @param numDestChannels the number of array elements in the destChannels array
  24198. @param startSampleInSource the position in the audio file or stream at which the samples
  24199. should be read, as a number of samples from the start of the
  24200. stream. It's ok for this to be beyond the start or end of the
  24201. available data - any samples that are out-of-range will be returned
  24202. as zeros.
  24203. @param numSamplesToRead the number of samples to read. If this is greater than the number
  24204. of samples that the file or stream contains. the result will be padded
  24205. with zeros
  24206. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  24207. for some of the channels that you pass in, then they should be filled with
  24208. copies of valid source channels.
  24209. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  24210. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  24211. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  24212. was false, then only the first channel would be filled with the file's contents, and
  24213. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  24214. from a stereo file, then the last 3 would all end up with copies of the same data.
  24215. @returns true if the operation succeeded, false if there was an error. Note
  24216. that reading sections of data beyond the extent of the stream isn't an
  24217. error - the reader should just return zeros for these regions
  24218. @see readMaxLevels
  24219. */
  24220. bool read (int* const* destSamples,
  24221. int numDestChannels,
  24222. int64 startSampleInSource,
  24223. int numSamplesToRead,
  24224. bool fillLeftoverChannelsWithCopies);
  24225. /** Finds the highest and lowest sample levels from a section of the audio stream.
  24226. This will read a block of samples from the stream, and measure the
  24227. highest and lowest sample levels from the channels in that section, returning
  24228. these as normalised floating-point levels.
  24229. @param startSample the offset into the audio stream to start reading from. It's
  24230. ok for this to be beyond the start or end of the stream.
  24231. @param numSamples how many samples to read
  24232. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  24233. @param highestLeft on return, this is the highest absolute sample from the left channel
  24234. @param lowestRight on return, this is the lowest absolute sample from the right
  24235. channel (if there is one)
  24236. @param highestRight on return, this is the highest absolute sample from the right
  24237. channel (if there is one)
  24238. @see read
  24239. */
  24240. virtual void readMaxLevels (int64 startSample,
  24241. int64 numSamples,
  24242. float& lowestLeft,
  24243. float& highestLeft,
  24244. float& lowestRight,
  24245. float& highestRight);
  24246. /** Scans the source looking for a sample whose magnitude is in a specified range.
  24247. This will read from the source, either forwards or backwards between two sample
  24248. positions, until it finds a sample whose magnitude lies between two specified levels.
  24249. If it finds a suitable sample, it returns its position; if not, it will return -1.
  24250. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  24251. points when you're searching for a continuous range of samples
  24252. @param startSample the first sample to look at
  24253. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  24254. the search will go backwards
  24255. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  24256. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  24257. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  24258. of this many consecutive samples, all of which lie
  24259. within the target range. When it finds such a sequence,
  24260. it returns the position of the first in-range sample
  24261. it found (i.e. the earliest one if scanning forwards, the
  24262. latest one if scanning backwards)
  24263. */
  24264. int64 searchForLevel (int64 startSample,
  24265. int64 numSamplesToSearch,
  24266. double magnitudeRangeMinimum,
  24267. double magnitudeRangeMaximum,
  24268. int minimumConsecutiveSamples);
  24269. /** The sample-rate of the stream. */
  24270. double sampleRate;
  24271. /** The number of bits per sample, e.g. 16, 24, 32. */
  24272. unsigned int bitsPerSample;
  24273. /** The total number of samples in the audio stream. */
  24274. int64 lengthInSamples;
  24275. /** The total number of channels in the audio stream. */
  24276. unsigned int numChannels;
  24277. /** Indicates whether the data is floating-point or fixed. */
  24278. bool usesFloatingPointData;
  24279. /** A set of metadata values that the reader has pulled out of the stream.
  24280. Exactly what these values are depends on the format, so you can
  24281. check out the format implementation code to see what kind of stuff
  24282. they understand.
  24283. */
  24284. StringPairArray metadataValues;
  24285. /** The input stream, for use by subclasses. */
  24286. InputStream* input;
  24287. /** Subclasses must implement this method to perform the low-level read operation.
  24288. Callers should use read() instead of calling this directly.
  24289. @param destSamples the array of destination buffers to fill. Some of these
  24290. pointers may be null
  24291. @param numDestChannels the number of items in the destSamples array. This
  24292. value is guaranteed not to be greater than the number of
  24293. channels that this reader object contains
  24294. @param startOffsetInDestBuffer the number of samples from the start of the
  24295. dest data at which to begin writing
  24296. @param startSampleInFile the number of samples into the source data at which
  24297. to begin reading. This value is guaranteed to be >= 0.
  24298. @param numSamples the number of samples to read
  24299. */
  24300. virtual bool readSamples (int** destSamples,
  24301. int numDestChannels,
  24302. int startOffsetInDestBuffer,
  24303. int64 startSampleInFile,
  24304. int numSamples) = 0;
  24305. protected:
  24306. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  24307. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  24308. struct ReadHelper
  24309. {
  24310. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  24311. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  24312. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) throw()
  24313. {
  24314. for (int i = 0; i < numDestChannels; ++i)
  24315. {
  24316. if (destData[i] != 0)
  24317. {
  24318. DestType dest (destData[i]);
  24319. dest += destOffset;
  24320. if (i < numSourceChannels)
  24321. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  24322. else
  24323. dest.clearSamples (numSamples);
  24324. }
  24325. }
  24326. }
  24327. };
  24328. private:
  24329. String formatName;
  24330. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  24331. };
  24332. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  24333. /*** End of inlined file: juce_AudioFormatReader.h ***/
  24334. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  24335. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  24336. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  24337. /*** Start of inlined file: juce_AudioSource.h ***/
  24338. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  24339. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  24340. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  24341. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  24342. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  24343. class AudioFormatReader;
  24344. class AudioFormatWriter;
  24345. /**
  24346. A multi-channel buffer of 32-bit floating point audio samples.
  24347. */
  24348. class JUCE_API AudioSampleBuffer
  24349. {
  24350. public:
  24351. /** Creates a buffer with a specified number of channels and samples.
  24352. The contents of the buffer will initially be undefined, so use clear() to
  24353. set all the samples to zero.
  24354. The buffer will allocate its memory internally, and this will be released
  24355. when the buffer is deleted.
  24356. */
  24357. AudioSampleBuffer (int numChannels,
  24358. int numSamples) throw();
  24359. /** Creates a buffer using a pre-allocated block of memory.
  24360. Note that if the buffer is resized or its number of channels is changed, it
  24361. will re-allocate memory internally and copy the existing data to this new area,
  24362. so it will then stop directly addressing this memory.
  24363. @param dataToReferTo a pre-allocated array containing pointers to the data
  24364. for each channel that should be used by this buffer. The
  24365. buffer will only refer to this memory, it won't try to delete
  24366. it when the buffer is deleted or resized.
  24367. @param numChannels the number of channels to use - this must correspond to the
  24368. number of elements in the array passed in
  24369. @param numSamples the number of samples to use - this must correspond to the
  24370. size of the arrays passed in
  24371. */
  24372. AudioSampleBuffer (float** dataToReferTo,
  24373. int numChannels,
  24374. int numSamples) throw();
  24375. /** Copies another buffer.
  24376. This buffer will make its own copy of the other's data, unless the buffer was created
  24377. using an external data buffer, in which case boths buffers will just point to the same
  24378. shared block of data.
  24379. */
  24380. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  24381. /** Copies another buffer onto this one.
  24382. This buffer's size will be changed to that of the other buffer.
  24383. */
  24384. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  24385. /** Destructor.
  24386. This will free any memory allocated by the buffer.
  24387. */
  24388. virtual ~AudioSampleBuffer() throw();
  24389. /** Returns the number of channels of audio data that this buffer contains.
  24390. @see getSampleData
  24391. */
  24392. int getNumChannels() const throw() { return numChannels; }
  24393. /** Returns the number of samples allocated in each of the buffer's channels.
  24394. @see getSampleData
  24395. */
  24396. int getNumSamples() const throw() { return size; }
  24397. /** Returns a pointer one of the buffer's channels.
  24398. For speed, this doesn't check whether the channel number is out of range,
  24399. so be careful when using it!
  24400. */
  24401. float* getSampleData (const int channelNumber) const throw()
  24402. {
  24403. jassert (isPositiveAndBelow (channelNumber, numChannels));
  24404. return channels [channelNumber];
  24405. }
  24406. /** Returns a pointer to a sample in one of the buffer's channels.
  24407. For speed, this doesn't check whether the channel and sample number
  24408. are out-of-range, so be careful when using it!
  24409. */
  24410. float* getSampleData (const int channelNumber,
  24411. const int sampleOffset) const throw()
  24412. {
  24413. jassert (isPositiveAndBelow (channelNumber, numChannels));
  24414. jassert (isPositiveAndBelow (sampleOffset, size));
  24415. return channels [channelNumber] + sampleOffset;
  24416. }
  24417. /** Returns an array of pointers to the channels in the buffer.
  24418. Don't modify any of the pointers that are returned, and bear in mind that
  24419. these will become invalid if the buffer is resized.
  24420. */
  24421. float** getArrayOfChannels() const throw() { return channels; }
  24422. /** Changes the buffer's size or number of channels.
  24423. This can expand or contract the buffer's length, and add or remove channels.
  24424. If keepExistingContent is true, it will try to preserve as much of the
  24425. old data as it can in the new buffer.
  24426. If clearExtraSpace is true, then any extra channels or space that is
  24427. allocated will be also be cleared. If false, then this space is left
  24428. uninitialised.
  24429. If avoidReallocating is true, then changing the buffer's size won't reduce the
  24430. amount of memory that is currently allocated (but it will still increase it if
  24431. the new size is bigger than the amount it currently has). If this is false, then
  24432. a new allocation will be done so that the buffer uses takes up the minimum amount
  24433. of memory that it needs.
  24434. */
  24435. void setSize (int newNumChannels,
  24436. int newNumSamples,
  24437. bool keepExistingContent = false,
  24438. bool clearExtraSpace = false,
  24439. bool avoidReallocating = false) throw();
  24440. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  24441. There's also a constructor that lets you specify arrays like this, but this
  24442. lets you change the channels dynamically.
  24443. Note that if the buffer is resized or its number of channels is changed, it
  24444. will re-allocate memory internally and copy the existing data to this new area,
  24445. so it will then stop directly addressing this memory.
  24446. @param dataToReferTo a pre-allocated array containing pointers to the data
  24447. for each channel that should be used by this buffer. The
  24448. buffer will only refer to this memory, it won't try to delete
  24449. it when the buffer is deleted or resized.
  24450. @param numChannels the number of channels to use - this must correspond to the
  24451. number of elements in the array passed in
  24452. @param numSamples the number of samples to use - this must correspond to the
  24453. size of the arrays passed in
  24454. */
  24455. void setDataToReferTo (float** dataToReferTo,
  24456. int numChannels,
  24457. int numSamples) throw();
  24458. /** Clears all the samples in all channels. */
  24459. void clear() throw();
  24460. /** Clears a specified region of all the channels.
  24461. For speed, this doesn't check whether the channel and sample number
  24462. are in-range, so be careful!
  24463. */
  24464. void clear (int startSample,
  24465. int numSamples) throw();
  24466. /** Clears a specified region of just one channel.
  24467. For speed, this doesn't check whether the channel and sample number
  24468. are in-range, so be careful!
  24469. */
  24470. void clear (int channel,
  24471. int startSample,
  24472. int numSamples) throw();
  24473. /** Applies a gain multiple to a region of one channel.
  24474. For speed, this doesn't check whether the channel and sample number
  24475. are in-range, so be careful!
  24476. */
  24477. void applyGain (int channel,
  24478. int startSample,
  24479. int numSamples,
  24480. float gain) throw();
  24481. /** Applies a gain multiple to a region of all the channels.
  24482. For speed, this doesn't check whether the sample numbers
  24483. are in-range, so be careful!
  24484. */
  24485. void applyGain (int startSample,
  24486. int numSamples,
  24487. float gain) throw();
  24488. /** Applies a range of gains to a region of a channel.
  24489. The gain that is applied to each sample will vary from
  24490. startGain on the first sample to endGain on the last Sample,
  24491. so it can be used to do basic fades.
  24492. For speed, this doesn't check whether the sample numbers
  24493. are in-range, so be careful!
  24494. */
  24495. void applyGainRamp (int channel,
  24496. int startSample,
  24497. int numSamples,
  24498. float startGain,
  24499. float endGain) throw();
  24500. /** Adds samples from another buffer to this one.
  24501. @param destChannel the channel within this buffer to add the samples to
  24502. @param destStartSample the start sample within this buffer's channel
  24503. @param source the source buffer to add from
  24504. @param sourceChannel the channel within the source buffer to read from
  24505. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  24506. @param numSamples the number of samples to process
  24507. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  24508. added to this buffer's samples
  24509. @see copyFrom
  24510. */
  24511. void addFrom (int destChannel,
  24512. int destStartSample,
  24513. const AudioSampleBuffer& source,
  24514. int sourceChannel,
  24515. int sourceStartSample,
  24516. int numSamples,
  24517. float gainToApplyToSource = 1.0f) throw();
  24518. /** Adds samples from an array of floats to one of the channels.
  24519. @param destChannel the channel within this buffer to add the samples to
  24520. @param destStartSample the start sample within this buffer's channel
  24521. @param source the source data to use
  24522. @param numSamples the number of samples to process
  24523. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  24524. added to this buffer's samples
  24525. @see copyFrom
  24526. */
  24527. void addFrom (int destChannel,
  24528. int destStartSample,
  24529. const float* source,
  24530. int numSamples,
  24531. float gainToApplyToSource = 1.0f) throw();
  24532. /** Adds samples from an array of floats, applying a gain ramp to them.
  24533. @param destChannel the channel within this buffer to add the samples to
  24534. @param destStartSample the start sample within this buffer's channel
  24535. @param source the source data to use
  24536. @param numSamples the number of samples to process
  24537. @param startGain the gain to apply to the first sample (this is multiplied with
  24538. the source samples before they are added to this buffer)
  24539. @param endGain the gain to apply to the final sample. The gain is linearly
  24540. interpolated between the first and last samples.
  24541. */
  24542. void addFromWithRamp (int destChannel,
  24543. int destStartSample,
  24544. const float* source,
  24545. int numSamples,
  24546. float startGain,
  24547. float endGain) throw();
  24548. /** Copies samples from another buffer to this one.
  24549. @param destChannel the channel within this buffer to copy the samples to
  24550. @param destStartSample the start sample within this buffer's channel
  24551. @param source the source buffer to read from
  24552. @param sourceChannel the channel within the source buffer to read from
  24553. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  24554. @param numSamples the number of samples to process
  24555. @see addFrom
  24556. */
  24557. void copyFrom (int destChannel,
  24558. int destStartSample,
  24559. const AudioSampleBuffer& source,
  24560. int sourceChannel,
  24561. int sourceStartSample,
  24562. int numSamples) throw();
  24563. /** Copies samples from an array of floats into one of the channels.
  24564. @param destChannel the channel within this buffer to copy the samples to
  24565. @param destStartSample the start sample within this buffer's channel
  24566. @param source the source buffer to read from
  24567. @param numSamples the number of samples to process
  24568. @see addFrom
  24569. */
  24570. void copyFrom (int destChannel,
  24571. int destStartSample,
  24572. const float* source,
  24573. int numSamples) throw();
  24574. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  24575. @param destChannel the channel within this buffer to copy the samples to
  24576. @param destStartSample the start sample within this buffer's channel
  24577. @param source the source buffer to read from
  24578. @param numSamples the number of samples to process
  24579. @param gain the gain to apply
  24580. @see addFrom
  24581. */
  24582. void copyFrom (int destChannel,
  24583. int destStartSample,
  24584. const float* source,
  24585. int numSamples,
  24586. float gain) throw();
  24587. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  24588. @param destChannel the channel within this buffer to copy the samples to
  24589. @param destStartSample the start sample within this buffer's channel
  24590. @param source the source buffer to read from
  24591. @param numSamples the number of samples to process
  24592. @param startGain the gain to apply to the first sample (this is multiplied with
  24593. the source samples before they are copied to this buffer)
  24594. @param endGain the gain to apply to the final sample. The gain is linearly
  24595. interpolated between the first and last samples.
  24596. @see addFrom
  24597. */
  24598. void copyFromWithRamp (int destChannel,
  24599. int destStartSample,
  24600. const float* source,
  24601. int numSamples,
  24602. float startGain,
  24603. float endGain) throw();
  24604. /** Finds the highest and lowest sample values in a given range.
  24605. @param channel the channel to read from
  24606. @param startSample the start sample within the channel
  24607. @param numSamples the number of samples to check
  24608. @param minVal on return, the lowest value that was found
  24609. @param maxVal on return, the highest value that was found
  24610. */
  24611. void findMinMax (int channel,
  24612. int startSample,
  24613. int numSamples,
  24614. float& minVal,
  24615. float& maxVal) const throw();
  24616. /** Finds the highest absolute sample value within a region of a channel.
  24617. */
  24618. float getMagnitude (int channel,
  24619. int startSample,
  24620. int numSamples) const throw();
  24621. /** Finds the highest absolute sample value within a region on all channels.
  24622. */
  24623. float getMagnitude (int startSample,
  24624. int numSamples) const throw();
  24625. /** Returns the root mean squared level for a region of a channel.
  24626. */
  24627. float getRMSLevel (int channel,
  24628. int startSample,
  24629. int numSamples) const throw();
  24630. /** Fills a section of the buffer using an AudioReader as its source.
  24631. This will convert the reader's fixed- or floating-point data to
  24632. the buffer's floating-point format, and will try to intelligently
  24633. cope with mismatches between the number of channels in the reader
  24634. and the buffer.
  24635. @see writeToAudioWriter
  24636. */
  24637. void readFromAudioReader (AudioFormatReader* reader,
  24638. int startSample,
  24639. int numSamples,
  24640. int readerStartSample,
  24641. bool useReaderLeftChan,
  24642. bool useReaderRightChan);
  24643. /** Writes a section of this buffer to an audio writer.
  24644. This saves you having to mess about with channels or floating/fixed
  24645. point conversion.
  24646. @see readFromAudioReader
  24647. */
  24648. void writeToAudioWriter (AudioFormatWriter* writer,
  24649. int startSample,
  24650. int numSamples) const;
  24651. private:
  24652. int numChannels, size;
  24653. size_t allocatedBytes;
  24654. float** channels;
  24655. HeapBlock <char> allocatedData;
  24656. float* preallocatedChannelSpace [32];
  24657. void allocateData();
  24658. void allocateChannels (float** dataToReferTo);
  24659. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  24660. };
  24661. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  24662. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  24663. /**
  24664. Used by AudioSource::getNextAudioBlock().
  24665. */
  24666. struct JUCE_API AudioSourceChannelInfo
  24667. {
  24668. /** The destination buffer to fill with audio data.
  24669. When the AudioSource::getNextAudioBlock() method is called, the active section
  24670. of this buffer should be filled with whatever output the source produces.
  24671. Only the samples specified by the startSample and numSamples members of this structure
  24672. should be affected by the call.
  24673. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  24674. method can be treated as the input if the source is performing some kind of filter operation,
  24675. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  24676. a handy way of doing this.
  24677. The number of channels in the buffer could be anything, so the AudioSource
  24678. must cope with this in whatever way is appropriate for its function.
  24679. */
  24680. AudioSampleBuffer* buffer;
  24681. /** The first sample in the buffer from which the callback is expected
  24682. to write data. */
  24683. int startSample;
  24684. /** The number of samples in the buffer which the callback is expected to
  24685. fill with data. */
  24686. int numSamples;
  24687. /** Convenient method to clear the buffer if the source is not producing any data. */
  24688. void clearActiveBufferRegion() const
  24689. {
  24690. if (buffer != 0)
  24691. buffer->clear (startSample, numSamples);
  24692. }
  24693. };
  24694. /**
  24695. Base class for objects that can produce a continuous stream of audio.
  24696. An AudioSource has two states: 'prepared' and 'unprepared'.
  24697. When a source needs to be played, it is first put into a 'prepared' state by a call to
  24698. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  24699. process the audio data.
  24700. Once playback has finished, the releaseResources() method is called to put the stream
  24701. back into an 'unprepared' state.
  24702. @see AudioFormatReaderSource, ResamplingAudioSource
  24703. */
  24704. class JUCE_API AudioSource
  24705. {
  24706. protected:
  24707. /** Creates an AudioSource. */
  24708. AudioSource() throw() {}
  24709. public:
  24710. /** Destructor. */
  24711. virtual ~AudioSource() {}
  24712. /** Tells the source to prepare for playing.
  24713. An AudioSource has two states: prepared and unprepared.
  24714. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  24715. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  24716. This callback allows the source to initialise any resources it might need when playing.
  24717. Once playback has finished, the releaseResources() method is called to put the stream
  24718. back into an 'unprepared' state.
  24719. Note that this method could be called more than once in succession without
  24720. a matching call to releaseResources(), so make sure your code is robust and
  24721. can handle that kind of situation.
  24722. @param samplesPerBlockExpected the number of samples that the source
  24723. will be expected to supply each time its
  24724. getNextAudioBlock() method is called. This
  24725. number may vary slightly, because it will be dependent
  24726. on audio hardware callbacks, and these aren't
  24727. guaranteed to always use a constant block size, so
  24728. the source should be able to cope with small variations.
  24729. @param sampleRate the sample rate that the output will be used at - this
  24730. is needed by sources such as tone generators.
  24731. @see releaseResources, getNextAudioBlock
  24732. */
  24733. virtual void prepareToPlay (int samplesPerBlockExpected,
  24734. double sampleRate) = 0;
  24735. /** Allows the source to release anything it no longer needs after playback has stopped.
  24736. This will be called when the source is no longer going to have its getNextAudioBlock()
  24737. method called, so it should release any spare memory, etc. that it might have
  24738. allocated during the prepareToPlay() call.
  24739. Note that there's no guarantee that prepareToPlay() will actually have been called before
  24740. releaseResources(), and it may be called more than once in succession, so make sure your
  24741. code is robust and doesn't make any assumptions about when it will be called.
  24742. @see prepareToPlay, getNextAudioBlock
  24743. */
  24744. virtual void releaseResources() = 0;
  24745. /** Called repeatedly to fetch subsequent blocks of audio data.
  24746. After calling the prepareToPlay() method, this callback will be made each
  24747. time the audio playback hardware (or whatever other destination the audio
  24748. data is going to) needs another block of data.
  24749. It will generally be called on a high-priority system thread, or possibly even
  24750. an interrupt, so be careful not to do too much work here, as that will cause
  24751. audio glitches!
  24752. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  24753. */
  24754. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  24755. };
  24756. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  24757. /*** End of inlined file: juce_AudioSource.h ***/
  24758. class AudioThumbnail;
  24759. /**
  24760. Writes samples to an audio file stream.
  24761. A subclass that writes a specific type of audio format will be created by
  24762. an AudioFormat object.
  24763. After creating one of these with the AudioFormat::createWriterFor() method
  24764. you can call its write() method to store the samples, and then delete it.
  24765. @see AudioFormat, AudioFormatReader
  24766. */
  24767. class JUCE_API AudioFormatWriter
  24768. {
  24769. protected:
  24770. /** Creates an AudioFormatWriter object.
  24771. @param destStream the stream to write to - this will be deleted
  24772. by this object when it is no longer needed
  24773. @param formatName the description that will be returned by the getFormatName()
  24774. method
  24775. @param sampleRate the sample rate to use - the base class just stores
  24776. this value, it doesn't do anything with it
  24777. @param numberOfChannels the number of channels to write - the base class just stores
  24778. this value, it doesn't do anything with it
  24779. @param bitsPerSample the bit depth of the stream - the base class just stores
  24780. this value, it doesn't do anything with it
  24781. */
  24782. AudioFormatWriter (OutputStream* destStream,
  24783. const String& formatName,
  24784. double sampleRate,
  24785. unsigned int numberOfChannels,
  24786. unsigned int bitsPerSample);
  24787. public:
  24788. /** Destructor. */
  24789. virtual ~AudioFormatWriter();
  24790. /** Returns a description of what type of format this is.
  24791. E.g. "AIFF file"
  24792. */
  24793. const String getFormatName() const throw() { return formatName; }
  24794. /** Writes a set of samples to the audio stream.
  24795. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  24796. can use AudioSampleBuffer::writeToAudioWriter().
  24797. @param samplesToWrite an array of arrays containing the sample data for
  24798. each channel to write. This is a zero-terminated
  24799. array of arrays, and can contain a different number
  24800. of channels than the actual stream uses, and the
  24801. writer should do its best to cope with this.
  24802. If the format is fixed-point, each channel will be formatted
  24803. as an array of signed integers using the full 32-bit
  24804. range -0x80000000 to 0x7fffffff, regardless of the source's
  24805. bit-depth. If it is a floating-point format, you should treat
  24806. the arrays as arrays of floats, and just cast it to an (int**)
  24807. to pass it into the method.
  24808. @param numSamples the number of samples to write
  24809. */
  24810. virtual bool write (const int** samplesToWrite,
  24811. int numSamples) = 0;
  24812. /** Reads a section of samples from an AudioFormatReader, and writes these to
  24813. the output.
  24814. This will take care of any floating-point conversion that's required to convert
  24815. between the two formats. It won't deal with sample-rate conversion, though.
  24816. If numSamplesToRead < 0, it will write the entire length of the reader.
  24817. @returns false if it can't read or write properly during the operation
  24818. */
  24819. bool writeFromAudioReader (AudioFormatReader& reader,
  24820. int64 startSample,
  24821. int64 numSamplesToRead);
  24822. /** Reads some samples from an AudioSource, and writes these to the output.
  24823. The source must already have been initialised with the AudioSource::prepareToPlay() method
  24824. @param source the source to read from
  24825. @param numSamplesToRead total number of samples to read and write
  24826. @param samplesPerBlock the maximum number of samples to fetch from the source
  24827. @returns false if it can't read or write properly during the operation
  24828. */
  24829. bool writeFromAudioSource (AudioSource& source,
  24830. int numSamplesToRead,
  24831. int samplesPerBlock = 2048);
  24832. /** Writes some samples from an AudioSampleBuffer.
  24833. */
  24834. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  24835. int startSample, int numSamples);
  24836. /** Returns the sample rate being used. */
  24837. double getSampleRate() const throw() { return sampleRate; }
  24838. /** Returns the number of channels being written. */
  24839. int getNumChannels() const throw() { return numChannels; }
  24840. /** Returns the bit-depth of the data being written. */
  24841. int getBitsPerSample() const throw() { return bitsPerSample; }
  24842. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  24843. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  24844. /**
  24845. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  24846. data into a buffer which will be flushed to disk by a background thread.
  24847. */
  24848. class ThreadedWriter
  24849. {
  24850. public:
  24851. /** Creates a ThreadedWriter for a given writer and a thread.
  24852. The writer object which is passed in here will be owned and deleted by
  24853. the ThreadedWriter when it is no longer needed.
  24854. To stop the writer and flush the buffer to disk, simply delete this object.
  24855. */
  24856. ThreadedWriter (AudioFormatWriter* writer,
  24857. TimeSliceThread& backgroundThread,
  24858. int numSamplesToBuffer);
  24859. /** Destructor. */
  24860. ~ThreadedWriter();
  24861. /** Pushes some incoming audio data into the FIFO.
  24862. If there's enough free space in the buffer, this will add the data to it,
  24863. If the FIFO is too full to accept this many samples, the method will return
  24864. false - then you could either wait until the background thread has had time to
  24865. consume some of the buffered data and try again, or you can give up
  24866. and lost this block.
  24867. The data must be an array containing the same number of channels as the
  24868. AudioFormatWriter object is using. None of these channels can be null.
  24869. */
  24870. bool write (const float** data, int numSamples);
  24871. /** Allows you to specify a thumbnail that this writer should update with the
  24872. incoming data.
  24873. The thumbnail will be cleared and will the writer will begin adding data to
  24874. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  24875. */
  24876. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  24877. /** @internal */
  24878. class Buffer; // (only public for VC6 compatibility)
  24879. private:
  24880. friend class ScopedPointer<Buffer>;
  24881. ScopedPointer<Buffer> buffer;
  24882. };
  24883. protected:
  24884. /** The sample rate of the stream. */
  24885. double sampleRate;
  24886. /** The number of channels being written to the stream. */
  24887. unsigned int numChannels;
  24888. /** The bit depth of the file. */
  24889. unsigned int bitsPerSample;
  24890. /** True if it's a floating-point format, false if it's fixed-point. */
  24891. bool usesFloatingPointData;
  24892. /** The output stream for Use by subclasses. */
  24893. OutputStream* output;
  24894. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  24895. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  24896. struct WriteHelper
  24897. {
  24898. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  24899. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  24900. static void write (void* destData, int numDestChannels, const int** source, int numSamples) throw()
  24901. {
  24902. for (int i = 0; i < numDestChannels; ++i)
  24903. {
  24904. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  24905. if (*source != 0)
  24906. {
  24907. dest.convertSamples (SourceType (*source), numSamples);
  24908. ++source;
  24909. }
  24910. else
  24911. {
  24912. dest.clearSamples (numSamples);
  24913. }
  24914. }
  24915. }
  24916. };
  24917. private:
  24918. String formatName;
  24919. friend class ThreadedWriter;
  24920. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  24921. };
  24922. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  24923. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  24924. /**
  24925. Subclasses of AudioFormat are used to read and write different audio
  24926. file formats.
  24927. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  24928. */
  24929. class JUCE_API AudioFormat
  24930. {
  24931. public:
  24932. /** Destructor. */
  24933. virtual ~AudioFormat();
  24934. /** Returns the name of this format.
  24935. e.g. "WAV file" or "AIFF file"
  24936. */
  24937. const String& getFormatName() const;
  24938. /** Returns all the file extensions that might apply to a file of this format.
  24939. The first item will be the one that's preferred when creating a new file.
  24940. So for a wav file this might just return ".wav"; for an AIFF file it might
  24941. return two items, ".aif" and ".aiff"
  24942. */
  24943. const StringArray& getFileExtensions() const;
  24944. /** Returns true if this the given file can be read by this format.
  24945. Subclasses shouldn't do too much work here, just check the extension or
  24946. file type. The base class implementation just checks the file's extension
  24947. against one of the ones that was registered in the constructor.
  24948. */
  24949. virtual bool canHandleFile (const File& fileToTest);
  24950. /** Returns a set of sample rates that the format can read and write. */
  24951. virtual const Array <int> getPossibleSampleRates() = 0;
  24952. /** Returns a set of bit depths that the format can read and write. */
  24953. virtual const Array <int> getPossibleBitDepths() = 0;
  24954. /** Returns true if the format can do 2-channel audio. */
  24955. virtual bool canDoStereo() = 0;
  24956. /** Returns true if the format can do 1-channel audio. */
  24957. virtual bool canDoMono() = 0;
  24958. /** Returns true if the format uses compressed data. */
  24959. virtual bool isCompressed();
  24960. /** Returns a list of different qualities that can be used when writing.
  24961. Non-compressed formats will just return an empty array, but for something
  24962. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  24963. When calling createWriterFor(), an index from this array is passed in to
  24964. tell the format which option is required.
  24965. */
  24966. virtual const StringArray getQualityOptions();
  24967. /** Tries to create an object that can read from a stream containing audio
  24968. data in this format.
  24969. The reader object that is returned can be used to read from the stream, and
  24970. should then be deleted by the caller.
  24971. @param sourceStream the stream to read from - the AudioFormatReader object
  24972. that is returned will delete this stream when it no longer
  24973. needs it.
  24974. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  24975. should delete the stream object that was passed-in. (If a valid
  24976. reader is returned, it will always be in charge of deleting the
  24977. stream, so this parameter is ignored)
  24978. @see AudioFormatReader
  24979. */
  24980. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  24981. bool deleteStreamIfOpeningFails) = 0;
  24982. /** Tries to create an object that can write to a stream with this audio format.
  24983. The writer object that is returned can be used to write to the stream, and
  24984. should then be deleted by the caller.
  24985. If the stream can't be created for some reason (e.g. the parameters passed in
  24986. here aren't suitable), this will return 0.
  24987. @param streamToWriteTo the stream that the data will go to - this will be
  24988. deleted by the AudioFormatWriter object when it's no longer
  24989. needed. If no AudioFormatWriter can be created by this method,
  24990. the stream will NOT be deleted, so that the caller can re-use it
  24991. to try to open a different format, etc
  24992. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  24993. returned by getPossibleSampleRates()
  24994. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  24995. the choice will depend on the results of canDoMono() and
  24996. canDoStereo()
  24997. @param bitsPerSample the bits per sample to use - this must be one of the values
  24998. returned by getPossibleBitDepths()
  24999. @param metadataValues a set of metadata values that the writer should try to write
  25000. to the stream. Exactly what these are depends on the format,
  25001. and the subclass doesn't actually have to do anything with
  25002. them if it doesn't want to. Have a look at the specific format
  25003. implementation classes to see possible values that can be
  25004. used
  25005. @param qualityOptionIndex the index of one of compression qualities returned by the
  25006. getQualityOptions() method. If there aren't any quality options
  25007. for this format, just pass 0 in this parameter, as it'll be
  25008. ignored
  25009. @see AudioFormatWriter
  25010. */
  25011. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  25012. double sampleRateToUse,
  25013. unsigned int numberOfChannels,
  25014. int bitsPerSample,
  25015. const StringPairArray& metadataValues,
  25016. int qualityOptionIndex) = 0;
  25017. protected:
  25018. /** Creates an AudioFormat object.
  25019. @param formatName this sets the value that will be returned by getFormatName()
  25020. @param fileExtensions a zero-terminated list of file extensions - this is what will
  25021. be returned by getFileExtension()
  25022. */
  25023. AudioFormat (const String& formatName,
  25024. const StringArray& fileExtensions);
  25025. private:
  25026. String formatName;
  25027. StringArray fileExtensions;
  25028. };
  25029. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  25030. /*** End of inlined file: juce_AudioFormat.h ***/
  25031. /**
  25032. Reads and Writes AIFF format audio files.
  25033. @see AudioFormat
  25034. */
  25035. class JUCE_API AiffAudioFormat : public AudioFormat
  25036. {
  25037. public:
  25038. /** Creates an format object. */
  25039. AiffAudioFormat();
  25040. /** Destructor. */
  25041. ~AiffAudioFormat();
  25042. const Array <int> getPossibleSampleRates();
  25043. const Array <int> getPossibleBitDepths();
  25044. bool canDoStereo();
  25045. bool canDoMono();
  25046. #if JUCE_MAC
  25047. bool canHandleFile (const File& fileToTest);
  25048. #endif
  25049. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  25050. bool deleteStreamIfOpeningFails);
  25051. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  25052. double sampleRateToUse,
  25053. unsigned int numberOfChannels,
  25054. int bitsPerSample,
  25055. const StringPairArray& metadataValues,
  25056. int qualityOptionIndex);
  25057. private:
  25058. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  25059. };
  25060. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  25061. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  25062. #endif
  25063. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  25064. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  25065. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  25066. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  25067. #if JUCE_USE_CDBURNER || DOXYGEN
  25068. /**
  25069. */
  25070. class AudioCDBurner : public ChangeBroadcaster
  25071. {
  25072. public:
  25073. /** Returns a list of available optical drives.
  25074. Use openDevice() to open one of the items from this list.
  25075. */
  25076. static const StringArray findAvailableDevices();
  25077. /** Tries to open one of the optical drives.
  25078. The deviceIndex is an index into the array returned by findAvailableDevices().
  25079. */
  25080. static AudioCDBurner* openDevice (const int deviceIndex);
  25081. /** Destructor. */
  25082. ~AudioCDBurner();
  25083. enum DiskState
  25084. {
  25085. unknown, /**< An error condition, if the device isn't responding. */
  25086. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  25087. may seem to be permanently open. */
  25088. noDisc, /**< The drive has no disk in it. */
  25089. writableDiskPresent, /**< The drive contains a writeable disk. */
  25090. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  25091. };
  25092. /** Returns the current status of the device.
  25093. To get informed when the drive's status changes, attach a ChangeListener to
  25094. the AudioCDBurner.
  25095. */
  25096. DiskState getDiskState() const;
  25097. /** Returns true if there's a writable disk in the drive. */
  25098. bool isDiskPresent() const;
  25099. /** Sends an eject signal to the drive.
  25100. The eject will happen asynchronously, so you can use getDiskState() and
  25101. waitUntilStateChange() to monitor its progress.
  25102. */
  25103. bool openTray();
  25104. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  25105. @returns the device's new state
  25106. */
  25107. DiskState waitUntilStateChange (int timeOutMilliseconds);
  25108. /** Returns the set of possible write speeds that the device can handle.
  25109. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  25110. Note that if there's no media present in the drive, this value may be unavailable!
  25111. @see setWriteSpeed, getWriteSpeed
  25112. */
  25113. const Array<int> getAvailableWriteSpeeds() const;
  25114. /** Tries to enable or disable buffer underrun safety on devices that support it.
  25115. @returns true if it's now enabled. If the device doesn't support it, this
  25116. will always return false.
  25117. */
  25118. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  25119. /** Returns the number of free blocks on the disk.
  25120. There are 75 blocks per second, at 44100Hz.
  25121. */
  25122. int getNumAvailableAudioBlocks() const;
  25123. /** Adds a track to be written.
  25124. The source passed-in here will be kept by this object, and it will
  25125. be used and deleted at some point in the future, either during the
  25126. burn() method or when this AudioCDBurner object is deleted. Your caller
  25127. method shouldn't keep a reference to it or use it again after passing
  25128. it in here.
  25129. */
  25130. bool addAudioTrack (AudioSource* source, int numSamples);
  25131. /** Receives progress callbacks during a cd-burn operation.
  25132. @see AudioCDBurner::burn()
  25133. */
  25134. class BurnProgressListener
  25135. {
  25136. public:
  25137. BurnProgressListener() throw() {}
  25138. virtual ~BurnProgressListener() {}
  25139. /** Called at intervals to report on the progress of the AudioCDBurner.
  25140. To cancel the burn, return true from this method.
  25141. */
  25142. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  25143. };
  25144. /** Runs the burn process.
  25145. This method will block until the operation is complete.
  25146. @param listener the object to receive callbacks about progress
  25147. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  25148. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  25149. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  25150. 0 or less to mean the fastest speed.
  25151. */
  25152. const String burn (BurnProgressListener* listener,
  25153. bool ejectDiscAfterwards,
  25154. bool performFakeBurnForTesting,
  25155. int writeSpeed);
  25156. /** If a burn operation is currently in progress, this tells it to stop
  25157. as soon as possible.
  25158. It's also possible to stop the burn process by returning true from
  25159. BurnProgressListener::audioCDBurnProgress()
  25160. */
  25161. void abortBurn();
  25162. private:
  25163. AudioCDBurner (const int deviceIndex);
  25164. class Pimpl;
  25165. friend class ScopedPointer<Pimpl>;
  25166. ScopedPointer<Pimpl> pimpl;
  25167. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  25168. };
  25169. #endif
  25170. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  25171. /*** End of inlined file: juce_AudioCDBurner.h ***/
  25172. #endif
  25173. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  25174. /*** Start of inlined file: juce_AudioCDReader.h ***/
  25175. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  25176. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  25177. #if JUCE_USE_CDREADER || DOXYGEN
  25178. #if JUCE_MAC
  25179. #endif
  25180. /**
  25181. A type of AudioFormatReader that reads from an audio CD.
  25182. One of these can be used to read a CD as if it's one big audio stream. Use the
  25183. getPositionOfTrackStart() method to find where the individual tracks are
  25184. within the stream.
  25185. @see AudioFormatReader
  25186. */
  25187. class JUCE_API AudioCDReader : public AudioFormatReader
  25188. {
  25189. public:
  25190. /** Returns a list of names of Audio CDs currently available for reading.
  25191. If there's a CD drive but no CD in it, this might return an empty list, or
  25192. possibly a device that can be opened but which has no tracks, depending
  25193. on the platform.
  25194. @see createReaderForCD
  25195. */
  25196. static const StringArray getAvailableCDNames();
  25197. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  25198. @param index the index of one of the available CDs - use getAvailableCDNames()
  25199. to find out how many there are.
  25200. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  25201. caller will be responsible for deleting the object returned.
  25202. */
  25203. static AudioCDReader* createReaderForCD (const int index);
  25204. /** Destructor. */
  25205. ~AudioCDReader();
  25206. /** Implementation of the AudioFormatReader method. */
  25207. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  25208. int64 startSampleInFile, int numSamples);
  25209. /** Checks whether the CD has been removed from the drive.
  25210. */
  25211. bool isCDStillPresent() const;
  25212. /** Returns the total number of tracks (audio + data).
  25213. */
  25214. int getNumTracks() const;
  25215. /** Finds the sample offset of the start of a track.
  25216. @param trackNum the track number, where trackNum = 0 is the first track
  25217. and trackNum = getNumTracks() means the end of the CD.
  25218. */
  25219. int getPositionOfTrackStart (int trackNum) const;
  25220. /** Returns true if a given track is an audio track.
  25221. @param trackNum the track number, where 0 is the first track.
  25222. */
  25223. bool isTrackAudio (int trackNum) const;
  25224. /** Returns an array of sample offsets for the start of each track, followed by
  25225. the sample position of the end of the CD.
  25226. */
  25227. const Array<int>& getTrackOffsets() const;
  25228. /** Refreshes the object's table of contents.
  25229. If the disc has been ejected and a different one put in since this
  25230. object was created, this will cause it to update its idea of how many tracks
  25231. there are, etc.
  25232. */
  25233. void refreshTrackLengths();
  25234. /** Enables scanning for indexes within tracks.
  25235. @see getLastIndex
  25236. */
  25237. void enableIndexScanning (bool enabled);
  25238. /** Returns the index number found during the last read() call.
  25239. Index scanning is turned off by default - turn it on with enableIndexScanning().
  25240. Then when the read() method is called, if it comes across an index within that
  25241. block, the index number is stored and returned by this method.
  25242. Some devices might not support indexes, of course.
  25243. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  25244. @see enableIndexScanning
  25245. */
  25246. int getLastIndex() const;
  25247. /** Scans a track to find the position of any indexes within it.
  25248. @param trackNumber the track to look in, where 0 is the first track on the disc
  25249. @returns an array of sample positions of any index points found (not including
  25250. the index that marks the start of the track)
  25251. */
  25252. const Array <int> findIndexesInTrack (const int trackNumber);
  25253. /** Returns the CDDB id number for the CD.
  25254. It's not a great way of identifying a disc, but it's traditional.
  25255. */
  25256. int getCDDBId();
  25257. /** Tries to eject the disk.
  25258. Of course this might not be possible, if some other process is using it.
  25259. */
  25260. void ejectDisk();
  25261. enum
  25262. {
  25263. framesPerSecond = 75,
  25264. samplesPerFrame = 44100 / framesPerSecond
  25265. };
  25266. private:
  25267. Array<int> trackStartSamples;
  25268. #if JUCE_MAC
  25269. File volumeDir;
  25270. Array<File> tracks;
  25271. int currentReaderTrack;
  25272. ScopedPointer <AudioFormatReader> reader;
  25273. AudioCDReader (const File& volume);
  25274. #elif JUCE_WINDOWS
  25275. bool audioTracks [100];
  25276. void* handle;
  25277. bool indexingEnabled;
  25278. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  25279. MemoryBlock buffer;
  25280. AudioCDReader (void* handle);
  25281. int getIndexAt (int samplePos);
  25282. #elif JUCE_LINUX
  25283. AudioCDReader();
  25284. #endif
  25285. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  25286. };
  25287. #endif
  25288. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  25289. /*** End of inlined file: juce_AudioCDReader.h ***/
  25290. #endif
  25291. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  25292. #endif
  25293. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  25294. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  25295. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  25296. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  25297. /**
  25298. A class for keeping a list of available audio formats, and for deciding which
  25299. one to use to open a given file.
  25300. You can either use this class as a singleton object, or create instances of it
  25301. yourself. Once created, use its registerFormat() method to tell it which
  25302. formats it should use.
  25303. @see AudioFormat
  25304. */
  25305. class JUCE_API AudioFormatManager
  25306. {
  25307. public:
  25308. /** Creates an empty format manager.
  25309. Before it'll be any use, you'll need to call registerFormat() with all the
  25310. formats you want it to be able to recognise.
  25311. */
  25312. AudioFormatManager();
  25313. /** Destructor. */
  25314. ~AudioFormatManager();
  25315. /** Adds a format to the manager's list of available file types.
  25316. The object passed-in will be deleted by this object, so don't keep a pointer
  25317. to it!
  25318. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  25319. return this one when called.
  25320. */
  25321. void registerFormat (AudioFormat* newFormat,
  25322. bool makeThisTheDefaultFormat);
  25323. /** Handy method to make it easy to register the formats that come with Juce.
  25324. Currently, this will add WAV and AIFF to the list.
  25325. */
  25326. void registerBasicFormats();
  25327. /** Clears the list of known formats. */
  25328. void clearFormats();
  25329. /** Returns the number of currently registered file formats. */
  25330. int getNumKnownFormats() const;
  25331. /** Returns one of the registered file formats. */
  25332. AudioFormat* getKnownFormat (int index) const;
  25333. /** Looks for which of the known formats is listed as being for a given file
  25334. extension.
  25335. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  25336. */
  25337. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  25338. /** Returns the format which has been set as the default one.
  25339. You can set a format as being the default when it is registered. It's useful
  25340. when you want to write to a file, because the best format may change between
  25341. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  25342. If none has been set as the default, this method will just return the first
  25343. one in the list.
  25344. */
  25345. AudioFormat* getDefaultFormat() const;
  25346. /** Returns a set of wildcards for file-matching that contains the extensions for
  25347. all known formats.
  25348. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  25349. */
  25350. const String getWildcardForAllFormats() const;
  25351. /** Searches through the known formats to try to create a suitable reader for
  25352. this file.
  25353. If none of the registered formats can open the file, it'll return 0. If it
  25354. returns a reader, it's the caller's responsibility to delete the reader.
  25355. */
  25356. AudioFormatReader* createReaderFor (const File& audioFile);
  25357. /** Searches through the known formats to try to create a suitable reader for
  25358. this stream.
  25359. The stream object that is passed-in will be deleted by this method or by the
  25360. reader that is returned, so the caller should not keep any references to it.
  25361. The stream that is passed-in must be capable of being repositioned so
  25362. that all the formats can have a go at opening it.
  25363. If none of the registered formats can open the stream, it'll return 0. If it
  25364. returns a reader, it's the caller's responsibility to delete the reader.
  25365. */
  25366. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  25367. private:
  25368. OwnedArray<AudioFormat> knownFormats;
  25369. int defaultFormatIndex;
  25370. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  25371. };
  25372. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  25373. /*** End of inlined file: juce_AudioFormatManager.h ***/
  25374. #endif
  25375. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  25376. #endif
  25377. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  25378. #endif
  25379. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  25380. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  25381. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  25382. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  25383. /**
  25384. This class is used to wrap an AudioFormatReader and only read from a
  25385. subsection of the file.
  25386. So if you have a reader which can read a 1000 sample file, you could wrap it
  25387. in one of these to only access, e.g. samples 100 to 200, and any samples
  25388. outside that will come back as 0. Accessing sample 0 from this reader will
  25389. actually read the first sample from the other's subsection, which might
  25390. be at a non-zero position.
  25391. @see AudioFormatReader
  25392. */
  25393. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  25394. {
  25395. public:
  25396. /** Creates a AudioSubsectionReader for a given data source.
  25397. @param sourceReader the source reader from which we'll be taking data
  25398. @param subsectionStartSample the sample within the source reader which will be
  25399. mapped onto sample 0 for this reader.
  25400. @param subsectionLength the number of samples from the source that will
  25401. make up the subsection. If this reader is asked for
  25402. any samples beyond this region, it will return zero.
  25403. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  25404. this object is deleted.
  25405. */
  25406. AudioSubsectionReader (AudioFormatReader* sourceReader,
  25407. int64 subsectionStartSample,
  25408. int64 subsectionLength,
  25409. bool deleteSourceWhenDeleted);
  25410. /** Destructor. */
  25411. ~AudioSubsectionReader();
  25412. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  25413. int64 startSampleInFile, int numSamples);
  25414. void readMaxLevels (int64 startSample,
  25415. int64 numSamples,
  25416. float& lowestLeft,
  25417. float& highestLeft,
  25418. float& lowestRight,
  25419. float& highestRight);
  25420. private:
  25421. AudioFormatReader* const source;
  25422. int64 startSample, length;
  25423. const bool deleteSourceWhenDeleted;
  25424. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  25425. };
  25426. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  25427. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  25428. #endif
  25429. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  25430. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  25431. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  25432. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  25433. class AudioThumbnailCache;
  25434. /**
  25435. Makes it easy to quickly draw scaled views of the waveform shape of an
  25436. audio file.
  25437. To use this class, just create an AudioThumbNail class for the file you want
  25438. to draw, call setSource to tell it which file or resource to use, then call
  25439. drawChannel() to draw it.
  25440. The class will asynchronously scan the wavefile to create its scaled-down view,
  25441. so you should make your UI repaint itself as this data comes in. To do this, the
  25442. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  25443. listeners should repaint themselves.
  25444. The thumbnail stores an internal low-res version of the wave data, and this can
  25445. be loaded and saved to avoid having to scan the file again.
  25446. @see AudioThumbnailCache
  25447. */
  25448. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  25449. {
  25450. public:
  25451. /** Creates an audio thumbnail.
  25452. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  25453. of the audio data, this is the scale at which it should be done. (This
  25454. number is the number of original samples that will be averaged for each
  25455. low-res sample)
  25456. @param formatManagerToUse the audio format manager that is used to open the file
  25457. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  25458. thread and storage that is used to by the thumbnail, and the cache
  25459. object can be shared between multiple thumbnails
  25460. */
  25461. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  25462. AudioFormatManager& formatManagerToUse,
  25463. AudioThumbnailCache& cacheToUse);
  25464. /** Destructor. */
  25465. ~AudioThumbnail();
  25466. /** Clears and resets the thumbnail. */
  25467. void clear();
  25468. /** Specifies the file or stream that contains the audio file.
  25469. For a file, just call
  25470. @code
  25471. setSource (new FileInputSource (file))
  25472. @endcode
  25473. You can pass a zero in here to clear the thumbnail.
  25474. The source that is passed in will be deleted by this object when it is no longer needed.
  25475. @returns true if the source could be opened as a valid audio file, false if this failed for
  25476. some reason.
  25477. */
  25478. bool setSource (InputSource* newSource);
  25479. /** Gives the thumbnail an AudioFormatReader to use directly.
  25480. This will start parsing the audio in a background thread (unless the hash code
  25481. can be looked-up successfully in the thumbnail cache). Note that the reader
  25482. object will be held by the thumbnail and deleted later when no longer needed.
  25483. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  25484. or change the input source, so the file will be held open for all this time. If
  25485. you don't want the thumbnail to keep a file handle open continuously, you
  25486. should use the setSource() method instead, which will only open the file when
  25487. it needs to.
  25488. */
  25489. void setReader (AudioFormatReader* newReader, int64 hashCode);
  25490. /** Resets the thumbnail, ready for adding data with the specified format.
  25491. If you're going to generate a thumbnail yourself, call this before using addBlock()
  25492. to add the data.
  25493. */
  25494. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  25495. /** Adds a block of level data to the thumbnail.
  25496. Call reset() before using this, to tell the thumbnail about the data format.
  25497. */
  25498. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  25499. int startOffsetInBuffer, int numSamples);
  25500. /** Reloads the low res thumbnail data from an input stream.
  25501. This is not an audio file stream! It takes a stream of thumbnail data that would
  25502. previously have been created by the saveTo() method.
  25503. @see saveTo
  25504. */
  25505. void loadFrom (InputStream& input);
  25506. /** Saves the low res thumbnail data to an output stream.
  25507. The data that is written can later be reloaded using loadFrom().
  25508. @see loadFrom
  25509. */
  25510. void saveTo (OutputStream& output) const;
  25511. /** Returns the number of channels in the file. */
  25512. int getNumChannels() const throw();
  25513. /** Returns the length of the audio file, in seconds. */
  25514. double getTotalLength() const throw();
  25515. /** Draws the waveform for a channel.
  25516. The waveform will be drawn within the specified rectangle, where startTime
  25517. and endTime specify the times within the audio file that should be positioned
  25518. at the left and right edges of the rectangle.
  25519. The waveform will be scaled vertically so that a full-volume sample will fill
  25520. the rectangle vertically, but you can also specify an extra vertical scale factor
  25521. with the verticalZoomFactor parameter.
  25522. */
  25523. void drawChannel (Graphics& g,
  25524. const Rectangle<int>& area,
  25525. double startTimeSeconds,
  25526. double endTimeSeconds,
  25527. int channelNum,
  25528. float verticalZoomFactor);
  25529. /** Draws the waveforms for all channels in the thumbnail.
  25530. This will call drawChannel() to render each of the thumbnail's channels, stacked
  25531. above each other within the specified area.
  25532. @see drawChannel
  25533. */
  25534. void drawChannels (Graphics& g,
  25535. const Rectangle<int>& area,
  25536. double startTimeSeconds,
  25537. double endTimeSeconds,
  25538. float verticalZoomFactor);
  25539. /** Returns true if the low res preview is fully generated. */
  25540. bool isFullyLoaded() const throw();
  25541. /** Returns the number of samples that have been set in the thumbnail. */
  25542. int64 getNumSamplesFinished() const throw();
  25543. /** Returns the highest level in the thumbnail.
  25544. Note that because the thumb only stores low-resolution data, this isn't
  25545. an accurate representation of the highest value, it's only a rough approximation.
  25546. */
  25547. float getApproximatePeak() const;
  25548. /** Returns the hash code that was set by setSource() or setReader(). */
  25549. int64 getHashCode() const;
  25550. #ifndef DOXYGEN
  25551. // (this is only public to avoid a VC6 bug)
  25552. class LevelDataSource;
  25553. #endif
  25554. private:
  25555. AudioFormatManager& formatManagerToUse;
  25556. AudioThumbnailCache& cache;
  25557. struct MinMaxValue;
  25558. class ThumbData;
  25559. class CachedWindow;
  25560. friend class LevelDataSource;
  25561. friend class ScopedPointer<LevelDataSource>;
  25562. friend class ThumbData;
  25563. friend class OwnedArray<ThumbData>;
  25564. friend class CachedWindow;
  25565. friend class ScopedPointer<CachedWindow>;
  25566. ScopedPointer<LevelDataSource> source;
  25567. ScopedPointer<CachedWindow> window;
  25568. OwnedArray<ThumbData> channels;
  25569. int32 samplesPerThumbSample;
  25570. int64 totalSamples, numSamplesFinished;
  25571. int32 numChannels;
  25572. double sampleRate;
  25573. CriticalSection lock;
  25574. bool setDataSource (LevelDataSource* newSource);
  25575. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  25576. void createChannels (int length);
  25577. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  25578. };
  25579. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  25580. /*** End of inlined file: juce_AudioThumbnail.h ***/
  25581. #endif
  25582. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  25583. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  25584. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  25585. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  25586. struct ThumbnailCacheEntry;
  25587. /**
  25588. An instance of this class is used to manage multiple AudioThumbnail objects.
  25589. The cache runs a single background thread that is shared by all the thumbnails
  25590. that need it, and it maintains a set of low-res previews in memory, to avoid
  25591. having to re-scan audio files too often.
  25592. @see AudioThumbnail
  25593. */
  25594. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  25595. {
  25596. public:
  25597. /** Creates a cache object.
  25598. The maxNumThumbsToStore parameter lets you specify how many previews should
  25599. be kept in memory at once.
  25600. */
  25601. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  25602. /** Destructor. */
  25603. ~AudioThumbnailCache();
  25604. /** Clears out any stored thumbnails.
  25605. */
  25606. void clear();
  25607. /** Reloads the specified thumb if this cache contains the appropriate stored
  25608. data.
  25609. This is called automatically by the AudioThumbnail class, so you shouldn't
  25610. normally need to call it directly.
  25611. */
  25612. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  25613. /** Stores the cachable data from the specified thumb in this cache.
  25614. This is called automatically by the AudioThumbnail class, so you shouldn't
  25615. normally need to call it directly.
  25616. */
  25617. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  25618. private:
  25619. OwnedArray <ThumbnailCacheEntry> thumbs;
  25620. int maxNumThumbsToStore;
  25621. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  25622. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  25623. };
  25624. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  25625. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  25626. #endif
  25627. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  25628. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  25629. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  25630. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  25631. #if JUCE_USE_FLAC || defined (DOXYGEN)
  25632. /**
  25633. Reads and writes the lossless-compression FLAC audio format.
  25634. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  25635. and make sure your include search path and library search path are set up to find
  25636. the FLAC header files and static libraries.
  25637. @see AudioFormat
  25638. */
  25639. class JUCE_API FlacAudioFormat : public AudioFormat
  25640. {
  25641. public:
  25642. FlacAudioFormat();
  25643. ~FlacAudioFormat();
  25644. const Array <int> getPossibleSampleRates();
  25645. const Array <int> getPossibleBitDepths();
  25646. bool canDoStereo();
  25647. bool canDoMono();
  25648. bool isCompressed();
  25649. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  25650. bool deleteStreamIfOpeningFails);
  25651. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  25652. double sampleRateToUse,
  25653. unsigned int numberOfChannels,
  25654. int bitsPerSample,
  25655. const StringPairArray& metadataValues,
  25656. int qualityOptionIndex);
  25657. private:
  25658. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  25659. };
  25660. #endif
  25661. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  25662. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  25663. #endif
  25664. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  25665. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  25666. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  25667. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  25668. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  25669. /**
  25670. Reads and writes the Ogg-Vorbis audio format.
  25671. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  25672. and make sure your include search path and library search path are set up to find
  25673. the Vorbis and Ogg header files and static libraries.
  25674. @see AudioFormat,
  25675. */
  25676. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  25677. {
  25678. public:
  25679. OggVorbisAudioFormat();
  25680. ~OggVorbisAudioFormat();
  25681. const Array <int> getPossibleSampleRates();
  25682. const Array <int> getPossibleBitDepths();
  25683. bool canDoStereo();
  25684. bool canDoMono();
  25685. bool isCompressed();
  25686. const StringArray getQualityOptions();
  25687. /** Tries to estimate the quality level of an ogg file based on its size.
  25688. If it can't read the file for some reason, this will just return 1 (medium quality),
  25689. otherwise it will return the approximate quality setting that would have been used
  25690. to create the file.
  25691. @see getQualityOptions
  25692. */
  25693. int estimateOggFileQuality (const File& source);
  25694. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  25695. bool deleteStreamIfOpeningFails);
  25696. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  25697. double sampleRateToUse,
  25698. unsigned int numberOfChannels,
  25699. int bitsPerSample,
  25700. const StringPairArray& metadataValues,
  25701. int qualityOptionIndex);
  25702. private:
  25703. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  25704. };
  25705. #endif
  25706. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  25707. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  25708. #endif
  25709. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  25710. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  25711. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  25712. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  25713. #if JUCE_QUICKTIME
  25714. /**
  25715. Uses QuickTime to read the audio track a movie or media file.
  25716. As well as QuickTime movies, this should also manage to open other audio
  25717. files that quicktime can understand, like mp3, m4a, etc.
  25718. @see AudioFormat
  25719. */
  25720. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  25721. {
  25722. public:
  25723. /** Creates a format object. */
  25724. QuickTimeAudioFormat();
  25725. /** Destructor. */
  25726. ~QuickTimeAudioFormat();
  25727. const Array <int> getPossibleSampleRates();
  25728. const Array <int> getPossibleBitDepths();
  25729. bool canDoStereo();
  25730. bool canDoMono();
  25731. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  25732. bool deleteStreamIfOpeningFails);
  25733. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  25734. double sampleRateToUse,
  25735. unsigned int numberOfChannels,
  25736. int bitsPerSample,
  25737. const StringPairArray& metadataValues,
  25738. int qualityOptionIndex);
  25739. private:
  25740. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  25741. };
  25742. #endif
  25743. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  25744. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  25745. #endif
  25746. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  25747. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  25748. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  25749. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  25750. /**
  25751. Reads and Writes WAV format audio files.
  25752. @see AudioFormat
  25753. */
  25754. class JUCE_API WavAudioFormat : public AudioFormat
  25755. {
  25756. public:
  25757. /** Creates a format object. */
  25758. WavAudioFormat();
  25759. /** Destructor. */
  25760. ~WavAudioFormat();
  25761. /** Metadata property name used by wav readers and writers for adding
  25762. a BWAV chunk to the file.
  25763. @see AudioFormatReader::metadataValues, createWriterFor
  25764. */
  25765. static const char* const bwavDescription;
  25766. /** Metadata property name used by wav readers and writers for adding
  25767. a BWAV chunk to the file.
  25768. @see AudioFormatReader::metadataValues, createWriterFor
  25769. */
  25770. static const char* const bwavOriginator;
  25771. /** Metadata property name used by wav readers and writers for adding
  25772. a BWAV chunk to the file.
  25773. @see AudioFormatReader::metadataValues, createWriterFor
  25774. */
  25775. static const char* const bwavOriginatorRef;
  25776. /** Metadata property name used by wav readers and writers for adding
  25777. a BWAV chunk to the file.
  25778. Date format is: yyyy-mm-dd
  25779. @see AudioFormatReader::metadataValues, createWriterFor
  25780. */
  25781. static const char* const bwavOriginationDate;
  25782. /** Metadata property name used by wav readers and writers for adding
  25783. a BWAV chunk to the file.
  25784. Time format is: hh-mm-ss
  25785. @see AudioFormatReader::metadataValues, createWriterFor
  25786. */
  25787. static const char* const bwavOriginationTime;
  25788. /** Metadata property name used by wav readers and writers for adding
  25789. a BWAV chunk to the file.
  25790. This is the number of samples from the start of an edit that the
  25791. file is supposed to begin at. Seems like an obvious mistake to
  25792. only allow a file to occur in an edit once, but that's the way
  25793. it is..
  25794. @see AudioFormatReader::metadataValues, createWriterFor
  25795. */
  25796. static const char* const bwavTimeReference;
  25797. /** Metadata property name used by wav readers and writers for adding
  25798. a BWAV chunk to the file.
  25799. This is a
  25800. @see AudioFormatReader::metadataValues, createWriterFor
  25801. */
  25802. static const char* const bwavCodingHistory;
  25803. /** Utility function to fill out the appropriate metadata for a BWAV file.
  25804. This just makes it easier than using the property names directly, and it
  25805. fills out the time and date in the right format.
  25806. */
  25807. static const StringPairArray createBWAVMetadata (const String& description,
  25808. const String& originator,
  25809. const String& originatorRef,
  25810. const Time& dateAndTime,
  25811. const int64 timeReferenceSamples,
  25812. const String& codingHistory);
  25813. const Array <int> getPossibleSampleRates();
  25814. const Array <int> getPossibleBitDepths();
  25815. bool canDoStereo();
  25816. bool canDoMono();
  25817. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  25818. bool deleteStreamIfOpeningFails);
  25819. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  25820. double sampleRateToUse,
  25821. unsigned int numberOfChannels,
  25822. int bitsPerSample,
  25823. const StringPairArray& metadataValues,
  25824. int qualityOptionIndex);
  25825. /** Utility function to replace the metadata in a wav file with a new set of values.
  25826. If possible, this cheats by overwriting just the metadata region of the file, rather
  25827. than by copying the whole file again.
  25828. */
  25829. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  25830. private:
  25831. JUCE_LEAK_DETECTOR (WavAudioFormat);
  25832. };
  25833. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  25834. /*** End of inlined file: juce_WavAudioFormat.h ***/
  25835. #endif
  25836. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  25837. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  25838. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  25839. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  25840. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  25841. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  25842. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  25843. /**
  25844. A type of AudioSource which can be repositioned.
  25845. The basic AudioSource just streams continuously with no idea of a current
  25846. time or length, so the PositionableAudioSource is used for a finite stream
  25847. that has a current read position.
  25848. @see AudioSource, AudioTransportSource
  25849. */
  25850. class JUCE_API PositionableAudioSource : public AudioSource
  25851. {
  25852. protected:
  25853. /** Creates the PositionableAudioSource. */
  25854. PositionableAudioSource() throw() {}
  25855. public:
  25856. /** Destructor */
  25857. ~PositionableAudioSource() {}
  25858. /** Tells the stream to move to a new position.
  25859. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  25860. should return samples from this position.
  25861. Note that this may be called on a different thread to getNextAudioBlock(),
  25862. so the subclass should make sure it's synchronised.
  25863. */
  25864. virtual void setNextReadPosition (int newPosition) = 0;
  25865. /** Returns the position from which the next block will be returned.
  25866. @see setNextReadPosition
  25867. */
  25868. virtual int getNextReadPosition() const = 0;
  25869. /** Returns the total length of the stream (in samples). */
  25870. virtual int getTotalLength() const = 0;
  25871. /** Returns true if this source is actually playing in a loop. */
  25872. virtual bool isLooping() const = 0;
  25873. /** Tells the source whether you'd like it to play in a loop. */
  25874. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  25875. };
  25876. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  25877. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  25878. /**
  25879. A type of AudioSource that will read from an AudioFormatReader.
  25880. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  25881. */
  25882. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  25883. {
  25884. public:
  25885. /** Creates an AudioFormatReaderSource for a given reader.
  25886. @param sourceReader the reader to use as the data source
  25887. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  25888. when this object is deleted; if false it will be
  25889. left up to the caller to manage its lifetime
  25890. */
  25891. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  25892. bool deleteReaderWhenThisIsDeleted);
  25893. /** Destructor. */
  25894. ~AudioFormatReaderSource();
  25895. /** Toggles loop-mode.
  25896. If set to true, it will continuously loop the input source. If false,
  25897. it will just emit silence after the source has finished.
  25898. @see isLooping
  25899. */
  25900. void setLooping (bool shouldLoop);
  25901. /** Returns whether loop-mode is turned on or not. */
  25902. bool isLooping() const { return looping; }
  25903. /** Returns the reader that's being used. */
  25904. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  25905. /** Implementation of the AudioSource method. */
  25906. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  25907. /** Implementation of the AudioSource method. */
  25908. void releaseResources();
  25909. /** Implementation of the AudioSource method. */
  25910. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  25911. /** Implements the PositionableAudioSource method. */
  25912. void setNextReadPosition (int newPosition);
  25913. /** Implements the PositionableAudioSource method. */
  25914. int getNextReadPosition() const;
  25915. /** Implements the PositionableAudioSource method. */
  25916. int getTotalLength() const;
  25917. private:
  25918. AudioFormatReader* reader;
  25919. bool deleteReader;
  25920. int volatile nextPlayPos;
  25921. bool volatile looping;
  25922. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  25923. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  25924. };
  25925. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  25926. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  25927. #endif
  25928. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  25929. #endif
  25930. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  25931. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  25932. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  25933. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  25934. /*** Start of inlined file: juce_AudioIODevice.h ***/
  25935. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25936. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25937. class AudioIODevice;
  25938. /**
  25939. One of these is passed to an AudioIODevice object to stream the audio data
  25940. in and out.
  25941. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  25942. method on its own high-priority audio thread, when it needs to send or receive
  25943. the next block of data.
  25944. @see AudioIODevice, AudioDeviceManager
  25945. */
  25946. class JUCE_API AudioIODeviceCallback
  25947. {
  25948. public:
  25949. /** Destructor. */
  25950. virtual ~AudioIODeviceCallback() {}
  25951. /** Processes a block of incoming and outgoing audio data.
  25952. The subclass's implementation should use the incoming audio for whatever
  25953. purposes it needs to, and must fill all the output channels with the next
  25954. block of output data before returning.
  25955. The channel data is arranged with the same array indices as the channel name
  25956. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  25957. that aren't specified in AudioIODevice::open() will have a null pointer for their
  25958. associated channel, so remember to check for this.
  25959. @param inputChannelData a set of arrays containing the audio data for each
  25960. incoming channel - this data is valid until the function
  25961. returns. There will be one channel of data for each input
  25962. channel that was enabled when the audio device was opened
  25963. (see AudioIODevice::open())
  25964. @param numInputChannels the number of pointers to channel data in the
  25965. inputChannelData array.
  25966. @param outputChannelData a set of arrays which need to be filled with the data
  25967. that should be sent to each outgoing channel of the device.
  25968. There will be one channel of data for each output channel
  25969. that was enabled when the audio device was opened (see
  25970. AudioIODevice::open())
  25971. The initial contents of the array is undefined, so the
  25972. callback function must fill all the channels with zeros if
  25973. its output is silence. Failing to do this could cause quite
  25974. an unpleasant noise!
  25975. @param numOutputChannels the number of pointers to channel data in the
  25976. outputChannelData array.
  25977. @param numSamples the number of samples in each channel of the input and
  25978. output arrays. The number of samples will depend on the
  25979. audio device's buffer size and will usually remain constant,
  25980. although this isn't guaranteed, so make sure your code can
  25981. cope with reasonable changes in the buffer size from one
  25982. callback to the next.
  25983. */
  25984. virtual void audioDeviceIOCallback (const float** inputChannelData,
  25985. int numInputChannels,
  25986. float** outputChannelData,
  25987. int numOutputChannels,
  25988. int numSamples) = 0;
  25989. /** Called to indicate that the device is about to start calling back.
  25990. This will be called just before the audio callbacks begin, either when this
  25991. callback has just been added to an audio device, or after the device has been
  25992. restarted because of a sample-rate or block-size change.
  25993. You can use this opportunity to find out the sample rate and block size
  25994. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  25995. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  25996. @param device the audio IO device that will be used to drive the callback.
  25997. Note that if you're going to store this this pointer, it is
  25998. only valid until the next time that audioDeviceStopped is called.
  25999. */
  26000. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  26001. /** Called to indicate that the device has stopped.
  26002. */
  26003. virtual void audioDeviceStopped() = 0;
  26004. };
  26005. /**
  26006. Base class for an audio device with synchronised input and output channels.
  26007. Subclasses of this are used to implement different protocols such as DirectSound,
  26008. ASIO, CoreAudio, etc.
  26009. To create one of these, you'll need to use the AudioIODeviceType class - see the
  26010. documentation for that class for more info.
  26011. For an easier way of managing audio devices and their settings, have a look at the
  26012. AudioDeviceManager class.
  26013. @see AudioIODeviceType, AudioDeviceManager
  26014. */
  26015. class JUCE_API AudioIODevice
  26016. {
  26017. public:
  26018. /** Destructor. */
  26019. virtual ~AudioIODevice();
  26020. /** Returns the device's name, (as set in the constructor). */
  26021. const String& getName() const throw() { return name; }
  26022. /** Returns the type of the device.
  26023. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  26024. */
  26025. const String& getTypeName() const throw() { return typeName; }
  26026. /** Returns the names of all the available output channels on this device.
  26027. To find out which of these are currently in use, call getActiveOutputChannels().
  26028. */
  26029. virtual const StringArray getOutputChannelNames() = 0;
  26030. /** Returns the names of all the available input channels on this device.
  26031. To find out which of these are currently in use, call getActiveInputChannels().
  26032. */
  26033. virtual const StringArray getInputChannelNames() = 0;
  26034. /** Returns the number of sample-rates this device supports.
  26035. To find out which rates are available on this device, use this method to
  26036. find out how many there are, and getSampleRate() to get the rates.
  26037. @see getSampleRate
  26038. */
  26039. virtual int getNumSampleRates() = 0;
  26040. /** Returns one of the sample-rates this device supports.
  26041. To find out which rates are available on this device, use getNumSampleRates() to
  26042. find out how many there are, and getSampleRate() to get the individual rates.
  26043. The sample rate is set by the open() method.
  26044. (Note that for DirectSound some rates might not work, depending on combinations
  26045. of i/o channels that are being opened).
  26046. @see getNumSampleRates
  26047. */
  26048. virtual double getSampleRate (int index) = 0;
  26049. /** Returns the number of sizes of buffer that are available.
  26050. @see getBufferSizeSamples, getDefaultBufferSize
  26051. */
  26052. virtual int getNumBufferSizesAvailable() = 0;
  26053. /** Returns one of the possible buffer-sizes.
  26054. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  26055. @returns a number of samples
  26056. @see getNumBufferSizesAvailable, getDefaultBufferSize
  26057. */
  26058. virtual int getBufferSizeSamples (int index) = 0;
  26059. /** Returns the default buffer-size to use.
  26060. @returns a number of samples
  26061. @see getNumBufferSizesAvailable, getBufferSizeSamples
  26062. */
  26063. virtual int getDefaultBufferSize() = 0;
  26064. /** Tries to open the device ready to play.
  26065. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  26066. input channel should be enabled
  26067. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  26068. output channel should be enabled
  26069. @param sampleRate the sample rate to try to use - to find out which rates are
  26070. available, see getNumSampleRates() and getSampleRate()
  26071. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  26072. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  26073. @returns an error description if there's a problem, or an empty string if it succeeds in
  26074. opening the device
  26075. @see close
  26076. */
  26077. virtual const String open (const BigInteger& inputChannels,
  26078. const BigInteger& outputChannels,
  26079. double sampleRate,
  26080. int bufferSizeSamples) = 0;
  26081. /** Closes and releases the device if it's open. */
  26082. virtual void close() = 0;
  26083. /** Returns true if the device is still open.
  26084. A device might spontaneously close itself if something goes wrong, so this checks if
  26085. it's still open.
  26086. */
  26087. virtual bool isOpen() = 0;
  26088. /** Starts the device actually playing.
  26089. This must be called after the device has been opened.
  26090. @param callback the callback to use for streaming the data.
  26091. @see AudioIODeviceCallback, open
  26092. */
  26093. virtual void start (AudioIODeviceCallback* callback) = 0;
  26094. /** Stops the device playing.
  26095. Once a device has been started, this will stop it. Any pending calls to the
  26096. callback class will be flushed before this method returns.
  26097. */
  26098. virtual void stop() = 0;
  26099. /** Returns true if the device is still calling back.
  26100. The device might mysteriously stop, so this checks whether it's
  26101. still playing.
  26102. */
  26103. virtual bool isPlaying() = 0;
  26104. /** Returns the last error that happened if anything went wrong. */
  26105. virtual const String getLastError() = 0;
  26106. /** Returns the buffer size that the device is currently using.
  26107. If the device isn't actually open, this value doesn't really mean much.
  26108. */
  26109. virtual int getCurrentBufferSizeSamples() = 0;
  26110. /** Returns the sample rate that the device is currently using.
  26111. If the device isn't actually open, this value doesn't really mean much.
  26112. */
  26113. virtual double getCurrentSampleRate() = 0;
  26114. /** Returns the device's current physical bit-depth.
  26115. If the device isn't actually open, this value doesn't really mean much.
  26116. */
  26117. virtual int getCurrentBitDepth() = 0;
  26118. /** Returns a mask showing which of the available output channels are currently
  26119. enabled.
  26120. @see getOutputChannelNames
  26121. */
  26122. virtual const BigInteger getActiveOutputChannels() const = 0;
  26123. /** Returns a mask showing which of the available input channels are currently
  26124. enabled.
  26125. @see getInputChannelNames
  26126. */
  26127. virtual const BigInteger getActiveInputChannels() const = 0;
  26128. /** Returns the device's output latency.
  26129. This is the delay in samples between a callback getting a block of data, and
  26130. that data actually getting played.
  26131. */
  26132. virtual int getOutputLatencyInSamples() = 0;
  26133. /** Returns the device's input latency.
  26134. This is the delay in samples between some audio actually arriving at the soundcard,
  26135. and the callback getting passed this block of data.
  26136. */
  26137. virtual int getInputLatencyInSamples() = 0;
  26138. /** True if this device can show a pop-up control panel for editing its settings.
  26139. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  26140. to display it.
  26141. */
  26142. virtual bool hasControlPanel() const;
  26143. /** Shows a device-specific control panel if there is one.
  26144. This should only be called for devices which return true from hasControlPanel().
  26145. */
  26146. virtual bool showControlPanel();
  26147. protected:
  26148. /** Creates a device, setting its name and type member variables. */
  26149. AudioIODevice (const String& deviceName,
  26150. const String& typeName);
  26151. /** @internal */
  26152. String name, typeName;
  26153. };
  26154. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  26155. /*** End of inlined file: juce_AudioIODevice.h ***/
  26156. /**
  26157. Wrapper class to continuously stream audio from an audio source to an
  26158. AudioIODevice.
  26159. This object acts as an AudioIODeviceCallback, so can be attached to an
  26160. output device, and will stream audio from an AudioSource.
  26161. */
  26162. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  26163. {
  26164. public:
  26165. /** Creates an empty AudioSourcePlayer. */
  26166. AudioSourcePlayer();
  26167. /** Destructor.
  26168. Make sure this object isn't still being used by an AudioIODevice before
  26169. deleting it!
  26170. */
  26171. virtual ~AudioSourcePlayer();
  26172. /** Changes the current audio source to play from.
  26173. If the source passed in is already being used, this method will do nothing.
  26174. If the source is not null, its prepareToPlay() method will be called
  26175. before it starts being used for playback.
  26176. If there's another source currently playing, its releaseResources() method
  26177. will be called after it has been swapped for the new one.
  26178. @param newSource the new source to use - this will NOT be deleted
  26179. by this object when no longer needed, so it's the
  26180. caller's responsibility to manage it.
  26181. */
  26182. void setSource (AudioSource* newSource);
  26183. /** Returns the source that's playing.
  26184. May return 0 if there's no source.
  26185. */
  26186. AudioSource* getCurrentSource() const throw() { return source; }
  26187. /** Sets a gain to apply to the audio data.
  26188. @see getGain
  26189. */
  26190. void setGain (float newGain) throw();
  26191. /** Returns the current gain.
  26192. @see setGain
  26193. */
  26194. float getGain() const throw() { return gain; }
  26195. /** Implementation of the AudioIODeviceCallback method. */
  26196. void audioDeviceIOCallback (const float** inputChannelData,
  26197. int totalNumInputChannels,
  26198. float** outputChannelData,
  26199. int totalNumOutputChannels,
  26200. int numSamples);
  26201. /** Implementation of the AudioIODeviceCallback method. */
  26202. void audioDeviceAboutToStart (AudioIODevice* device);
  26203. /** Implementation of the AudioIODeviceCallback method. */
  26204. void audioDeviceStopped();
  26205. private:
  26206. CriticalSection readLock;
  26207. AudioSource* source;
  26208. double sampleRate;
  26209. int bufferSize;
  26210. float* channels [128];
  26211. float* outputChans [128];
  26212. const float* inputChans [128];
  26213. AudioSampleBuffer tempBuffer;
  26214. float lastGain, gain;
  26215. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  26216. };
  26217. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  26218. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  26219. #endif
  26220. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  26221. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  26222. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  26223. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  26224. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  26225. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  26226. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  26227. /**
  26228. An AudioSource which takes another source as input, and buffers it using a thread.
  26229. Create this as a wrapper around another thread, and it will read-ahead with
  26230. a background thread to smooth out playback. You can either create one of these
  26231. directly, or use it indirectly using an AudioTransportSource.
  26232. @see PositionableAudioSource, AudioTransportSource
  26233. */
  26234. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  26235. {
  26236. public:
  26237. /** Creates a BufferingAudioSource.
  26238. @param source the input source to read from
  26239. @param deleteSourceWhenDeleted if true, then the input source object will
  26240. be deleted when this object is deleted
  26241. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  26242. */
  26243. BufferingAudioSource (PositionableAudioSource* source,
  26244. bool deleteSourceWhenDeleted,
  26245. int numberOfSamplesToBuffer);
  26246. /** Destructor.
  26247. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  26248. flag was set in the constructor.
  26249. */
  26250. ~BufferingAudioSource();
  26251. /** Implementation of the AudioSource method. */
  26252. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  26253. /** Implementation of the AudioSource method. */
  26254. void releaseResources();
  26255. /** Implementation of the AudioSource method. */
  26256. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  26257. /** Implements the PositionableAudioSource method. */
  26258. void setNextReadPosition (int newPosition);
  26259. /** Implements the PositionableAudioSource method. */
  26260. int getNextReadPosition() const;
  26261. /** Implements the PositionableAudioSource method. */
  26262. int getTotalLength() const { return source->getTotalLength(); }
  26263. /** Implements the PositionableAudioSource method. */
  26264. bool isLooping() const { return source->isLooping(); }
  26265. private:
  26266. PositionableAudioSource* source;
  26267. bool deleteSourceWhenDeleted;
  26268. int numberOfSamplesToBuffer;
  26269. AudioSampleBuffer buffer;
  26270. CriticalSection bufferStartPosLock;
  26271. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  26272. bool wasSourceLooping;
  26273. double volatile sampleRate;
  26274. friend class SharedBufferingAudioSourceThread;
  26275. bool readNextBufferChunk();
  26276. void readBufferSection (int start, int length, int bufferOffset);
  26277. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  26278. };
  26279. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  26280. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  26281. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  26282. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  26283. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  26284. /**
  26285. A type of AudioSource that takes an input source and changes its sample rate.
  26286. @see AudioSource
  26287. */
  26288. class JUCE_API ResamplingAudioSource : public AudioSource
  26289. {
  26290. public:
  26291. /** Creates a ResamplingAudioSource for a given input source.
  26292. @param inputSource the input source to read from
  26293. @param deleteInputWhenDeleted if true, the input source will be deleted when
  26294. this object is deleted
  26295. @param numChannels the number of channels to process
  26296. */
  26297. ResamplingAudioSource (AudioSource* inputSource,
  26298. bool deleteInputWhenDeleted,
  26299. int numChannels = 2);
  26300. /** Destructor. */
  26301. ~ResamplingAudioSource();
  26302. /** Changes the resampling ratio.
  26303. (This value can be changed at any time, even while the source is running).
  26304. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  26305. values will speed it up; lower values will slow it
  26306. down. The ratio must be greater than 0
  26307. */
  26308. void setResamplingRatio (double samplesInPerOutputSample);
  26309. /** Returns the current resampling ratio.
  26310. This is the value that was set by setResamplingRatio().
  26311. */
  26312. double getResamplingRatio() const throw() { return ratio; }
  26313. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  26314. void releaseResources();
  26315. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  26316. private:
  26317. AudioSource* const input;
  26318. const bool deleteInputWhenDeleted;
  26319. double ratio, lastRatio;
  26320. AudioSampleBuffer buffer;
  26321. int bufferPos, sampsInBuffer;
  26322. double subSampleOffset;
  26323. double coefficients[6];
  26324. CriticalSection ratioLock;
  26325. const int numChannels;
  26326. HeapBlock<float*> destBuffers, srcBuffers;
  26327. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  26328. void createLowPass (double proportionalRate);
  26329. struct FilterState
  26330. {
  26331. double x1, x2, y1, y2;
  26332. };
  26333. HeapBlock<FilterState> filterStates;
  26334. void resetFilters();
  26335. void applyFilter (float* samples, int num, FilterState& fs);
  26336. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  26337. };
  26338. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  26339. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  26340. /**
  26341. An AudioSource that takes a PositionableAudioSource and allows it to be
  26342. played, stopped, started, etc.
  26343. This can also be told use a buffer and background thread to read ahead, and
  26344. if can correct for different sample-rates.
  26345. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  26346. to control playback of an audio file.
  26347. @see AudioSource, AudioSourcePlayer
  26348. */
  26349. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  26350. public ChangeBroadcaster
  26351. {
  26352. public:
  26353. /** Creates an AudioTransportSource.
  26354. After creating one of these, use the setSource() method to select an input source.
  26355. */
  26356. AudioTransportSource();
  26357. /** Destructor. */
  26358. ~AudioTransportSource();
  26359. /** Sets the reader that is being used as the input source.
  26360. This will stop playback, reset the position to 0 and change to the new reader.
  26361. The source passed in will not be deleted by this object, so must be managed by
  26362. the caller.
  26363. @param newSource the new input source to use. This may be zero
  26364. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  26365. is zero, no reading ahead will be done; if it's
  26366. greater than zero, a BufferingAudioSource will be used
  26367. to do the reading-ahead
  26368. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  26369. rate of the source, and playback will be sample-rate
  26370. adjusted to maintain playback at the correct pitch. If
  26371. this is 0, no sample-rate adjustment will be performed
  26372. */
  26373. void setSource (PositionableAudioSource* newSource,
  26374. int readAheadBufferSize = 0,
  26375. double sourceSampleRateToCorrectFor = 0.0);
  26376. /** Changes the current playback position in the source stream.
  26377. The next time the getNextAudioBlock() method is called, this
  26378. is the time from which it'll read data.
  26379. @see getPosition
  26380. */
  26381. void setPosition (double newPosition);
  26382. /** Returns the position that the next data block will be read from
  26383. This is a time in seconds.
  26384. */
  26385. double getCurrentPosition() const;
  26386. /** Returns the stream's length in seconds. */
  26387. double getLengthInSeconds() const;
  26388. /** Returns true if the player has stopped because its input stream ran out of data.
  26389. */
  26390. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  26391. /** Starts playing (if a source has been selected).
  26392. If it starts playing, this will send a message to any ChangeListeners
  26393. that are registered with this object.
  26394. */
  26395. void start();
  26396. /** Stops playing.
  26397. If it's actually playing, this will send a message to any ChangeListeners
  26398. that are registered with this object.
  26399. */
  26400. void stop();
  26401. /** Returns true if it's currently playing. */
  26402. bool isPlaying() const throw() { return playing; }
  26403. /** Changes the gain to apply to the output.
  26404. @param newGain a factor by which to multiply the outgoing samples,
  26405. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  26406. */
  26407. void setGain (float newGain) throw();
  26408. /** Returns the current gain setting.
  26409. @see setGain
  26410. */
  26411. float getGain() const throw() { return gain; }
  26412. /** Implementation of the AudioSource method. */
  26413. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  26414. /** Implementation of the AudioSource method. */
  26415. void releaseResources();
  26416. /** Implementation of the AudioSource method. */
  26417. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  26418. /** Implements the PositionableAudioSource method. */
  26419. void setNextReadPosition (int newPosition);
  26420. /** Implements the PositionableAudioSource method. */
  26421. int getNextReadPosition() const;
  26422. /** Implements the PositionableAudioSource method. */
  26423. int getTotalLength() const;
  26424. /** Implements the PositionableAudioSource method. */
  26425. bool isLooping() const;
  26426. private:
  26427. PositionableAudioSource* source;
  26428. ResamplingAudioSource* resamplerSource;
  26429. BufferingAudioSource* bufferingSource;
  26430. PositionableAudioSource* positionableSource;
  26431. AudioSource* masterSource;
  26432. CriticalSection callbackLock;
  26433. float volatile gain, lastGain;
  26434. bool volatile playing, stopped;
  26435. double sampleRate, sourceSampleRate;
  26436. int blockSize, readAheadBufferSize;
  26437. bool isPrepared, inputStreamEOF;
  26438. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  26439. };
  26440. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  26441. /*** End of inlined file: juce_AudioTransportSource.h ***/
  26442. #endif
  26443. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  26444. #endif
  26445. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  26446. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  26447. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  26448. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  26449. /**
  26450. An AudioSource that takes the audio from another source, and re-maps its
  26451. input and output channels to a different arrangement.
  26452. You can use this to increase or decrease the number of channels that an
  26453. audio source uses, or to re-order those channels.
  26454. Call the reset() method before using it to set up a default mapping, and then
  26455. the setInputChannelMapping() and setOutputChannelMapping() methods to
  26456. create an appropriate mapping, otherwise no channels will be connected and
  26457. it'll produce silence.
  26458. @see AudioSource
  26459. */
  26460. class ChannelRemappingAudioSource : public AudioSource
  26461. {
  26462. public:
  26463. /** Creates a remapping source that will pass on audio from the given input.
  26464. @param source the input source to use. Make sure that this doesn't
  26465. get deleted before the ChannelRemappingAudioSource object
  26466. @param deleteSourceWhenDeleted if true, the input source will be deleted
  26467. when this object is deleted, if false, the caller is
  26468. responsible for its deletion
  26469. */
  26470. ChannelRemappingAudioSource (AudioSource* source,
  26471. bool deleteSourceWhenDeleted);
  26472. /** Destructor. */
  26473. ~ChannelRemappingAudioSource();
  26474. /** Specifies a number of channels that this audio source must produce from its
  26475. getNextAudioBlock() callback.
  26476. */
  26477. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  26478. /** Clears any mapped channels.
  26479. After this, no channels are mapped, so this object will produce silence. Create
  26480. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  26481. */
  26482. void clearAllMappings();
  26483. /** Creates an input channel mapping.
  26484. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  26485. data will be sent to destChannelIndex of our input source.
  26486. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  26487. source specified when this object was created).
  26488. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  26489. during our getNextAudioBlock() callback
  26490. */
  26491. void setInputChannelMapping (int destChannelIndex,
  26492. int sourceChannelIndex);
  26493. /** Creates an output channel mapping.
  26494. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  26495. our input audio source will be copied to channel destChannelIndex of the final buffer.
  26496. @param sourceChannelIndex the index of an output channel coming from our input audio source
  26497. (i.e. the source specified when this object was created).
  26498. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  26499. during our getNextAudioBlock() callback
  26500. */
  26501. void setOutputChannelMapping (int sourceChannelIndex,
  26502. int destChannelIndex);
  26503. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  26504. our input audio source.
  26505. */
  26506. int getRemappedInputChannel (int inputChannelIndex) const;
  26507. /** Returns the output channel to which channel outputChannelIndex of our input audio
  26508. source will be sent to.
  26509. */
  26510. int getRemappedOutputChannel (int outputChannelIndex) const;
  26511. /** Returns an XML object to encapsulate the state of the mappings.
  26512. @see restoreFromXml
  26513. */
  26514. XmlElement* createXml() const;
  26515. /** Restores the mappings from an XML object created by createXML().
  26516. @see createXml
  26517. */
  26518. void restoreFromXml (const XmlElement& e);
  26519. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  26520. void releaseResources();
  26521. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  26522. private:
  26523. int requiredNumberOfChannels;
  26524. Array <int> remappedInputs, remappedOutputs;
  26525. AudioSource* const source;
  26526. const bool deleteSourceWhenDeleted;
  26527. AudioSampleBuffer buffer;
  26528. AudioSourceChannelInfo remappedInfo;
  26529. CriticalSection lock;
  26530. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  26531. };
  26532. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  26533. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  26534. #endif
  26535. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  26536. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  26537. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  26538. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  26539. /*** Start of inlined file: juce_IIRFilter.h ***/
  26540. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  26541. #define __JUCE_IIRFILTER_JUCEHEADER__
  26542. /**
  26543. An IIR filter that can perform low, high, or band-pass filtering on an
  26544. audio signal.
  26545. @see IIRFilterAudioSource
  26546. */
  26547. class JUCE_API IIRFilter
  26548. {
  26549. public:
  26550. /** Creates a filter.
  26551. Initially the filter is inactive, so will have no effect on samples that
  26552. you process with it. Use the appropriate method to turn it into the type
  26553. of filter needed.
  26554. */
  26555. IIRFilter();
  26556. /** Creates a copy of another filter. */
  26557. IIRFilter (const IIRFilter& other);
  26558. /** Destructor. */
  26559. ~IIRFilter();
  26560. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  26561. Note that this clears the processing state, but the type of filter and
  26562. its coefficients aren't changed. To put a filter into an inactive state, use
  26563. the makeInactive() method.
  26564. */
  26565. void reset() throw();
  26566. /** Performs the filter operation on the given set of samples.
  26567. */
  26568. void processSamples (float* samples,
  26569. int numSamples) throw();
  26570. /** Processes a single sample, without any locking or checking.
  26571. Use this if you need fast processing of a single value, but be aware that
  26572. this isn't thread-safe in the way that processSamples() is.
  26573. */
  26574. float processSingleSampleRaw (float sample) throw();
  26575. /** Sets the filter up to act as a low-pass filter.
  26576. */
  26577. void makeLowPass (double sampleRate,
  26578. double frequency) throw();
  26579. /** Sets the filter up to act as a high-pass filter.
  26580. */
  26581. void makeHighPass (double sampleRate,
  26582. double frequency) throw();
  26583. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  26584. The gain is a scale factor that the low frequencies are multiplied by, so values
  26585. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  26586. attenuate them.
  26587. */
  26588. void makeLowShelf (double sampleRate,
  26589. double cutOffFrequency,
  26590. double Q,
  26591. float gainFactor) throw();
  26592. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  26593. The gain is a scale factor that the high frequencies are multiplied by, so values
  26594. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  26595. attenuate them.
  26596. */
  26597. void makeHighShelf (double sampleRate,
  26598. double cutOffFrequency,
  26599. double Q,
  26600. float gainFactor) throw();
  26601. /** Sets the filter up to act as a band pass filter centred around a
  26602. frequency, with a variable Q and gain.
  26603. The gain is a scale factor that the centre frequencies are multiplied by, so
  26604. values greater than 1.0 will boost the centre frequencies, values less than
  26605. 1.0 will attenuate them.
  26606. */
  26607. void makeBandPass (double sampleRate,
  26608. double centreFrequency,
  26609. double Q,
  26610. float gainFactor) throw();
  26611. /** Clears the filter's coefficients so that it becomes inactive.
  26612. */
  26613. void makeInactive() throw();
  26614. /** Makes this filter duplicate the set-up of another one.
  26615. */
  26616. void copyCoefficientsFrom (const IIRFilter& other) throw();
  26617. protected:
  26618. CriticalSection processLock;
  26619. void setCoefficients (double c1, double c2, double c3,
  26620. double c4, double c5, double c6) throw();
  26621. bool active;
  26622. float coefficients[6];
  26623. float x1, x2, y1, y2;
  26624. // (use the copyCoefficientsFrom() method instead of this operator)
  26625. IIRFilter& operator= (const IIRFilter&);
  26626. JUCE_LEAK_DETECTOR (IIRFilter);
  26627. };
  26628. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  26629. /*** End of inlined file: juce_IIRFilter.h ***/
  26630. /**
  26631. An AudioSource that performs an IIR filter on another source.
  26632. */
  26633. class JUCE_API IIRFilterAudioSource : public AudioSource
  26634. {
  26635. public:
  26636. /** Creates a IIRFilterAudioSource for a given input source.
  26637. @param inputSource the input source to read from
  26638. @param deleteInputWhenDeleted if true, the input source will be deleted when
  26639. this object is deleted
  26640. */
  26641. IIRFilterAudioSource (AudioSource* inputSource,
  26642. bool deleteInputWhenDeleted);
  26643. /** Destructor. */
  26644. ~IIRFilterAudioSource();
  26645. /** Changes the filter to use the same parameters as the one being passed in.
  26646. */
  26647. void setFilterParameters (const IIRFilter& newSettings);
  26648. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  26649. void releaseResources();
  26650. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  26651. private:
  26652. AudioSource* const input;
  26653. const bool deleteInputWhenDeleted;
  26654. OwnedArray <IIRFilter> iirFilters;
  26655. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  26656. };
  26657. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  26658. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  26659. #endif
  26660. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  26661. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  26662. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  26663. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  26664. /**
  26665. An AudioSource that mixes together the output of a set of other AudioSources.
  26666. Input sources can be added and removed while the mixer is running as long as their
  26667. prepareToPlay() and releaseResources() methods are called before and after adding
  26668. them to the mixer.
  26669. */
  26670. class JUCE_API MixerAudioSource : public AudioSource
  26671. {
  26672. public:
  26673. /** Creates a MixerAudioSource.
  26674. */
  26675. MixerAudioSource();
  26676. /** Destructor. */
  26677. ~MixerAudioSource();
  26678. /** Adds an input source to the mixer.
  26679. If the mixer is running you'll need to make sure that the input source
  26680. is ready to play by calling its prepareToPlay() method before adding it.
  26681. If the mixer is stopped, then its input sources will be automatically
  26682. prepared when the mixer's prepareToPlay() method is called.
  26683. @param newInput the source to add to the mixer
  26684. @param deleteWhenRemoved if true, then this source will be deleted when
  26685. the mixer is deleted or when removeAllInputs() is
  26686. called (unless the source is previously removed
  26687. with the removeInputSource method)
  26688. */
  26689. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  26690. /** Removes an input source.
  26691. If the mixer is running, this will remove the source but not call its
  26692. releaseResources() method, so the caller might want to do this manually.
  26693. @param input the source to remove
  26694. @param deleteSource whether to delete this source after it's been removed
  26695. */
  26696. void removeInputSource (AudioSource* input, bool deleteSource);
  26697. /** Removes all the input sources.
  26698. If the mixer is running, this will remove the sources but not call their
  26699. releaseResources() method, so the caller might want to do this manually.
  26700. Any sources which were added with the deleteWhenRemoved flag set will be
  26701. deleted by this method.
  26702. */
  26703. void removeAllInputs();
  26704. /** Implementation of the AudioSource method.
  26705. This will call prepareToPlay() on all its input sources.
  26706. */
  26707. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  26708. /** Implementation of the AudioSource method.
  26709. This will call releaseResources() on all its input sources.
  26710. */
  26711. void releaseResources();
  26712. /** Implementation of the AudioSource method. */
  26713. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  26714. private:
  26715. Array <AudioSource*> inputs;
  26716. BigInteger inputsToDelete;
  26717. CriticalSection lock;
  26718. AudioSampleBuffer tempBuffer;
  26719. double currentSampleRate;
  26720. int bufferSizeExpected;
  26721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  26722. };
  26723. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  26724. /*** End of inlined file: juce_MixerAudioSource.h ***/
  26725. #endif
  26726. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  26727. #endif
  26728. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  26729. #endif
  26730. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  26731. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  26732. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  26733. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  26734. /**
  26735. A simple AudioSource that generates a sine wave.
  26736. */
  26737. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  26738. {
  26739. public:
  26740. /** Creates a ToneGeneratorAudioSource. */
  26741. ToneGeneratorAudioSource();
  26742. /** Destructor. */
  26743. ~ToneGeneratorAudioSource();
  26744. /** Sets the signal's amplitude. */
  26745. void setAmplitude (float newAmplitude);
  26746. /** Sets the signal's frequency. */
  26747. void setFrequency (double newFrequencyHz);
  26748. /** Implementation of the AudioSource method. */
  26749. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  26750. /** Implementation of the AudioSource method. */
  26751. void releaseResources();
  26752. /** Implementation of the AudioSource method. */
  26753. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  26754. private:
  26755. double frequency, sampleRate;
  26756. double currentPhase, phasePerSample;
  26757. float amplitude;
  26758. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  26759. };
  26760. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  26761. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  26762. #endif
  26763. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26764. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  26765. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26766. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26767. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  26768. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26769. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26770. class AudioDeviceManager;
  26771. class Component;
  26772. /**
  26773. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  26774. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  26775. method. Each of the objects returned can then be used to list the available
  26776. devices of that type. E.g.
  26777. @code
  26778. OwnedArray <AudioIODeviceType> types;
  26779. myAudioDeviceManager.createAudioDeviceTypes (types);
  26780. for (int i = 0; i < types.size(); ++i)
  26781. {
  26782. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  26783. types[i]->scanForDevices(); // This must be called before getting the list of devices
  26784. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  26785. for (int j = 0; j < deviceNames.size(); ++j)
  26786. {
  26787. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  26788. ...
  26789. }
  26790. }
  26791. @endcode
  26792. For an easier way of managing audio devices and their settings, have a look at the
  26793. AudioDeviceManager class.
  26794. @see AudioIODevice, AudioDeviceManager
  26795. */
  26796. class JUCE_API AudioIODeviceType
  26797. {
  26798. public:
  26799. /** Returns the name of this type of driver that this object manages.
  26800. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  26801. */
  26802. const String& getTypeName() const throw() { return typeName; }
  26803. /** Refreshes the object's cached list of known devices.
  26804. This must be called at least once before calling getDeviceNames() or any of
  26805. the other device creation methods.
  26806. */
  26807. virtual void scanForDevices() = 0;
  26808. /** Returns the list of available devices of this type.
  26809. The scanForDevices() method must have been called to create this list.
  26810. @param wantInputNames only really used by DirectSound where devices are split up
  26811. into inputs and outputs, this indicates whether to use
  26812. the input or output name to refer to a pair of devices.
  26813. */
  26814. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  26815. /** Returns the name of the default device.
  26816. This will be one of the names from the getDeviceNames() list.
  26817. @param forInput if true, this means that a default input device should be
  26818. returned; if false, it should return the default output
  26819. */
  26820. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  26821. /** Returns the index of a given device in the list of device names.
  26822. If asInput is true, it shows the index in the inputs list, otherwise it
  26823. looks for it in the outputs list.
  26824. */
  26825. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  26826. /** Returns true if two different devices can be used for the input and output.
  26827. */
  26828. virtual bool hasSeparateInputsAndOutputs() const = 0;
  26829. /** Creates one of the devices of this type.
  26830. The deviceName must be one of the strings returned by getDeviceNames(), and
  26831. scanForDevices() must have been called before this method is used.
  26832. */
  26833. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  26834. const String& inputDeviceName) = 0;
  26835. struct DeviceSetupDetails
  26836. {
  26837. AudioDeviceManager* manager;
  26838. int minNumInputChannels, maxNumInputChannels;
  26839. int minNumOutputChannels, maxNumOutputChannels;
  26840. bool useStereoPairs;
  26841. };
  26842. /** Destructor. */
  26843. virtual ~AudioIODeviceType();
  26844. protected:
  26845. explicit AudioIODeviceType (const String& typeName);
  26846. private:
  26847. String typeName;
  26848. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  26849. };
  26850. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26851. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  26852. /*** Start of inlined file: juce_MidiInput.h ***/
  26853. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  26854. #define __JUCE_MIDIINPUT_JUCEHEADER__
  26855. /*** Start of inlined file: juce_MidiMessage.h ***/
  26856. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  26857. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  26858. /**
  26859. Encapsulates a MIDI message.
  26860. @see MidiMessageSequence, MidiOutput, MidiInput
  26861. */
  26862. class JUCE_API MidiMessage
  26863. {
  26864. public:
  26865. /** Creates a 3-byte short midi message.
  26866. @param byte1 message byte 1
  26867. @param byte2 message byte 2
  26868. @param byte3 message byte 3
  26869. @param timeStamp the time to give the midi message - this value doesn't
  26870. use any particular units, so will be application-specific
  26871. */
  26872. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  26873. /** Creates a 2-byte short midi message.
  26874. @param byte1 message byte 1
  26875. @param byte2 message byte 2
  26876. @param timeStamp the time to give the midi message - this value doesn't
  26877. use any particular units, so will be application-specific
  26878. */
  26879. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  26880. /** Creates a 1-byte short midi message.
  26881. @param byte1 message byte 1
  26882. @param timeStamp the time to give the midi message - this value doesn't
  26883. use any particular units, so will be application-specific
  26884. */
  26885. MidiMessage (int byte1, double timeStamp = 0) throw();
  26886. /** Creates a midi message from a block of data. */
  26887. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  26888. /** Reads the next midi message from some data.
  26889. This will read as many bytes from a data stream as it needs to make a
  26890. complete message, and will return the number of bytes it used. This lets
  26891. you read a sequence of midi messages from a file or stream.
  26892. @param data the data to read from
  26893. @param maxBytesToUse the maximum number of bytes it's allowed to read
  26894. @param numBytesUsed returns the number of bytes that were actually needed
  26895. @param lastStatusByte in a sequence of midi messages, the initial byte
  26896. can be dropped from a message if it's the same as the
  26897. first byte of the previous message, so this lets you
  26898. supply the byte to use if the first byte of the message
  26899. has in fact been dropped.
  26900. @param timeStamp the time to give the midi message - this value doesn't
  26901. use any particular units, so will be application-specific
  26902. */
  26903. MidiMessage (const void* data, int maxBytesToUse,
  26904. int& numBytesUsed, uint8 lastStatusByte,
  26905. double timeStamp = 0);
  26906. /** Creates an active-sense message.
  26907. Since the MidiMessage has to contain a valid message, this default constructor
  26908. just initialises it with an empty sysex message.
  26909. */
  26910. MidiMessage() throw();
  26911. /** Creates a copy of another midi message. */
  26912. MidiMessage (const MidiMessage& other);
  26913. /** Creates a copy of another midi message, with a different timestamp. */
  26914. MidiMessage (const MidiMessage& other, double newTimeStamp);
  26915. /** Destructor. */
  26916. ~MidiMessage();
  26917. /** Copies this message from another one. */
  26918. MidiMessage& operator= (const MidiMessage& other);
  26919. /** Returns a pointer to the raw midi data.
  26920. @see getRawDataSize
  26921. */
  26922. uint8* getRawData() const throw() { return data; }
  26923. /** Returns the number of bytes of data in the message.
  26924. @see getRawData
  26925. */
  26926. int getRawDataSize() const throw() { return size; }
  26927. /** Returns the timestamp associated with this message.
  26928. The exact meaning of this time and its units will vary, as messages are used in
  26929. a variety of different contexts.
  26930. If you're getting the message from a midi file, this could be a time in seconds, or
  26931. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  26932. If the message is being used in a MidiBuffer, it might indicate the number of
  26933. audio samples from the start of the buffer.
  26934. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  26935. for details of the way that it initialises this value.
  26936. @see setTimeStamp, addToTimeStamp
  26937. */
  26938. double getTimeStamp() const throw() { return timeStamp; }
  26939. /** Changes the message's associated timestamp.
  26940. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  26941. @see addToTimeStamp, getTimeStamp
  26942. */
  26943. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  26944. /** Adds a value to the message's timestamp.
  26945. The units for the timestamp will be application-specific.
  26946. */
  26947. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  26948. /** Returns the midi channel associated with the message.
  26949. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  26950. if it's a sysex)
  26951. @see isForChannel, setChannel
  26952. */
  26953. int getChannel() const throw();
  26954. /** Returns true if the message applies to the given midi channel.
  26955. @param channelNumber the channel number to look for, in the range 1 to 16
  26956. @see getChannel, setChannel
  26957. */
  26958. bool isForChannel (int channelNumber) const throw();
  26959. /** Changes the message's midi channel.
  26960. This won't do anything for non-channel messages like sysexes.
  26961. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  26962. */
  26963. void setChannel (int newChannelNumber) throw();
  26964. /** Returns true if this is a system-exclusive message.
  26965. */
  26966. bool isSysEx() const throw();
  26967. /** Returns a pointer to the sysex data inside the message.
  26968. If this event isn't a sysex event, it'll return 0.
  26969. @see getSysExDataSize
  26970. */
  26971. const uint8* getSysExData() const throw();
  26972. /** Returns the size of the sysex data.
  26973. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  26974. @see getSysExData
  26975. */
  26976. int getSysExDataSize() const throw();
  26977. /** Returns true if this message is a 'key-down' event.
  26978. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  26979. velocity 0, it will still be considered to be a note-on and the
  26980. method will return true. If returnTrueForVelocity0 is false, then
  26981. if this is a note-on event with velocity 0, it'll be regarded as
  26982. a note-off, and the method will return false
  26983. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  26984. */
  26985. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  26986. /** Creates a key-down message (using a floating-point velocity).
  26987. @param channel the midi channel, in the range 1 to 16
  26988. @param noteNumber the key number, 0 to 127
  26989. @param velocity in the range 0 to 1.0
  26990. @see isNoteOn
  26991. */
  26992. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  26993. /** Creates a key-down message (using an integer velocity).
  26994. @param channel the midi channel, in the range 1 to 16
  26995. @param noteNumber the key number, 0 to 127
  26996. @param velocity in the range 0 to 127
  26997. @see isNoteOn
  26998. */
  26999. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  27000. /** Returns true if this message is a 'key-up' event.
  27001. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  27002. for a note-on event with a velocity of 0.
  27003. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  27004. */
  27005. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  27006. /** Creates a key-up message.
  27007. @param channel the midi channel, in the range 1 to 16
  27008. @param noteNumber the key number, 0 to 127
  27009. @see isNoteOff
  27010. */
  27011. static const MidiMessage noteOff (int channel, int noteNumber) throw();
  27012. /** Returns true if this message is a 'key-down' or 'key-up' event.
  27013. @see isNoteOn, isNoteOff
  27014. */
  27015. bool isNoteOnOrOff() const throw();
  27016. /** Returns the midi note number for note-on and note-off messages.
  27017. If the message isn't a note-on or off, the value returned will be
  27018. meaningless.
  27019. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  27020. */
  27021. int getNoteNumber() const throw();
  27022. /** Changes the midi note number of a note-on or note-off message.
  27023. If the message isn't a note on or off, this will do nothing.
  27024. */
  27025. void setNoteNumber (int newNoteNumber) throw();
  27026. /** Returns the velocity of a note-on or note-off message.
  27027. The value returned will be in the range 0 to 127.
  27028. If the message isn't a note-on or off event, it will return 0.
  27029. @see getFloatVelocity
  27030. */
  27031. uint8 getVelocity() const throw();
  27032. /** Returns the velocity of a note-on or note-off message.
  27033. The value returned will be in the range 0 to 1.0
  27034. If the message isn't a note-on or off event, it will return 0.
  27035. @see getVelocity, setVelocity
  27036. */
  27037. float getFloatVelocity() const throw();
  27038. /** Changes the velocity of a note-on or note-off message.
  27039. If the message isn't a note on or off, this will do nothing.
  27040. @param newVelocity the new velocity, in the range 0 to 1.0
  27041. @see getFloatVelocity, multiplyVelocity
  27042. */
  27043. void setVelocity (float newVelocity) throw();
  27044. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  27045. If the message isn't a note on or off, this will do nothing.
  27046. @param scaleFactor the value by which to multiply the velocity
  27047. @see setVelocity
  27048. */
  27049. void multiplyVelocity (float scaleFactor) throw();
  27050. /** Returns true if the message is a program (patch) change message.
  27051. @see getProgramChangeNumber, getGMInstrumentName
  27052. */
  27053. bool isProgramChange() const throw();
  27054. /** Returns the new program number of a program change message.
  27055. If the message isn't a program change, the value returned will be
  27056. nonsense.
  27057. @see isProgramChange, getGMInstrumentName
  27058. */
  27059. int getProgramChangeNumber() const throw();
  27060. /** Creates a program-change message.
  27061. @param channel the midi channel, in the range 1 to 16
  27062. @param programNumber the midi program number, 0 to 127
  27063. @see isProgramChange, getGMInstrumentName
  27064. */
  27065. static const MidiMessage programChange (int channel, int programNumber) throw();
  27066. /** Returns true if the message is a pitch-wheel move.
  27067. @see getPitchWheelValue, pitchWheel
  27068. */
  27069. bool isPitchWheel() const throw();
  27070. /** Returns the pitch wheel position from a pitch-wheel move message.
  27071. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  27072. If called for messages which aren't pitch wheel events, the number returned will be
  27073. nonsense.
  27074. @see isPitchWheel
  27075. */
  27076. int getPitchWheelValue() const throw();
  27077. /** Creates a pitch-wheel move message.
  27078. @param channel the midi channel, in the range 1 to 16
  27079. @param position the wheel position, in the range 0 to 16383
  27080. @see isPitchWheel
  27081. */
  27082. static const MidiMessage pitchWheel (int channel, int position) throw();
  27083. /** Returns true if the message is an aftertouch event.
  27084. For aftertouch events, use the getNoteNumber() method to find out the key
  27085. that it applies to, and getAftertouchValue() to find out the amount. Use
  27086. getChannel() to find out the channel.
  27087. @see getAftertouchValue, getNoteNumber
  27088. */
  27089. bool isAftertouch() const throw();
  27090. /** Returns the amount of aftertouch from an aftertouch messages.
  27091. The value returned is in the range 0 to 127, and will be nonsense for messages
  27092. other than aftertouch messages.
  27093. @see isAftertouch
  27094. */
  27095. int getAfterTouchValue() const throw();
  27096. /** Creates an aftertouch message.
  27097. @param channel the midi channel, in the range 1 to 16
  27098. @param noteNumber the key number, 0 to 127
  27099. @param aftertouchAmount the amount of aftertouch, 0 to 127
  27100. @see isAftertouch
  27101. */
  27102. static const MidiMessage aftertouchChange (int channel,
  27103. int noteNumber,
  27104. int aftertouchAmount) throw();
  27105. /** Returns true if the message is a channel-pressure change event.
  27106. This is like aftertouch, but common to the whole channel rather than a specific
  27107. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  27108. to find out the channel.
  27109. @see channelPressureChange
  27110. */
  27111. bool isChannelPressure() const throw();
  27112. /** Returns the pressure from a channel pressure change message.
  27113. @returns the pressure, in the range 0 to 127
  27114. @see isChannelPressure, channelPressureChange
  27115. */
  27116. int getChannelPressureValue() const throw();
  27117. /** Creates a channel-pressure change event.
  27118. @param channel the midi channel: 1 to 16
  27119. @param pressure the pressure, 0 to 127
  27120. @see isChannelPressure
  27121. */
  27122. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  27123. /** Returns true if this is a midi controller message.
  27124. @see getControllerNumber, getControllerValue, controllerEvent
  27125. */
  27126. bool isController() const throw();
  27127. /** Returns the controller number of a controller message.
  27128. The name of the controller can be looked up using the getControllerName() method.
  27129. Note that the value returned is invalid for messages that aren't controller changes.
  27130. @see isController, getControllerName, getControllerValue
  27131. */
  27132. int getControllerNumber() const throw();
  27133. /** Returns the controller value from a controller message.
  27134. A value 0 to 127 is returned to indicate the new controller position.
  27135. Note that the value returned is invalid for messages that aren't controller changes.
  27136. @see isController, getControllerNumber
  27137. */
  27138. int getControllerValue() const throw();
  27139. /** Creates a controller message.
  27140. @param channel the midi channel, in the range 1 to 16
  27141. @param controllerType the type of controller
  27142. @param value the controller value
  27143. @see isController
  27144. */
  27145. static const MidiMessage controllerEvent (int channel,
  27146. int controllerType,
  27147. int value) throw();
  27148. /** Checks whether this message is an all-notes-off message.
  27149. @see allNotesOff
  27150. */
  27151. bool isAllNotesOff() const throw();
  27152. /** Checks whether this message is an all-sound-off message.
  27153. @see allSoundOff
  27154. */
  27155. bool isAllSoundOff() const throw();
  27156. /** Creates an all-notes-off message.
  27157. @param channel the midi channel, in the range 1 to 16
  27158. @see isAllNotesOff
  27159. */
  27160. static const MidiMessage allNotesOff (int channel) throw();
  27161. /** Creates an all-sound-off message.
  27162. @param channel the midi channel, in the range 1 to 16
  27163. @see isAllSoundOff
  27164. */
  27165. static const MidiMessage allSoundOff (int channel) throw();
  27166. /** Creates an all-controllers-off message.
  27167. @param channel the midi channel, in the range 1 to 16
  27168. */
  27169. static const MidiMessage allControllersOff (int channel) throw();
  27170. /** Returns true if this event is a meta-event.
  27171. Meta-events are things like tempo changes, track names, etc.
  27172. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  27173. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  27174. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  27175. */
  27176. bool isMetaEvent() const throw();
  27177. /** Returns a meta-event's type number.
  27178. If the message isn't a meta-event, this will return -1.
  27179. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  27180. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  27181. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  27182. */
  27183. int getMetaEventType() const throw();
  27184. /** Returns a pointer to the data in a meta-event.
  27185. @see isMetaEvent, getMetaEventLength
  27186. */
  27187. const uint8* getMetaEventData() const throw();
  27188. /** Returns the length of the data for a meta-event.
  27189. @see isMetaEvent, getMetaEventData
  27190. */
  27191. int getMetaEventLength() const throw();
  27192. /** Returns true if this is a 'track' meta-event. */
  27193. bool isTrackMetaEvent() const throw();
  27194. /** Returns true if this is an 'end-of-track' meta-event. */
  27195. bool isEndOfTrackMetaEvent() const throw();
  27196. /** Creates an end-of-track meta-event.
  27197. @see isEndOfTrackMetaEvent
  27198. */
  27199. static const MidiMessage endOfTrack() throw();
  27200. /** Returns true if this is an 'track name' meta-event.
  27201. You can use the getTextFromTextMetaEvent() method to get the track's name.
  27202. */
  27203. bool isTrackNameEvent() const throw();
  27204. /** Returns true if this is a 'text' meta-event.
  27205. @see getTextFromTextMetaEvent
  27206. */
  27207. bool isTextMetaEvent() const throw();
  27208. /** Returns the text from a text meta-event.
  27209. @see isTextMetaEvent
  27210. */
  27211. const String getTextFromTextMetaEvent() const;
  27212. /** Returns true if this is a 'tempo' meta-event.
  27213. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  27214. */
  27215. bool isTempoMetaEvent() const throw();
  27216. /** Returns the tick length from a tempo meta-event.
  27217. @param timeFormat the 16-bit time format value from the midi file's header.
  27218. @returns the tick length (in seconds).
  27219. @see isTempoMetaEvent
  27220. */
  27221. double getTempoMetaEventTickLength (short timeFormat) const throw();
  27222. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  27223. @see isTempoMetaEvent, getTempoMetaEventTickLength
  27224. */
  27225. double getTempoSecondsPerQuarterNote() const throw();
  27226. /** Creates a tempo meta-event.
  27227. @see isTempoMetaEvent
  27228. */
  27229. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  27230. /** Returns true if this is a 'time-signature' meta-event.
  27231. @see getTimeSignatureInfo
  27232. */
  27233. bool isTimeSignatureMetaEvent() const throw();
  27234. /** Returns the time-signature values from a time-signature meta-event.
  27235. @see isTimeSignatureMetaEvent
  27236. */
  27237. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  27238. /** Creates a time-signature meta-event.
  27239. @see isTimeSignatureMetaEvent
  27240. */
  27241. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  27242. /** Returns true if this is a 'key-signature' meta-event.
  27243. @see getKeySignatureNumberOfSharpsOrFlats
  27244. */
  27245. bool isKeySignatureMetaEvent() const throw();
  27246. /** Returns the key from a key-signature meta-event.
  27247. @see isKeySignatureMetaEvent
  27248. */
  27249. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  27250. /** Returns true if this is a 'channel' meta-event.
  27251. A channel meta-event specifies the midi channel that should be used
  27252. for subsequent meta-events.
  27253. @see getMidiChannelMetaEventChannel
  27254. */
  27255. bool isMidiChannelMetaEvent() const throw();
  27256. /** Returns the channel number from a channel meta-event.
  27257. @returns the channel, in the range 1 to 16.
  27258. @see isMidiChannelMetaEvent
  27259. */
  27260. int getMidiChannelMetaEventChannel() const throw();
  27261. /** Creates a midi channel meta-event.
  27262. @param channel the midi channel, in the range 1 to 16
  27263. @see isMidiChannelMetaEvent
  27264. */
  27265. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  27266. /** Returns true if this is an active-sense message. */
  27267. bool isActiveSense() const throw();
  27268. /** Returns true if this is a midi start event.
  27269. @see midiStart
  27270. */
  27271. bool isMidiStart() const throw();
  27272. /** Creates a midi start event. */
  27273. static const MidiMessage midiStart() throw();
  27274. /** Returns true if this is a midi continue event.
  27275. @see midiContinue
  27276. */
  27277. bool isMidiContinue() const throw();
  27278. /** Creates a midi continue event. */
  27279. static const MidiMessage midiContinue() throw();
  27280. /** Returns true if this is a midi stop event.
  27281. @see midiStop
  27282. */
  27283. bool isMidiStop() const throw();
  27284. /** Creates a midi stop event. */
  27285. static const MidiMessage midiStop() throw();
  27286. /** Returns true if this is a midi clock event.
  27287. @see midiClock, songPositionPointer
  27288. */
  27289. bool isMidiClock() const throw();
  27290. /** Creates a midi clock event. */
  27291. static const MidiMessage midiClock() throw();
  27292. /** Returns true if this is a song-position-pointer message.
  27293. @see getSongPositionPointerMidiBeat, songPositionPointer
  27294. */
  27295. bool isSongPositionPointer() const throw();
  27296. /** Returns the midi beat-number of a song-position-pointer message.
  27297. @see isSongPositionPointer, songPositionPointer
  27298. */
  27299. int getSongPositionPointerMidiBeat() const throw();
  27300. /** Creates a song-position-pointer message.
  27301. The position is a number of midi beats from the start of the song, where 1 midi
  27302. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  27303. are 4 midi beats in a quarter-note.
  27304. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  27305. */
  27306. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  27307. /** Returns true if this is a quarter-frame midi timecode message.
  27308. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  27309. */
  27310. bool isQuarterFrame() const throw();
  27311. /** Returns the sequence number of a quarter-frame midi timecode message.
  27312. This will be a value between 0 and 7.
  27313. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  27314. */
  27315. int getQuarterFrameSequenceNumber() const throw();
  27316. /** Returns the value from a quarter-frame message.
  27317. This will be the lower nybble of the message's data-byte, a value
  27318. between 0 and 15
  27319. */
  27320. int getQuarterFrameValue() const throw();
  27321. /** Creates a quarter-frame MTC message.
  27322. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  27323. @param value a value 0 to 15 for the lower nybble of the message's data byte
  27324. */
  27325. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  27326. /** SMPTE timecode types.
  27327. Used by the getFullFrameParameters() and fullFrame() methods.
  27328. */
  27329. enum SmpteTimecodeType
  27330. {
  27331. fps24 = 0,
  27332. fps25 = 1,
  27333. fps30drop = 2,
  27334. fps30 = 3
  27335. };
  27336. /** Returns true if this is a full-frame midi timecode message.
  27337. */
  27338. bool isFullFrame() const throw();
  27339. /** Extracts the timecode information from a full-frame midi timecode message.
  27340. You should only call this on messages where you've used isFullFrame() to
  27341. check that they're the right kind.
  27342. */
  27343. void getFullFrameParameters (int& hours,
  27344. int& minutes,
  27345. int& seconds,
  27346. int& frames,
  27347. SmpteTimecodeType& timecodeType) const throw();
  27348. /** Creates a full-frame MTC message.
  27349. */
  27350. static const MidiMessage fullFrame (int hours,
  27351. int minutes,
  27352. int seconds,
  27353. int frames,
  27354. SmpteTimecodeType timecodeType);
  27355. /** Types of MMC command.
  27356. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  27357. */
  27358. enum MidiMachineControlCommand
  27359. {
  27360. mmc_stop = 1,
  27361. mmc_play = 2,
  27362. mmc_deferredplay = 3,
  27363. mmc_fastforward = 4,
  27364. mmc_rewind = 5,
  27365. mmc_recordStart = 6,
  27366. mmc_recordStop = 7,
  27367. mmc_pause = 9
  27368. };
  27369. /** Checks whether this is an MMC message.
  27370. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  27371. */
  27372. bool isMidiMachineControlMessage() const throw();
  27373. /** For an MMC message, this returns its type.
  27374. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  27375. calling this method.
  27376. */
  27377. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  27378. /** Creates an MMC message.
  27379. */
  27380. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  27381. /** Checks whether this is an MMC "goto" message.
  27382. If it is, the parameters passed-in are set to the time that the message contains.
  27383. @see midiMachineControlGoto
  27384. */
  27385. bool isMidiMachineControlGoto (int& hours,
  27386. int& minutes,
  27387. int& seconds,
  27388. int& frames) const throw();
  27389. /** Creates an MMC "goto" message.
  27390. This messages tells the device to go to a specific frame.
  27391. @see isMidiMachineControlGoto
  27392. */
  27393. static const MidiMessage midiMachineControlGoto (int hours,
  27394. int minutes,
  27395. int seconds,
  27396. int frames);
  27397. /** Creates a master-volume change message.
  27398. @param volume the volume, 0 to 1.0
  27399. */
  27400. static const MidiMessage masterVolume (float volume);
  27401. /** Creates a system-exclusive message.
  27402. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  27403. */
  27404. static const MidiMessage createSysExMessage (const uint8* sysexData,
  27405. int dataSize);
  27406. /** Reads a midi variable-length integer.
  27407. @param data the data to read the number from
  27408. @param numBytesUsed on return, this will be set to the number of bytes that were read
  27409. */
  27410. static int readVariableLengthVal (const uint8* data,
  27411. int& numBytesUsed) throw();
  27412. /** Based on the first byte of a short midi message, this uses a lookup table
  27413. to return the message length (either 1, 2, or 3 bytes).
  27414. The value passed in must be 0x80 or higher.
  27415. */
  27416. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  27417. /** Returns the name of a midi note number.
  27418. E.g "C", "D#", etc.
  27419. @param noteNumber the midi note number, 0 to 127
  27420. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  27421. they'll be flattened, e.g. "Db"
  27422. @param includeOctaveNumber if true, the octave number will be appended to the string,
  27423. e.g. "C#4"
  27424. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  27425. number that will be used for middle C's octave
  27426. @see getMidiNoteInHertz
  27427. */
  27428. static const String getMidiNoteName (int noteNumber,
  27429. bool useSharps,
  27430. bool includeOctaveNumber,
  27431. int octaveNumForMiddleC);
  27432. /** Returns the frequency of a midi note number.
  27433. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  27434. @see getMidiNoteName
  27435. */
  27436. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) throw();
  27437. /** Returns the standard name of a GM instrument.
  27438. @param midiInstrumentNumber the program number 0 to 127
  27439. @see getProgramChangeNumber
  27440. */
  27441. static const String getGMInstrumentName (int midiInstrumentNumber);
  27442. /** Returns the name of a bank of GM instruments.
  27443. @param midiBankNumber the bank, 0 to 15
  27444. */
  27445. static const String getGMInstrumentBankName (int midiBankNumber);
  27446. /** Returns the standard name of a channel 10 percussion sound.
  27447. @param midiNoteNumber the key number, 35 to 81
  27448. */
  27449. static const String getRhythmInstrumentName (int midiNoteNumber);
  27450. /** Returns the name of a controller type number.
  27451. @see getControllerNumber
  27452. */
  27453. static const String getControllerName (int controllerNumber);
  27454. private:
  27455. double timeStamp;
  27456. uint8* data;
  27457. int size;
  27458. #ifndef DOXYGEN
  27459. union
  27460. {
  27461. uint8 asBytes[4];
  27462. uint32 asInt32;
  27463. } preallocatedData;
  27464. #endif
  27465. };
  27466. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  27467. /*** End of inlined file: juce_MidiMessage.h ***/
  27468. class MidiInput;
  27469. /**
  27470. Receives midi messages from a midi input device.
  27471. This class is overridden to handle incoming midi messages. See the MidiInput
  27472. class for more details.
  27473. @see MidiInput
  27474. */
  27475. class JUCE_API MidiInputCallback
  27476. {
  27477. public:
  27478. /** Destructor. */
  27479. virtual ~MidiInputCallback() {}
  27480. /** Receives an incoming message.
  27481. A MidiInput object will call this method when a midi event arrives. It'll be
  27482. called on a high-priority system thread, so avoid doing anything time-consuming
  27483. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  27484. for queueing incoming messages for use later.
  27485. @param source the MidiInput object that generated the message
  27486. @param message the incoming message. The message's timestamp is set to a value
  27487. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  27488. time when the message arrived.
  27489. */
  27490. virtual void handleIncomingMidiMessage (MidiInput* source,
  27491. const MidiMessage& message) = 0;
  27492. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  27493. If a long sysex message is broken up into multiple packets, this callback is made
  27494. for each packet that arrives until the message is finished, at which point
  27495. the normal handleIncomingMidiMessage() callback will be made with the entire
  27496. message.
  27497. The message passed in will contain the start of a sysex, but won't be finished
  27498. with the terminating 0xf7 byte.
  27499. */
  27500. virtual void handlePartialSysexMessage (MidiInput* source,
  27501. const uint8* messageData,
  27502. const int numBytesSoFar,
  27503. const double timestamp)
  27504. {
  27505. // (this bit is just to avoid compiler warnings about unused variables)
  27506. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  27507. }
  27508. };
  27509. /**
  27510. Represents a midi input device.
  27511. To create one of these, use the static getDevices() method to find out what inputs are
  27512. available, and then use the openDevice() method to try to open one.
  27513. @see MidiOutput
  27514. */
  27515. class JUCE_API MidiInput
  27516. {
  27517. public:
  27518. /** Returns a list of the available midi input devices.
  27519. You can open one of the devices by passing its index into the
  27520. openDevice() method.
  27521. @see getDefaultDeviceIndex, openDevice
  27522. */
  27523. static const StringArray getDevices();
  27524. /** Returns the index of the default midi input device to use.
  27525. This refers to the index in the list returned by getDevices().
  27526. */
  27527. static int getDefaultDeviceIndex();
  27528. /** Tries to open one of the midi input devices.
  27529. This will return a MidiInput object if it manages to open it. You can then
  27530. call start() and stop() on this device, and delete it when no longer needed.
  27531. If the device can't be opened, this will return a null pointer.
  27532. @param deviceIndex the index of a device from the list returned by getDevices()
  27533. @param callback the object that will receive the midi messages from this device.
  27534. @see MidiInputCallback, getDevices
  27535. */
  27536. static MidiInput* openDevice (int deviceIndex,
  27537. MidiInputCallback* callback);
  27538. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  27539. /** This will try to create a new midi input device (Not available on Windows).
  27540. This will attempt to create a new midi input device with the specified name,
  27541. for other apps to connect to.
  27542. Returns 0 if a device can't be created.
  27543. @param deviceName the name to use for the new device
  27544. @param callback the object that will receive the midi messages from this device.
  27545. */
  27546. static MidiInput* createNewDevice (const String& deviceName,
  27547. MidiInputCallback* callback);
  27548. #endif
  27549. /** Destructor. */
  27550. virtual ~MidiInput();
  27551. /** Returns the name of this device.
  27552. */
  27553. virtual const String getName() const throw() { return name; }
  27554. /** Allows you to set a custom name for the device, in case you don't like the name
  27555. it was given when created.
  27556. */
  27557. virtual void setName (const String& newName) throw() { name = newName; }
  27558. /** Starts the device running.
  27559. After calling this, the device will start sending midi messages to the
  27560. MidiInputCallback object that was specified when the openDevice() method
  27561. was called.
  27562. @see stop
  27563. */
  27564. virtual void start();
  27565. /** Stops the device running.
  27566. @see start
  27567. */
  27568. virtual void stop();
  27569. protected:
  27570. String name;
  27571. void* internal;
  27572. explicit MidiInput (const String& name);
  27573. private:
  27574. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  27575. };
  27576. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  27577. /*** End of inlined file: juce_MidiInput.h ***/
  27578. /*** Start of inlined file: juce_MidiOutput.h ***/
  27579. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  27580. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  27581. /*** Start of inlined file: juce_MidiBuffer.h ***/
  27582. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  27583. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  27584. /**
  27585. Holds a sequence of time-stamped midi events.
  27586. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  27587. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  27588. @see MidiMessage
  27589. */
  27590. class JUCE_API MidiBuffer
  27591. {
  27592. public:
  27593. /** Creates an empty MidiBuffer. */
  27594. MidiBuffer() throw();
  27595. /** Creates a MidiBuffer containing a single midi message. */
  27596. explicit MidiBuffer (const MidiMessage& message) throw();
  27597. /** Creates a copy of another MidiBuffer. */
  27598. MidiBuffer (const MidiBuffer& other) throw();
  27599. /** Makes a copy of another MidiBuffer. */
  27600. MidiBuffer& operator= (const MidiBuffer& other) throw();
  27601. /** Destructor */
  27602. ~MidiBuffer();
  27603. /** Removes all events from the buffer. */
  27604. void clear() throw();
  27605. /** Removes all events between two times from the buffer.
  27606. All events for which (start <= event position < start + numSamples) will
  27607. be removed.
  27608. */
  27609. void clear (int start, int numSamples);
  27610. /** Returns true if the buffer is empty.
  27611. To actually retrieve the events, use a MidiBuffer::Iterator object
  27612. */
  27613. bool isEmpty() const throw();
  27614. /** Counts the number of events in the buffer.
  27615. This is actually quite a slow operation, as it has to iterate through all
  27616. the events, so you might prefer to call isEmpty() if that's all you need
  27617. to know.
  27618. */
  27619. int getNumEvents() const throw();
  27620. /** Adds an event to the buffer.
  27621. The sample number will be used to determine the position of the event in
  27622. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  27623. ignored.
  27624. If an event is added whose sample position is the same as one or more events
  27625. already in the buffer, the new event will be placed after the existing ones.
  27626. To retrieve events, use a MidiBuffer::Iterator object
  27627. */
  27628. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  27629. /** Adds an event to the buffer from raw midi data.
  27630. The sample number will be used to determine the position of the event in
  27631. the buffer, which is always kept sorted.
  27632. If an event is added whose sample position is the same as one or more events
  27633. already in the buffer, the new event will be placed after the existing ones.
  27634. The event data will be inspected to calculate the number of bytes in length that
  27635. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  27636. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  27637. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  27638. add an event at all.
  27639. To retrieve events, use a MidiBuffer::Iterator object
  27640. */
  27641. void addEvent (const void* rawMidiData,
  27642. int maxBytesOfMidiData,
  27643. int sampleNumber);
  27644. /** Adds some events from another buffer to this one.
  27645. @param otherBuffer the buffer containing the events you want to add
  27646. @param startSample the lowest sample number in the source buffer for which
  27647. events should be added. Any source events whose timestamp is
  27648. less than this will be ignored
  27649. @param numSamples the valid range of samples from the source buffer for which
  27650. events should be added - i.e. events in the source buffer whose
  27651. timestamp is greater than or equal to (startSample + numSamples)
  27652. will be ignored. If this value is less than 0, all events after
  27653. startSample will be taken.
  27654. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  27655. that are added to this buffer
  27656. */
  27657. void addEvents (const MidiBuffer& otherBuffer,
  27658. int startSample,
  27659. int numSamples,
  27660. int sampleDeltaToAdd);
  27661. /** Returns the sample number of the first event in the buffer.
  27662. If the buffer's empty, this will just return 0.
  27663. */
  27664. int getFirstEventTime() const throw();
  27665. /** Returns the sample number of the last event in the buffer.
  27666. If the buffer's empty, this will just return 0.
  27667. */
  27668. int getLastEventTime() const throw();
  27669. /** Exchanges the contents of this buffer with another one.
  27670. This is a quick operation, because no memory allocating or copying is done, it
  27671. just swaps the internal state of the two buffers.
  27672. */
  27673. void swapWith (MidiBuffer& other) throw();
  27674. /** Preallocates some memory for the buffer to use.
  27675. This helps to avoid needing to reallocate space when the buffer has messages
  27676. added to it.
  27677. */
  27678. void ensureSize (size_t minimumNumBytes);
  27679. /**
  27680. Used to iterate through the events in a MidiBuffer.
  27681. Note that altering the buffer while an iterator is using it isn't a
  27682. safe operation.
  27683. @see MidiBuffer
  27684. */
  27685. class Iterator
  27686. {
  27687. public:
  27688. /** Creates an Iterator for this MidiBuffer. */
  27689. Iterator (const MidiBuffer& buffer) throw();
  27690. /** Destructor. */
  27691. ~Iterator() throw();
  27692. /** Repositions the iterator so that the next event retrieved will be the first
  27693. one whose sample position is at greater than or equal to the given position.
  27694. */
  27695. void setNextSamplePosition (int samplePosition) throw();
  27696. /** Retrieves a copy of the next event from the buffer.
  27697. @param result on return, this will be the message (the MidiMessage's timestamp
  27698. is not set)
  27699. @param samplePosition on return, this will be the position of the event
  27700. @returns true if an event was found, or false if the iterator has reached
  27701. the end of the buffer
  27702. */
  27703. bool getNextEvent (MidiMessage& result,
  27704. int& samplePosition) throw();
  27705. /** Retrieves the next event from the buffer.
  27706. @param midiData on return, this pointer will be set to a block of data containing
  27707. the midi message. Note that to make it fast, this is a pointer
  27708. directly into the MidiBuffer's internal data, so is only valid
  27709. temporarily until the MidiBuffer is altered.
  27710. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  27711. midi message
  27712. @param samplePosition on return, this will be the position of the event
  27713. @returns true if an event was found, or false if the iterator has reached
  27714. the end of the buffer
  27715. */
  27716. bool getNextEvent (const uint8* &midiData,
  27717. int& numBytesOfMidiData,
  27718. int& samplePosition) throw();
  27719. private:
  27720. const MidiBuffer& buffer;
  27721. const uint8* data;
  27722. JUCE_DECLARE_NON_COPYABLE (Iterator);
  27723. };
  27724. private:
  27725. friend class MidiBuffer::Iterator;
  27726. MemoryBlock data;
  27727. int bytesUsed;
  27728. uint8* getData() const throw();
  27729. uint8* findEventAfter (uint8* d, int samplePosition) const throw();
  27730. static int getEventTime (const void* d) throw();
  27731. static uint16 getEventDataSize (const void* d) throw();
  27732. static uint16 getEventTotalSize (const void* d) throw();
  27733. JUCE_LEAK_DETECTOR (MidiBuffer);
  27734. };
  27735. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  27736. /*** End of inlined file: juce_MidiBuffer.h ***/
  27737. /**
  27738. Represents a midi output device.
  27739. To create one of these, use the static getDevices() method to find out what
  27740. outputs are available, then use the openDevice() method to try to open one.
  27741. @see MidiInput
  27742. */
  27743. class JUCE_API MidiOutput : private Thread
  27744. {
  27745. public:
  27746. /** Returns a list of the available midi output devices.
  27747. You can open one of the devices by passing its index into the
  27748. openDevice() method.
  27749. @see getDefaultDeviceIndex, openDevice
  27750. */
  27751. static const StringArray getDevices();
  27752. /** Returns the index of the default midi output device to use.
  27753. This refers to the index in the list returned by getDevices().
  27754. */
  27755. static int getDefaultDeviceIndex();
  27756. /** Tries to open one of the midi output devices.
  27757. This will return a MidiOutput object if it manages to open it. You can then
  27758. send messages to this device, and delete it when no longer needed.
  27759. If the device can't be opened, this will return a null pointer.
  27760. @param deviceIndex the index of a device from the list returned by getDevices()
  27761. @see getDevices
  27762. */
  27763. static MidiOutput* openDevice (int deviceIndex);
  27764. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  27765. /** This will try to create a new midi output device (Not available on Windows).
  27766. This will attempt to create a new midi output device that other apps can connect
  27767. to and use as their midi input.
  27768. Returns 0 if a device can't be created.
  27769. @param deviceName the name to use for the new device
  27770. */
  27771. static MidiOutput* createNewDevice (const String& deviceName);
  27772. #endif
  27773. /** Destructor. */
  27774. virtual ~MidiOutput();
  27775. /** Makes this device output a midi message.
  27776. @see MidiMessage
  27777. */
  27778. virtual void sendMessageNow (const MidiMessage& message);
  27779. /** Sends a midi reset to the device. */
  27780. virtual void reset();
  27781. /** Returns the current volume setting for this device. */
  27782. virtual bool getVolume (float& leftVol,
  27783. float& rightVol);
  27784. /** Changes the overall volume for this device. */
  27785. virtual void setVolume (float leftVol,
  27786. float rightVol);
  27787. /** This lets you supply a block of messages that will be sent out at some point
  27788. in the future.
  27789. The MidiOutput class has an internal thread that can send out timestamped
  27790. messages - this appends a set of messages to its internal buffer, ready for
  27791. sending.
  27792. This will only work if you've already started the thread with startBackgroundThread().
  27793. A time is supplied, at which the block of messages should be sent. This time uses
  27794. the same time base as Time::getMillisecondCounter(), and must be in the future.
  27795. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  27796. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  27797. samplesPerSecondForBuffer value is needed to convert this sample position to a
  27798. real time.
  27799. */
  27800. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  27801. double millisecondCounterToStartAt,
  27802. double samplesPerSecondForBuffer);
  27803. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  27804. */
  27805. virtual void clearAllPendingMessages();
  27806. /** Starts up a background thread so that the device can send blocks of data.
  27807. Call this to get the device ready, before using sendBlockOfMessages().
  27808. */
  27809. virtual void startBackgroundThread();
  27810. /** Stops the background thread, and clears any pending midi events.
  27811. @see startBackgroundThread
  27812. */
  27813. virtual void stopBackgroundThread();
  27814. protected:
  27815. void* internal;
  27816. struct PendingMessage
  27817. {
  27818. PendingMessage (const uint8* data, int len, double sampleNumber);
  27819. MidiMessage message;
  27820. PendingMessage* next;
  27821. };
  27822. CriticalSection lock;
  27823. PendingMessage* firstMessage;
  27824. MidiOutput();
  27825. void run();
  27826. private:
  27827. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  27828. };
  27829. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  27830. /*** End of inlined file: juce_MidiOutput.h ***/
  27831. /*** Start of inlined file: juce_ComboBox.h ***/
  27832. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  27833. #define __JUCE_COMBOBOX_JUCEHEADER__
  27834. /*** Start of inlined file: juce_Label.h ***/
  27835. #ifndef __JUCE_LABEL_JUCEHEADER__
  27836. #define __JUCE_LABEL_JUCEHEADER__
  27837. /*** Start of inlined file: juce_TextEditor.h ***/
  27838. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  27839. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  27840. /*** Start of inlined file: juce_Viewport.h ***/
  27841. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  27842. #define __JUCE_VIEWPORT_JUCEHEADER__
  27843. /*** Start of inlined file: juce_ScrollBar.h ***/
  27844. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  27845. #define __JUCE_SCROLLBAR_JUCEHEADER__
  27846. /*** Start of inlined file: juce_Button.h ***/
  27847. #ifndef __JUCE_BUTTON_JUCEHEADER__
  27848. #define __JUCE_BUTTON_JUCEHEADER__
  27849. /*** Start of inlined file: juce_TooltipWindow.h ***/
  27850. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  27851. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  27852. /*** Start of inlined file: juce_TooltipClient.h ***/
  27853. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  27854. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  27855. /**
  27856. Components that want to use pop-up tooltips should implement this interface.
  27857. A TooltipWindow will wait for the mouse to hover over a component that
  27858. implements the TooltipClient interface, and when it finds one, it will display
  27859. the tooltip returned by its getTooltip() method.
  27860. @see TooltipWindow, SettableTooltipClient
  27861. */
  27862. class JUCE_API TooltipClient
  27863. {
  27864. public:
  27865. /** Destructor. */
  27866. virtual ~TooltipClient() {}
  27867. /** Returns the string that this object wants to show as its tooltip. */
  27868. virtual const String getTooltip() = 0;
  27869. };
  27870. /**
  27871. An implementation of TooltipClient that stores the tooltip string and a method
  27872. for changing it.
  27873. This makes it easy to add a tooltip to a custom component, by simply adding this
  27874. as a base class and calling setTooltip().
  27875. Many of the Juce widgets already use this as a base class to implement their
  27876. tooltips.
  27877. @see TooltipClient, TooltipWindow
  27878. */
  27879. class JUCE_API SettableTooltipClient : public TooltipClient
  27880. {
  27881. public:
  27882. /** Destructor. */
  27883. virtual ~SettableTooltipClient() {}
  27884. /** Assigns a new tooltip to this object. */
  27885. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  27886. /** Returns the tooltip assigned to this object. */
  27887. virtual const String getTooltip() { return tooltipString; }
  27888. protected:
  27889. SettableTooltipClient() {}
  27890. private:
  27891. String tooltipString;
  27892. };
  27893. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  27894. /*** End of inlined file: juce_TooltipClient.h ***/
  27895. /**
  27896. A window that displays a pop-up tooltip when the mouse hovers over another component.
  27897. To enable tooltips in your app, just create a single instance of a TooltipWindow
  27898. object.
  27899. The TooltipWindow object will then stay invisible, waiting until the mouse
  27900. hovers for the specified length of time - it will then see if it's currently
  27901. over a component which implements the TooltipClient interface, and if so,
  27902. it will make itself visible to show the tooltip in the appropriate place.
  27903. @see TooltipClient, SettableTooltipClient
  27904. */
  27905. class JUCE_API TooltipWindow : public Component,
  27906. private Timer
  27907. {
  27908. public:
  27909. /** Creates a tooltip window.
  27910. Make sure your app only creates one instance of this class, otherwise you'll
  27911. get multiple overlaid tooltips appearing. The window will initially be invisible
  27912. and will make itself visible when it needs to display a tip.
  27913. To change the style of tooltips, see the LookAndFeel class for its tooltip
  27914. methods.
  27915. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  27916. otherwise the tooltip will be added to the given parent
  27917. component.
  27918. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  27919. before a tooltip will be shown
  27920. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  27921. */
  27922. explicit TooltipWindow (Component* parentComponent = 0,
  27923. int millisecondsBeforeTipAppears = 700);
  27924. /** Destructor. */
  27925. ~TooltipWindow();
  27926. /** Changes the time before the tip appears.
  27927. This lets you change the value that was set in the constructor.
  27928. */
  27929. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  27930. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  27931. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27932. methods.
  27933. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27934. */
  27935. enum ColourIds
  27936. {
  27937. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  27938. textColourId = 0x1001c00, /**< The colour to use for the text. */
  27939. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  27940. };
  27941. private:
  27942. int millisecondsBeforeTipAppears;
  27943. Point<int> lastMousePos;
  27944. int mouseClicks;
  27945. unsigned int lastCompChangeTime, lastHideTime;
  27946. Component* lastComponentUnderMouse;
  27947. bool changedCompsSinceShown;
  27948. String tipShowing, lastTipUnderMouse;
  27949. void paint (Graphics& g);
  27950. void mouseEnter (const MouseEvent& e);
  27951. void timerCallback();
  27952. static const String getTipFor (Component* c);
  27953. void showFor (const String& tip);
  27954. void hide();
  27955. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  27956. };
  27957. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  27958. /*** End of inlined file: juce_TooltipWindow.h ***/
  27959. #if JUCE_VC6
  27960. #define Listener ButtonListener
  27961. #endif
  27962. /**
  27963. A base class for buttons.
  27964. This contains all the logic for button behaviours such as enabling/disabling,
  27965. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  27966. and radio groups, etc.
  27967. @see TextButton, DrawableButton, ToggleButton
  27968. */
  27969. class JUCE_API Button : public Component,
  27970. public SettableTooltipClient,
  27971. public ApplicationCommandManagerListener,
  27972. public ValueListener,
  27973. private KeyListener
  27974. {
  27975. protected:
  27976. /** Creates a button.
  27977. @param buttonName the text to put in the button (the component's name is also
  27978. initially set to this string, but these can be changed later
  27979. using the setName() and setButtonText() methods)
  27980. */
  27981. explicit Button (const String& buttonName);
  27982. public:
  27983. /** Destructor. */
  27984. virtual ~Button();
  27985. /** Changes the button's text.
  27986. @see getButtonText
  27987. */
  27988. void setButtonText (const String& newText);
  27989. /** Returns the text displayed in the button.
  27990. @see setButtonText
  27991. */
  27992. const String getButtonText() const { return text; }
  27993. /** Returns true if the button is currently being held down by the mouse.
  27994. @see isOver
  27995. */
  27996. bool isDown() const throw();
  27997. /** Returns true if the mouse is currently over the button.
  27998. This will be also be true if the mouse is being held down.
  27999. @see isDown
  28000. */
  28001. bool isOver() const throw();
  28002. /** A button has an on/off state associated with it, and this changes that.
  28003. By default buttons are 'off' and for simple buttons that you click to perform
  28004. an action you won't change this. Toggle buttons, however will want to
  28005. change their state when turned on or off.
  28006. @param shouldBeOn whether to set the button's toggle state to be on or
  28007. off. If it's a member of a button group, this will
  28008. always try to turn it on, and to turn off any other
  28009. buttons in the group
  28010. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  28011. the button will be repainted but no notification will
  28012. be sent
  28013. @see getToggleState, setRadioGroupId
  28014. */
  28015. void setToggleState (bool shouldBeOn,
  28016. bool sendChangeNotification);
  28017. /** Returns true if the button in 'on'.
  28018. By default buttons are 'off' and for simple buttons that you click to perform
  28019. an action you won't change this. Toggle buttons, however will want to
  28020. change their state when turned on or off.
  28021. @see setToggleState
  28022. */
  28023. bool getToggleState() const throw() { return isOn.getValue(); }
  28024. /** Returns the Value object that represents the botton's toggle state.
  28025. You can use this Value object to connect the button's state to external values or setters,
  28026. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  28027. your own Value object.
  28028. @see getToggleState, Value
  28029. */
  28030. Value& getToggleStateValue() { return isOn; }
  28031. /** This tells the button to automatically flip the toggle state when
  28032. the button is clicked.
  28033. If set to true, then before the clicked() callback occurs, the toggle-state
  28034. of the button is flipped.
  28035. */
  28036. void setClickingTogglesState (bool shouldToggle) throw();
  28037. /** Returns true if this button is set to be an automatic toggle-button.
  28038. This returns the last value that was passed to setClickingTogglesState().
  28039. */
  28040. bool getClickingTogglesState() const throw();
  28041. /** Enables the button to act as a member of a mutually-exclusive group
  28042. of 'radio buttons'.
  28043. If the group ID is set to a non-zero number, then this button will
  28044. act as part of a group of buttons with the same ID, only one of
  28045. which can be 'on' at the same time. Note that when it's part of
  28046. a group, clicking a toggle-button that's 'on' won't turn it off.
  28047. To find other buttons with the same ID, this button will search through
  28048. its sibling components for ToggleButtons, so all the buttons for a
  28049. particular group must be placed inside the same parent component.
  28050. Set the group ID back to zero if you want it to act as a normal toggle
  28051. button again.
  28052. @see getRadioGroupId
  28053. */
  28054. void setRadioGroupId (int newGroupId);
  28055. /** Returns the ID of the group to which this button belongs.
  28056. (See setRadioGroupId() for an explanation of this).
  28057. */
  28058. int getRadioGroupId() const throw() { return radioGroupId; }
  28059. /**
  28060. Used to receive callbacks when a button is clicked.
  28061. @see Button::addListener, Button::removeListener
  28062. */
  28063. class JUCE_API Listener
  28064. {
  28065. public:
  28066. /** Destructor. */
  28067. virtual ~Listener() {}
  28068. /** Called when the button is clicked. */
  28069. virtual void buttonClicked (Button* button) = 0;
  28070. /** Called when the button's state changes. */
  28071. virtual void buttonStateChanged (Button*) {}
  28072. };
  28073. /** Registers a listener to receive events when this button's state changes.
  28074. If the listener is already registered, this will not register it again.
  28075. @see removeListener
  28076. */
  28077. void addListener (Listener* newListener);
  28078. /** Removes a previously-registered button listener
  28079. @see addListener
  28080. */
  28081. void removeListener (Listener* listener);
  28082. /** Causes the button to act as if it's been clicked.
  28083. This will asynchronously make the button draw itself going down and up, and
  28084. will then call back the clicked() method as if mouse was clicked on it.
  28085. @see clicked
  28086. */
  28087. virtual void triggerClick();
  28088. /** Sets a command ID for this button to automatically invoke when it's clicked.
  28089. When the button is pressed, it will use the given manager to trigger the
  28090. command ID.
  28091. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  28092. before this button is. To disable the command triggering, call this method and
  28093. pass 0 for the parameters.
  28094. If generateTooltip is true, then the button's tooltip will be automatically
  28095. generated based on the name of this command and its current shortcut key.
  28096. @see addShortcut, getCommandID
  28097. */
  28098. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  28099. int commandID,
  28100. bool generateTooltip);
  28101. /** Returns the command ID that was set by setCommandToTrigger().
  28102. */
  28103. int getCommandID() const throw() { return commandID; }
  28104. /** Assigns a shortcut key to trigger the button.
  28105. The button registers itself with its top-level parent component for keypresses.
  28106. Note that a different way of linking buttons to keypresses is by using the
  28107. setCommandToTrigger() method to invoke a command.
  28108. @see clearShortcuts
  28109. */
  28110. void addShortcut (const KeyPress& key);
  28111. /** Removes all key shortcuts that had been set for this button.
  28112. @see addShortcut
  28113. */
  28114. void clearShortcuts();
  28115. /** Returns true if the given keypress is a shortcut for this button.
  28116. @see addShortcut
  28117. */
  28118. bool isRegisteredForShortcut (const KeyPress& key) const;
  28119. /** Sets an auto-repeat speed for the button when it is held down.
  28120. (Auto-repeat is disabled by default).
  28121. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  28122. triggering the next click. If this is zero, auto-repeat
  28123. is disabled
  28124. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  28125. triggered
  28126. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  28127. get faster, the longer the button is held down, up to the
  28128. minimum interval specified here
  28129. */
  28130. void setRepeatSpeed (int initialDelayInMillisecs,
  28131. int repeatDelayInMillisecs,
  28132. int minimumDelayInMillisecs = -1) throw();
  28133. /** Sets whether the button click should happen when the mouse is pressed or released.
  28134. By default the button is only considered to have been clicked when the mouse is
  28135. released, but setting this to true will make it call the clicked() method as soon
  28136. as the button is pressed.
  28137. This is useful if the button is being used to show a pop-up menu, as it allows
  28138. the click to be used as a drag onto the menu.
  28139. */
  28140. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  28141. /** Returns the number of milliseconds since the last time the button
  28142. went into the 'down' state.
  28143. */
  28144. uint32 getMillisecondsSinceButtonDown() const throw();
  28145. /** Sets the tooltip for this button.
  28146. @see TooltipClient, TooltipWindow
  28147. */
  28148. void setTooltip (const String& newTooltip);
  28149. // (implementation of the TooltipClient method)
  28150. const String getTooltip();
  28151. /** A combination of these flags are used by setConnectedEdges().
  28152. */
  28153. enum ConnectedEdgeFlags
  28154. {
  28155. ConnectedOnLeft = 1,
  28156. ConnectedOnRight = 2,
  28157. ConnectedOnTop = 4,
  28158. ConnectedOnBottom = 8
  28159. };
  28160. /** Hints about which edges of the button might be connected to adjoining buttons.
  28161. The value passed in is a bitwise combination of any of the values in the
  28162. ConnectedEdgeFlags enum.
  28163. E.g. if you are placing two buttons adjacent to each other, you could use this to
  28164. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  28165. without rounded corners on the edges that connect. It's only a hint, so the
  28166. LookAndFeel can choose to ignore it if it's not relevent for this type of
  28167. button.
  28168. */
  28169. void setConnectedEdges (int connectedEdgeFlags);
  28170. /** Returns the set of flags passed into setConnectedEdges(). */
  28171. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  28172. /** Indicates whether the button adjoins another one on its left edge.
  28173. @see setConnectedEdges
  28174. */
  28175. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  28176. /** Indicates whether the button adjoins another one on its right edge.
  28177. @see setConnectedEdges
  28178. */
  28179. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  28180. /** Indicates whether the button adjoins another one on its top edge.
  28181. @see setConnectedEdges
  28182. */
  28183. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  28184. /** Indicates whether the button adjoins another one on its bottom edge.
  28185. @see setConnectedEdges
  28186. */
  28187. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  28188. /** Used by setState(). */
  28189. enum ButtonState
  28190. {
  28191. buttonNormal,
  28192. buttonOver,
  28193. buttonDown
  28194. };
  28195. /** Can be used to force the button into a particular state.
  28196. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  28197. from happening.
  28198. The state that you set here will only last until it is automatically changed when the mouse
  28199. enters or exits the button, or the mouse-button is pressed or released.
  28200. */
  28201. void setState (const ButtonState newState);
  28202. // These are deprecated - please use addListener() and removeListener() instead!
  28203. JUCE_DEPRECATED (void addButtonListener (Listener*));
  28204. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  28205. protected:
  28206. /** This method is called when the button has been clicked.
  28207. Subclasses can override this to perform whatever they actions they need
  28208. to do.
  28209. Alternatively, a ButtonListener can be added to the button, and these listeners
  28210. will be called when the click occurs.
  28211. @see triggerClick
  28212. */
  28213. virtual void clicked();
  28214. /** This method is called when the button has been clicked.
  28215. By default it just calls clicked(), but you might want to override it to handle
  28216. things like clicking when a modifier key is pressed, etc.
  28217. @see ModifierKeys
  28218. */
  28219. virtual void clicked (const ModifierKeys& modifiers);
  28220. /** Subclasses should override this to actually paint the button's contents.
  28221. It's better to use this than the paint method, because it gives you information
  28222. about the over/down state of the button.
  28223. @param g the graphics context to use
  28224. @param isMouseOverButton true if the button is either in the 'over' or
  28225. 'down' state
  28226. @param isButtonDown true if the button should be drawn in the 'down' position
  28227. */
  28228. virtual void paintButton (Graphics& g,
  28229. bool isMouseOverButton,
  28230. bool isButtonDown) = 0;
  28231. /** Called when the button's up/down/over state changes.
  28232. Subclasses can override this if they need to do something special when the button
  28233. goes up or down.
  28234. @see isDown, isOver
  28235. */
  28236. virtual void buttonStateChanged();
  28237. /** @internal */
  28238. virtual void internalClickCallback (const ModifierKeys& modifiers);
  28239. /** @internal */
  28240. void handleCommandMessage (int commandId);
  28241. /** @internal */
  28242. void mouseEnter (const MouseEvent& e);
  28243. /** @internal */
  28244. void mouseExit (const MouseEvent& e);
  28245. /** @internal */
  28246. void mouseDown (const MouseEvent& e);
  28247. /** @internal */
  28248. void mouseDrag (const MouseEvent& e);
  28249. /** @internal */
  28250. void mouseUp (const MouseEvent& e);
  28251. /** @internal */
  28252. bool keyPressed (const KeyPress& key);
  28253. /** @internal */
  28254. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  28255. /** @internal */
  28256. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  28257. /** @internal */
  28258. void paint (Graphics& g);
  28259. /** @internal */
  28260. void parentHierarchyChanged();
  28261. /** @internal */
  28262. void visibilityChanged();
  28263. /** @internal */
  28264. void focusGained (FocusChangeType cause);
  28265. /** @internal */
  28266. void focusLost (FocusChangeType cause);
  28267. /** @internal */
  28268. void enablementChanged();
  28269. /** @internal */
  28270. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  28271. /** @internal */
  28272. void applicationCommandListChanged();
  28273. /** @internal */
  28274. void valueChanged (Value& value);
  28275. private:
  28276. Array <KeyPress> shortcuts;
  28277. WeakReference<Component> keySource;
  28278. String text;
  28279. ListenerList <Listener> buttonListeners;
  28280. class RepeatTimer;
  28281. friend class RepeatTimer;
  28282. friend class ScopedPointer <RepeatTimer>;
  28283. ScopedPointer <RepeatTimer> repeatTimer;
  28284. uint32 buttonPressTime, lastRepeatTime;
  28285. ApplicationCommandManager* commandManagerToUse;
  28286. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  28287. int radioGroupId, commandID, connectedEdgeFlags;
  28288. ButtonState buttonState;
  28289. Value isOn;
  28290. bool lastToggleState : 1;
  28291. bool clickTogglesState : 1;
  28292. bool needsToRelease : 1;
  28293. bool needsRepainting : 1;
  28294. bool isKeyDown : 1;
  28295. bool triggerOnMouseDown : 1;
  28296. bool generateTooltip : 1;
  28297. void repeatTimerCallback();
  28298. RepeatTimer& getRepeatTimer();
  28299. ButtonState updateState();
  28300. ButtonState updateState (bool isOver, bool isDown);
  28301. bool isShortcutPressed() const;
  28302. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  28303. void flashButtonState();
  28304. void sendClickMessage (const ModifierKeys& modifiers);
  28305. void sendStateMessage();
  28306. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  28307. };
  28308. #ifndef DOXYGEN
  28309. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  28310. typedef Button::Listener ButtonListener;
  28311. #endif
  28312. #if JUCE_VC6
  28313. #undef Listener
  28314. #endif
  28315. #endif // __JUCE_BUTTON_JUCEHEADER__
  28316. /*** End of inlined file: juce_Button.h ***/
  28317. /**
  28318. A scrollbar component.
  28319. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  28320. sets the range of values it can represent. Then you can use setCurrentRange() to
  28321. change the position and size of the scrollbar's 'thumb'.
  28322. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  28323. the user moves it, and you can use the getCurrentRangeStart() to find out where
  28324. they moved it to.
  28325. The scrollbar will adjust its own visibility according to whether its thumb size
  28326. allows it to actually be scrolled.
  28327. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  28328. instead of handling a scrollbar directly.
  28329. @see ScrollBar::Listener
  28330. */
  28331. class JUCE_API ScrollBar : public Component,
  28332. public AsyncUpdater,
  28333. private Timer
  28334. {
  28335. public:
  28336. /** Creates a Scrollbar.
  28337. @param isVertical whether it should be a vertical or horizontal bar
  28338. @param buttonsAreVisible whether to show the up/down or left/right buttons
  28339. */
  28340. ScrollBar (bool isVertical,
  28341. bool buttonsAreVisible = true);
  28342. /** Destructor. */
  28343. ~ScrollBar();
  28344. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  28345. bool isVertical() const throw() { return vertical; }
  28346. /** Changes the scrollbar's direction.
  28347. You'll also need to resize the bar appropriately - this just changes its internal
  28348. layout.
  28349. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  28350. */
  28351. void setOrientation (bool shouldBeVertical);
  28352. /** Shows or hides the scrollbar's buttons. */
  28353. void setButtonVisibility (bool buttonsAreVisible);
  28354. /** Tells the scrollbar whether to make itself invisible when not needed.
  28355. The default behaviour is for a scrollbar to become invisible when the thumb
  28356. fills the whole of its range (i.e. when it can't be moved). Setting this
  28357. value to false forces the bar to always be visible.
  28358. @see autoHides()
  28359. */
  28360. void setAutoHide (bool shouldHideWhenFullRange);
  28361. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  28362. as its maximum range.
  28363. @see setAutoHide
  28364. */
  28365. bool autoHides() const throw();
  28366. /** Sets the minimum and maximum values that the bar will move between.
  28367. The bar's thumb will always be constrained so that the entire thumb lies
  28368. within this range.
  28369. @see setCurrentRange
  28370. */
  28371. void setRangeLimits (const Range<double>& newRangeLimit);
  28372. /** Sets the minimum and maximum values that the bar will move between.
  28373. The bar's thumb will always be constrained so that the entire thumb lies
  28374. within this range.
  28375. @see setCurrentRange
  28376. */
  28377. void setRangeLimits (double minimum, double maximum);
  28378. /** Returns the current limits on the thumb position.
  28379. @see setRangeLimits
  28380. */
  28381. const Range<double> getRangeLimit() const throw() { return totalRange; }
  28382. /** Returns the lower value that the thumb can be set to.
  28383. This is the value set by setRangeLimits().
  28384. */
  28385. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  28386. /** Returns the upper value that the thumb can be set to.
  28387. This is the value set by setRangeLimits().
  28388. */
  28389. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  28390. /** Changes the position of the scrollbar's 'thumb'.
  28391. If this method call actually changes the scrollbar's position, it will trigger an
  28392. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  28393. are registered.
  28394. @see getCurrentRange. setCurrentRangeStart
  28395. */
  28396. void setCurrentRange (const Range<double>& newRange);
  28397. /** Changes the position of the scrollbar's 'thumb'.
  28398. This sets both the position and size of the thumb - to just set the position without
  28399. changing the size, you can use setCurrentRangeStart().
  28400. If this method call actually changes the scrollbar's position, it will trigger an
  28401. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  28402. are registered.
  28403. @param newStart the top (or left) of the thumb, in the range
  28404. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  28405. value is beyond these limits, it will be clipped.
  28406. @param newSize the size of the thumb, such that
  28407. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  28408. size is beyond these limits, it will be clipped.
  28409. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  28410. */
  28411. void setCurrentRange (double newStart, double newSize);
  28412. /** Moves the bar's thumb position.
  28413. This will move the thumb position without changing the thumb size. Note
  28414. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  28415. If this method call actually changes the scrollbar's position, it will trigger an
  28416. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  28417. are registered.
  28418. @see setCurrentRange
  28419. */
  28420. void setCurrentRangeStart (double newStart);
  28421. /** Returns the current thumb range.
  28422. @see getCurrentRange, setCurrentRange
  28423. */
  28424. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  28425. /** Returns the position of the top of the thumb.
  28426. @see getCurrentRange, setCurrentRangeStart
  28427. */
  28428. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  28429. /** Returns the current size of the thumb.
  28430. @see getCurrentRange, setCurrentRange
  28431. */
  28432. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  28433. /** Sets the amount by which the up and down buttons will move the bar.
  28434. The value here is in terms of the total range, and is added or subtracted
  28435. from the thumb position when the user clicks an up/down (or left/right) button.
  28436. */
  28437. void setSingleStepSize (double newSingleStepSize);
  28438. /** Moves the scrollbar by a number of single-steps.
  28439. This will move the bar by a multiple of its single-step interval (as
  28440. specified using the setSingleStepSize() method).
  28441. A positive value here will move the bar down or to the right, a negative
  28442. value moves it up or to the left.
  28443. */
  28444. void moveScrollbarInSteps (int howManySteps);
  28445. /** Moves the scroll bar up or down in pages.
  28446. This will move the bar by a multiple of its current thumb size, effectively
  28447. doing a page-up or down.
  28448. A positive value here will move the bar down or to the right, a negative
  28449. value moves it up or to the left.
  28450. */
  28451. void moveScrollbarInPages (int howManyPages);
  28452. /** Scrolls to the top (or left).
  28453. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  28454. */
  28455. void scrollToTop();
  28456. /** Scrolls to the bottom (or right).
  28457. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  28458. */
  28459. void scrollToBottom();
  28460. /** Changes the delay before the up and down buttons autorepeat when they are held
  28461. down.
  28462. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  28463. @see Button::setRepeatSpeed
  28464. */
  28465. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  28466. int repeatDelayInMillisecs,
  28467. int minimumDelayInMillisecs = -1);
  28468. /** A set of colour IDs to use to change the colour of various aspects of the component.
  28469. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  28470. methods.
  28471. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  28472. */
  28473. enum ColourIds
  28474. {
  28475. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  28476. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  28477. 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. */
  28478. };
  28479. /**
  28480. A class for receiving events from a ScrollBar.
  28481. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  28482. method, and it will be called when the bar's position changes.
  28483. @see ScrollBar::addListener, ScrollBar::removeListener
  28484. */
  28485. class JUCE_API Listener
  28486. {
  28487. public:
  28488. /** Destructor. */
  28489. virtual ~Listener() {}
  28490. /** Called when a ScrollBar is moved.
  28491. @param scrollBarThatHasMoved the bar that has moved
  28492. @param newRangeStart the new range start of this bar
  28493. */
  28494. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  28495. double newRangeStart) = 0;
  28496. };
  28497. /** Registers a listener that will be called when the scrollbar is moved. */
  28498. void addListener (Listener* listener);
  28499. /** Deregisters a previously-registered listener. */
  28500. void removeListener (Listener* listener);
  28501. /** @internal */
  28502. bool keyPressed (const KeyPress& key);
  28503. /** @internal */
  28504. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  28505. /** @internal */
  28506. void lookAndFeelChanged();
  28507. /** @internal */
  28508. void handleAsyncUpdate();
  28509. /** @internal */
  28510. void mouseDown (const MouseEvent& e);
  28511. /** @internal */
  28512. void mouseDrag (const MouseEvent& e);
  28513. /** @internal */
  28514. void mouseUp (const MouseEvent& e);
  28515. /** @internal */
  28516. void paint (Graphics& g);
  28517. /** @internal */
  28518. void resized();
  28519. private:
  28520. Range <double> totalRange, visibleRange;
  28521. double singleStepSize, dragStartRange;
  28522. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  28523. int dragStartMousePos, lastMousePos;
  28524. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  28525. bool vertical, isDraggingThumb, autohides;
  28526. class ScrollbarButton;
  28527. friend class ScopedPointer<ScrollbarButton>;
  28528. ScopedPointer<ScrollbarButton> upButton, downButton;
  28529. ListenerList <Listener> listeners;
  28530. void updateThumbPosition();
  28531. void timerCallback();
  28532. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  28533. };
  28534. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  28535. typedef ScrollBar::Listener ScrollBarListener;
  28536. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  28537. /*** End of inlined file: juce_ScrollBar.h ***/
  28538. /**
  28539. A Viewport is used to contain a larger child component, and allows the child
  28540. to be automatically scrolled around.
  28541. To use a Viewport, just create one and set the component that goes inside it
  28542. using the setViewedComponent() method. When the child component changes size,
  28543. the Viewport will adjust its scrollbars accordingly.
  28544. A subclass of the viewport can be created which will receive calls to its
  28545. visibleAreaChanged() method when the subcomponent changes position or size.
  28546. */
  28547. class JUCE_API Viewport : public Component,
  28548. private ComponentListener,
  28549. private ScrollBar::Listener
  28550. {
  28551. public:
  28552. /** Creates a Viewport.
  28553. The viewport is initially empty - use the setViewedComponent() method to
  28554. add a child component for it to manage.
  28555. */
  28556. explicit Viewport (const String& componentName = String::empty);
  28557. /** Destructor. */
  28558. ~Viewport();
  28559. /** Sets the component that this viewport will contain and scroll around.
  28560. This will add the given component to this Viewport and position it at
  28561. (0, 0).
  28562. (Don't add or remove any child components directly using the normal
  28563. Component::addChildComponent() methods).
  28564. @param newViewedComponent the component to add to this viewport (this pointer
  28565. may be null). The component passed in will be deleted
  28566. by the Viewport when it's no longer needed
  28567. @see getViewedComponent
  28568. */
  28569. void setViewedComponent (Component* newViewedComponent);
  28570. /** Returns the component that's currently being used inside the Viewport.
  28571. @see setViewedComponent
  28572. */
  28573. Component* getViewedComponent() const throw() { return contentComp; }
  28574. /** Changes the position of the viewed component.
  28575. The inner component will be moved so that the pixel at the top left of
  28576. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  28577. within the inner component.
  28578. This will update the scrollbars and might cause a call to visibleAreaChanged().
  28579. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  28580. */
  28581. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  28582. /** Changes the position of the viewed component.
  28583. The inner component will be moved so that the pixel at the top left of
  28584. the viewport will be the pixel at the specified coordinates within the
  28585. inner component.
  28586. This will update the scrollbars and might cause a call to visibleAreaChanged().
  28587. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  28588. */
  28589. void setViewPosition (const Point<int>& newPosition);
  28590. /** Changes the view position as a proportion of the distance it can move.
  28591. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  28592. visible area in the top-left, and (1, 1) would put it as far down and
  28593. to the right as it's possible to go whilst keeping the child component
  28594. on-screen.
  28595. */
  28596. void setViewPositionProportionately (double proportionX, double proportionY);
  28597. /** If the specified position is at the edges of the viewport, this method scrolls
  28598. the viewport to bring that position nearer to the centre.
  28599. Call this if you're dragging an object inside a viewport and want to make it scroll
  28600. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  28601. useful when auto-scrolling.
  28602. @param mouseX the x position, relative to the Viewport's top-left
  28603. @param mouseY the y position, relative to the Viewport's top-left
  28604. @param distanceFromEdge specifies how close to an edge the position needs to be
  28605. before the viewport should scroll in that direction
  28606. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  28607. to scroll by.
  28608. @returns true if the viewport was scrolled
  28609. */
  28610. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  28611. /** Returns the position within the child component of the top-left of its visible area.
  28612. */
  28613. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  28614. /** Returns the position within the child component of the top-left of its visible area.
  28615. @see getViewWidth, setViewPosition
  28616. */
  28617. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  28618. /** Returns the position within the child component of the top-left of its visible area.
  28619. @see getViewHeight, setViewPosition
  28620. */
  28621. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  28622. /** Returns the width of the visible area of the child component.
  28623. This may be less than the width of this Viewport if there's a vertical scrollbar
  28624. or if the child component is itself smaller.
  28625. */
  28626. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  28627. /** Returns the height of the visible area of the child component.
  28628. This may be less than the height of this Viewport if there's a horizontal scrollbar
  28629. or if the child component is itself smaller.
  28630. */
  28631. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  28632. /** Returns the width available within this component for the contents.
  28633. This will be the width of the viewport component minus the width of a
  28634. vertical scrollbar (if visible).
  28635. */
  28636. int getMaximumVisibleWidth() const;
  28637. /** Returns the height available within this component for the contents.
  28638. This will be the height of the viewport component minus the space taken up
  28639. by a horizontal scrollbar (if visible).
  28640. */
  28641. int getMaximumVisibleHeight() const;
  28642. /** Callback method that is called when the visible area changes.
  28643. This will be called when the visible area is moved either be scrolling or
  28644. by calls to setViewPosition(), etc.
  28645. */
  28646. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  28647. /** Turns scrollbars on or off.
  28648. If set to false, the scrollbars won't ever appear. When true (the default)
  28649. they will appear only when needed.
  28650. */
  28651. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  28652. bool showHorizontalScrollbarIfNeeded);
  28653. /** True if the vertical scrollbar is enabled.
  28654. @see setScrollBarsShown
  28655. */
  28656. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  28657. /** True if the horizontal scrollbar is enabled.
  28658. @see setScrollBarsShown
  28659. */
  28660. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  28661. /** Changes the width of the scrollbars.
  28662. If this isn't specified, the default width from the LookAndFeel class will be used.
  28663. @see LookAndFeel::getDefaultScrollbarWidth
  28664. */
  28665. void setScrollBarThickness (int thickness);
  28666. /** Returns the thickness of the scrollbars.
  28667. @see setScrollBarThickness
  28668. */
  28669. int getScrollBarThickness() const;
  28670. /** Changes the distance that a single-step click on a scrollbar button
  28671. will move the viewport.
  28672. */
  28673. void setSingleStepSizes (int stepX, int stepY);
  28674. /** Shows or hides the buttons on any scrollbars that are used.
  28675. @see ScrollBar::setButtonVisibility
  28676. */
  28677. void setScrollBarButtonVisibility (bool buttonsVisible);
  28678. /** Returns a pointer to the scrollbar component being used.
  28679. Handy if you need to customise the bar somehow.
  28680. */
  28681. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  28682. /** Returns a pointer to the scrollbar component being used.
  28683. Handy if you need to customise the bar somehow.
  28684. */
  28685. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  28686. /** @internal */
  28687. void resized();
  28688. /** @internal */
  28689. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  28690. /** @internal */
  28691. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  28692. /** @internal */
  28693. bool keyPressed (const KeyPress& key);
  28694. /** @internal */
  28695. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  28696. /** @internal */
  28697. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  28698. private:
  28699. WeakReference<Component> contentComp;
  28700. Rectangle<int> lastVisibleArea;
  28701. int scrollBarThickness;
  28702. int singleStepX, singleStepY;
  28703. bool showHScrollbar, showVScrollbar;
  28704. Component contentHolder;
  28705. ScrollBar verticalScrollBar;
  28706. ScrollBar horizontalScrollBar;
  28707. void updateVisibleArea();
  28708. void deleteContentComp();
  28709. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  28710. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  28711. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  28712. #endif
  28713. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  28714. };
  28715. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  28716. /*** End of inlined file: juce_Viewport.h ***/
  28717. /*** Start of inlined file: juce_PopupMenu.h ***/
  28718. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  28719. #define __JUCE_POPUPMENU_JUCEHEADER__
  28720. /** Creates and displays a popup-menu.
  28721. To show a popup-menu, you create one of these, add some items to it, then
  28722. call its show() method, which returns the id of the item the user selects.
  28723. E.g. @code
  28724. void MyWidget::mouseDown (const MouseEvent& e)
  28725. {
  28726. PopupMenu m;
  28727. m.addItem (1, "item 1");
  28728. m.addItem (2, "item 2");
  28729. const int result = m.show();
  28730. if (result == 0)
  28731. {
  28732. // user dismissed the menu without picking anything
  28733. }
  28734. else if (result == 1)
  28735. {
  28736. // user picked item 1
  28737. }
  28738. else if (result == 2)
  28739. {
  28740. // user picked item 2
  28741. }
  28742. }
  28743. @endcode
  28744. Submenus are easy too: @code
  28745. void MyWidget::mouseDown (const MouseEvent& e)
  28746. {
  28747. PopupMenu subMenu;
  28748. subMenu.addItem (1, "item 1");
  28749. subMenu.addItem (2, "item 2");
  28750. PopupMenu mainMenu;
  28751. mainMenu.addItem (3, "item 3");
  28752. mainMenu.addSubMenu ("other choices", subMenu);
  28753. const int result = m.show();
  28754. ...etc
  28755. }
  28756. @endcode
  28757. */
  28758. class JUCE_API PopupMenu
  28759. {
  28760. public:
  28761. /** Creates an empty popup menu. */
  28762. PopupMenu();
  28763. /** Creates a copy of another menu. */
  28764. PopupMenu (const PopupMenu& other);
  28765. /** Destructor. */
  28766. ~PopupMenu();
  28767. /** Copies this menu from another one. */
  28768. PopupMenu& operator= (const PopupMenu& other);
  28769. /** Resets the menu, removing all its items. */
  28770. void clear();
  28771. /** Appends a new text item for this menu to show.
  28772. @param itemResultId the number that will be returned from the show() method
  28773. if the user picks this item. The value should never be
  28774. zero, because that's used to indicate that the user didn't
  28775. select anything.
  28776. @param itemText the text to show.
  28777. @param isActive if false, the item will be shown 'greyed-out' and can't be
  28778. picked
  28779. @param isTicked if true, the item will be shown with a tick next to it
  28780. @param iconToUse if this is non-zero, it should be an image that will be
  28781. displayed to the left of the item. This method will take its
  28782. own copy of the image passed-in, so there's no need to keep
  28783. it hanging around.
  28784. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  28785. */
  28786. void addItem (int itemResultId,
  28787. const String& itemText,
  28788. bool isActive = true,
  28789. bool isTicked = false,
  28790. const Image& iconToUse = Image::null);
  28791. /** Adds an item that represents one of the commands in a command manager object.
  28792. @param commandManager the manager to use to trigger the command and get information
  28793. about it
  28794. @param commandID the ID of the command
  28795. @param displayName if this is non-empty, then this string will be used instead of
  28796. the command's registered name
  28797. */
  28798. void addCommandItem (ApplicationCommandManager* commandManager,
  28799. int commandID,
  28800. const String& displayName = String::empty);
  28801. /** Appends a text item with a special colour.
  28802. This is the same as addItem(), but specifies a colour to use for the
  28803. text, which will override the default colours that are used by the
  28804. current look-and-feel. See addItem() for a description of the parameters.
  28805. */
  28806. void addColouredItem (int itemResultId,
  28807. const String& itemText,
  28808. const Colour& itemTextColour,
  28809. bool isActive = true,
  28810. bool isTicked = false,
  28811. const Image& iconToUse = Image::null);
  28812. /** Appends a custom menu item that can't be used to trigger a result.
  28813. This will add a user-defined component to use as a menu item. Unlike the
  28814. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  28815. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  28816. delete the component when it's finished, so it's the caller's responsibility
  28817. to manage the component that is passed-in.
  28818. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  28819. detection of a mouse-click on your component, and use that to trigger the
  28820. menu ID specified in itemResultId. If this is false, the menu item can't
  28821. be triggered, so itemResultId is not used.
  28822. @see CustomComponent
  28823. */
  28824. void addCustomItem (int itemResultId,
  28825. Component* customComponent,
  28826. int idealWidth, int idealHeight,
  28827. bool triggerMenuItemAutomaticallyWhenClicked);
  28828. /** Appends a sub-menu.
  28829. If the menu that's passed in is empty, it will appear as an inactive item.
  28830. */
  28831. void addSubMenu (const String& subMenuName,
  28832. const PopupMenu& subMenu,
  28833. bool isActive = true,
  28834. const Image& iconToUse = Image::null,
  28835. bool isTicked = false);
  28836. /** Appends a separator to the menu, to help break it up into sections.
  28837. The menu class is smart enough not to display separators at the top or bottom
  28838. of the menu, and it will replace mutliple adjacent separators with a single
  28839. one, so your code can be quite free and easy about adding these, and it'll
  28840. always look ok.
  28841. */
  28842. void addSeparator();
  28843. /** Adds a non-clickable text item to the menu.
  28844. This is a bold-font items which can be used as a header to separate the items
  28845. into named groups.
  28846. */
  28847. void addSectionHeader (const String& title);
  28848. /** Returns the number of items that the menu currently contains.
  28849. (This doesn't count separators).
  28850. */
  28851. int getNumItems() const throw();
  28852. /** Returns true if the menu contains a command item that triggers the given command. */
  28853. bool containsCommandItem (int commandID) const;
  28854. /** Returns true if the menu contains any items that can be used. */
  28855. bool containsAnyActiveItems() const throw();
  28856. /** Displays the menu and waits for the user to pick something.
  28857. This will display the menu modally, and return the ID of the item that the
  28858. user picks. If they click somewhere off the menu to get rid of it without
  28859. choosing anything, this will return 0.
  28860. The current location of the mouse will be used as the position to show the
  28861. menu - to explicitly set the menu's position, use showAt() instead. Depending
  28862. on where this point is on the screen, the menu will appear above, below or
  28863. to the side of the point.
  28864. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  28865. then when the menu first appears, it will make sure
  28866. that this item is visible. So if the menu has too many
  28867. items to fit on the screen, it will be scrolled to a
  28868. position where this item is visible.
  28869. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  28870. than this if some items are too long to fit.
  28871. @param maximumNumColumns if there are too many items to fit on-screen in a single
  28872. vertical column, the menu may be laid out as a series of
  28873. columns - this is the maximum number allowed. To use the
  28874. default value for this (probably about 7), you can pass
  28875. in zero.
  28876. @param standardItemHeight if this is non-zero, it will be used as the standard
  28877. height for menu items (apart from custom items)
  28878. @param callback if this is non-zero, the menu will be launched asynchronously,
  28879. returning immediately, and the callback will receive a
  28880. call when the menu is either dismissed or has an item
  28881. selected. This object will be owned and deleted by the
  28882. system, so make sure that it works safely and that any
  28883. pointers that it uses are safely within scope.
  28884. @see showAt
  28885. */
  28886. int show (int itemIdThatMustBeVisible = 0,
  28887. int minimumWidth = 0,
  28888. int maximumNumColumns = 0,
  28889. int standardItemHeight = 0,
  28890. ModalComponentManager::Callback* callback = 0);
  28891. /** Displays the menu at a specific location.
  28892. This is the same as show(), but uses a specific location (in global screen
  28893. co-ordinates) rather than the current mouse position.
  28894. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  28895. will be adjacent. Depending on where this is, the menu will decide which edge to
  28896. attach itself to, in order to fit itself fully on-screen. If you just want to
  28897. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  28898. with the position that you want.
  28899. @see show()
  28900. */
  28901. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  28902. int itemIdThatMustBeVisible = 0,
  28903. int minimumWidth = 0,
  28904. int maximumNumColumns = 0,
  28905. int standardItemHeight = 0,
  28906. ModalComponentManager::Callback* callback = 0);
  28907. /** Displays the menu as if it's attached to a component such as a button.
  28908. This is similar to showAt(), but will position it next to the given component, e.g.
  28909. so that the menu's edge is aligned with that of the component. This is intended for
  28910. things like buttons that trigger a pop-up menu.
  28911. */
  28912. int showAt (Component* componentToAttachTo,
  28913. int itemIdThatMustBeVisible = 0,
  28914. int minimumWidth = 0,
  28915. int maximumNumColumns = 0,
  28916. int standardItemHeight = 0,
  28917. ModalComponentManager::Callback* callback = 0);
  28918. /** Closes any menus that are currently open.
  28919. This might be useful if you have a situation where your window is being closed
  28920. by some means other than a user action, and you'd like to make sure that menus
  28921. aren't left hanging around.
  28922. */
  28923. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  28924. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  28925. This can be called before show() if you need a customised menu. Be careful
  28926. not to delete the LookAndFeel object before the menu has been deleted.
  28927. */
  28928. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  28929. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  28930. These constants can be used either via the LookAndFeel::setColour()
  28931. method for the look and feel that is set for this menu with setLookAndFeel()
  28932. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  28933. */
  28934. enum ColourIds
  28935. {
  28936. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  28937. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  28938. colour is specified when the item is added). */
  28939. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  28940. addSectionHeader() method). */
  28941. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  28942. highlighted menu item. */
  28943. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  28944. highlighted item. */
  28945. };
  28946. /**
  28947. Allows you to iterate through the items in a pop-up menu, and examine
  28948. their properties.
  28949. To use this, just create one and repeatedly call its next() method. When this
  28950. returns true, all the member variables of the iterator are filled-out with
  28951. information describing the menu item. When it returns false, the end of the
  28952. list has been reached.
  28953. */
  28954. class JUCE_API MenuItemIterator
  28955. {
  28956. public:
  28957. /** Creates an iterator that will scan through the items in the specified
  28958. menu.
  28959. Be careful not to add any items to a menu while it is being iterated,
  28960. or things could get out of step.
  28961. */
  28962. MenuItemIterator (const PopupMenu& menu);
  28963. /** Destructor. */
  28964. ~MenuItemIterator();
  28965. /** Returns true if there is another item, and sets up all this object's
  28966. member variables to reflect that item's properties.
  28967. */
  28968. bool next();
  28969. String itemName;
  28970. const PopupMenu* subMenu;
  28971. int itemId;
  28972. bool isSeparator;
  28973. bool isTicked;
  28974. bool isEnabled;
  28975. bool isCustomComponent;
  28976. bool isSectionHeader;
  28977. const Colour* customColour;
  28978. Image customImage;
  28979. ApplicationCommandManager* commandManager;
  28980. private:
  28981. const PopupMenu& menu;
  28982. int index;
  28983. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  28984. };
  28985. /** A user-defined copmonent that can be used as an item in a popup menu.
  28986. @see PopupMenu::addCustomItem
  28987. */
  28988. class JUCE_API CustomComponent : public Component,
  28989. public ReferenceCountedObject
  28990. {
  28991. public:
  28992. /** Creates a custom item.
  28993. If isTriggeredAutomatically is true, then the menu will automatically detect
  28994. a mouse-click on this component and use that to invoke the menu item. If it's
  28995. false, then it's up to your class to manually trigger the item when it wants to.
  28996. */
  28997. CustomComponent (bool isTriggeredAutomatically = true);
  28998. /** Destructor. */
  28999. ~CustomComponent();
  29000. /** Returns a rectangle with the size that this component would like to have.
  29001. Note that the size which this method returns isn't necessarily the one that
  29002. the menu will give it, as the items will be stretched to have a uniform width.
  29003. */
  29004. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  29005. /** Dismisses the menu, indicating that this item has been chosen.
  29006. This will cause the menu to exit from its modal state, returning
  29007. this item's id as the result.
  29008. */
  29009. void triggerMenuItem();
  29010. /** Returns true if this item should be highlighted because the mouse is over it.
  29011. You can call this method in your paint() method to find out whether
  29012. to draw a highlight.
  29013. */
  29014. bool isItemHighlighted() const throw() { return isHighlighted; }
  29015. /** @internal. */
  29016. bool isTriggeredAutomatically() const throw() { return triggeredAutomatically; }
  29017. /** @internal. */
  29018. void setHighlighted (bool shouldBeHighlighted);
  29019. private:
  29020. bool isHighlighted, triggeredAutomatically;
  29021. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  29022. };
  29023. /** Appends a custom menu item.
  29024. This will add a user-defined component to use as a menu item. The component
  29025. passed in will be deleted by this menu when it's no longer needed.
  29026. @see CustomComponent
  29027. */
  29028. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  29029. private:
  29030. class Item;
  29031. class ItemComponent;
  29032. class Window;
  29033. friend class MenuItemIterator;
  29034. friend class ItemComponent;
  29035. friend class Window;
  29036. friend class CustomComponent;
  29037. friend class MenuBarComponent;
  29038. friend class OwnedArray <Item>;
  29039. friend class OwnedArray <ItemComponent>;
  29040. friend class ScopedPointer <Window>;
  29041. OwnedArray <Item> items;
  29042. LookAndFeel* lookAndFeel;
  29043. bool separatorPending;
  29044. void addSeparatorIfPending();
  29045. int showMenu (const Rectangle<int>& target, int itemIdThatMustBeVisible,
  29046. int minimumWidth, int maximumNumColumns, int standardItemHeight,
  29047. Component* componentAttachedTo, ModalComponentManager::Callback* callback);
  29048. JUCE_LEAK_DETECTOR (PopupMenu);
  29049. };
  29050. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  29051. /*** End of inlined file: juce_PopupMenu.h ***/
  29052. /*** Start of inlined file: juce_TextInputTarget.h ***/
  29053. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  29054. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  29055. /** An abstract base class that is implemented by components that wish to be used
  29056. as text editors.
  29057. This class allows different types of text editor component to provide a uniform
  29058. interface, which can be used by things like OS-specific input methods, on-screen
  29059. keyboards, etc.
  29060. */
  29061. class JUCE_API TextInputTarget
  29062. {
  29063. public:
  29064. /** */
  29065. TextInputTarget() {}
  29066. /** Destructor. */
  29067. virtual ~TextInputTarget() {}
  29068. /** Returns true if this input target is currently accepting input.
  29069. For example, a text editor might return false if it's in read-only mode.
  29070. */
  29071. virtual bool isTextInputActive() const = 0;
  29072. /** Returns the extents of the selected text region, or an empty range if
  29073. nothing is selected,
  29074. */
  29075. virtual const Range<int> getHighlightedRegion() const = 0;
  29076. /** Sets the currently-selected text region.
  29077. */
  29078. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  29079. /** Returns a specified sub-section of the text.
  29080. */
  29081. virtual const String getTextInRange (const Range<int>& range) const = 0;
  29082. /** Inserts some text, overwriting the selected text region, if there is one. */
  29083. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  29084. };
  29085. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  29086. /*** End of inlined file: juce_TextInputTarget.h ***/
  29087. /**
  29088. A component containing text that can be edited.
  29089. A TextEditor can either be in single- or multi-line mode, and supports mixed
  29090. fonts and colours.
  29091. @see TextEditor::Listener, Label
  29092. */
  29093. class JUCE_API TextEditor : public Component,
  29094. public TextInputTarget,
  29095. public SettableTooltipClient
  29096. {
  29097. public:
  29098. /** Creates a new, empty text editor.
  29099. @param componentName the name to pass to the component for it to use as its name
  29100. @param passwordCharacter if this is not zero, this character will be used as a replacement
  29101. for all characters that are drawn on screen - e.g. to create
  29102. a password-style textbox containing circular blobs instead of text,
  29103. you could set this value to 0x25cf, which is the unicode character
  29104. for a black splodge (not all fonts include this, though), or 0x2022,
  29105. which is a bullet (probably the best choice for linux).
  29106. */
  29107. explicit TextEditor (const String& componentName = String::empty,
  29108. juce_wchar passwordCharacter = 0);
  29109. /** Destructor. */
  29110. virtual ~TextEditor();
  29111. /** Puts the editor into either multi- or single-line mode.
  29112. By default, the editor will be in single-line mode, so use this if you need a multi-line
  29113. editor.
  29114. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  29115. on if you want a multi-line editor with line-breaks.
  29116. @see isMultiLine, setReturnKeyStartsNewLine
  29117. */
  29118. void setMultiLine (bool shouldBeMultiLine,
  29119. bool shouldWordWrap = true);
  29120. /** Returns true if the editor is in multi-line mode.
  29121. */
  29122. bool isMultiLine() const;
  29123. /** Changes the behaviour of the return key.
  29124. If set to true, the return key will insert a new-line into the text; if false
  29125. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  29126. method. By default this is set to false, and when true it will only insert
  29127. new-lines when in multi-line mode (see setMultiLine()).
  29128. */
  29129. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  29130. /** Returns the value set by setReturnKeyStartsNewLine().
  29131. See setReturnKeyStartsNewLine() for more info.
  29132. */
  29133. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  29134. /** Indicates whether the tab key should be accepted and used to input a tab character,
  29135. or whether it gets ignored.
  29136. By default the tab key is ignored, so that it can be used to switch keyboard focus
  29137. between components.
  29138. */
  29139. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  29140. /** Returns true if the tab key is being used for input.
  29141. @see setTabKeyUsedAsCharacter
  29142. */
  29143. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  29144. /** Changes the editor to read-only mode.
  29145. By default, the text editor is not read-only. If you're making it read-only, you
  29146. might also want to call setCaretVisible (false) to get rid of the caret.
  29147. The text can still be highlighted and copied when in read-only mode.
  29148. @see isReadOnly, setCaretVisible
  29149. */
  29150. void setReadOnly (bool shouldBeReadOnly);
  29151. /** Returns true if the editor is in read-only mode.
  29152. */
  29153. bool isReadOnly() const;
  29154. /** Makes the caret visible or invisible.
  29155. By default the caret is visible.
  29156. @see setCaretColour, setCaretPosition
  29157. */
  29158. void setCaretVisible (bool shouldBeVisible);
  29159. /** Returns true if the caret is enabled.
  29160. @see setCaretVisible
  29161. */
  29162. bool isCaretVisible() const { return caretVisible; }
  29163. /** Enables/disables a vertical scrollbar.
  29164. (This only applies when in multi-line mode). When the text gets too long to fit
  29165. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  29166. this is enabled, the scrollbar will be hidden unless it's needed.
  29167. By default the scrollbar is enabled.
  29168. */
  29169. void setScrollbarsShown (bool shouldBeEnabled);
  29170. /** Returns true if scrollbars are enabled.
  29171. @see setScrollbarsShown
  29172. */
  29173. bool areScrollbarsShown() const { return scrollbarVisible; }
  29174. /** Changes the password character used to disguise the text.
  29175. @param passwordCharacter if this is not zero, this character will be used as a replacement
  29176. for all characters that are drawn on screen - e.g. to create
  29177. a password-style textbox containing circular blobs instead of text,
  29178. you could set this value to 0x25cf, which is the unicode character
  29179. for a black splodge (not all fonts include this, though), or 0x2022,
  29180. which is a bullet (probably the best choice for linux).
  29181. */
  29182. void setPasswordCharacter (juce_wchar passwordCharacter);
  29183. /** Returns the current password character.
  29184. @see setPasswordCharacter
  29185. */
  29186. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  29187. /** Allows a right-click menu to appear for the editor.
  29188. (This defaults to being enabled).
  29189. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  29190. of options such as cut/copy/paste, undo/redo, etc.
  29191. */
  29192. void setPopupMenuEnabled (bool menuEnabled);
  29193. /** Returns true if the right-click menu is enabled.
  29194. @see setPopupMenuEnabled
  29195. */
  29196. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  29197. /** Returns true if a popup-menu is currently being displayed.
  29198. */
  29199. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  29200. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  29201. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29202. methods.
  29203. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29204. */
  29205. enum ColourIds
  29206. {
  29207. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  29208. transparent if necessary. */
  29209. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  29210. that because the editor can contain multiple colours, calling this
  29211. method won't change the colour of existing text - to do that, call
  29212. applyFontToAllText() after calling this method.*/
  29213. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  29214. the text - this can be transparent if you don't want to show any
  29215. highlighting.*/
  29216. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  29217. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  29218. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  29219. the edge of the component. */
  29220. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  29221. the edge of the component when it has focus. */
  29222. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  29223. around the edge of the editor. */
  29224. };
  29225. /** Sets the font to use for newly added text.
  29226. This will change the font that will be used next time any text is added or entered
  29227. into the editor. It won't change the font of any existing text - to do that, use
  29228. applyFontToAllText() instead.
  29229. @see applyFontToAllText
  29230. */
  29231. void setFont (const Font& newFont);
  29232. /** Applies a font to all the text in the editor.
  29233. This will also set the current font to use for any new text that's added.
  29234. @see setFont
  29235. */
  29236. void applyFontToAllText (const Font& newFont);
  29237. /** Returns the font that's currently being used for new text.
  29238. @see setFont
  29239. */
  29240. const Font getFont() const;
  29241. /** If set to true, focusing on the editor will highlight all its text.
  29242. (Set to false by default).
  29243. This is useful for boxes where you expect the user to re-enter all the
  29244. text when they focus on the component, rather than editing what's already there.
  29245. */
  29246. void setSelectAllWhenFocused (bool b);
  29247. /** Sets limits on the characters that can be entered.
  29248. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  29249. limit is set
  29250. @param allowedCharacters if this is non-empty, then only characters that occur in
  29251. this string are allowed to be entered into the editor.
  29252. */
  29253. void setInputRestrictions (int maxTextLength,
  29254. const String& allowedCharacters = String::empty);
  29255. /** When the text editor is empty, it can be set to display a message.
  29256. This is handy for things like telling the user what to type in the box - the
  29257. string is only displayed, it's not taken to actually be the contents of
  29258. the editor.
  29259. */
  29260. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  29261. /** Changes the size of the scrollbars that are used.
  29262. Handy if you need smaller scrollbars for a small text box.
  29263. */
  29264. void setScrollBarThickness (int newThicknessPixels);
  29265. /** Shows or hides the buttons on any scrollbars that are used.
  29266. @see ScrollBar::setButtonVisibility
  29267. */
  29268. void setScrollBarButtonVisibility (bool buttonsVisible);
  29269. /**
  29270. Receives callbacks from a TextEditor component when it changes.
  29271. @see TextEditor::addListener
  29272. */
  29273. class JUCE_API Listener
  29274. {
  29275. public:
  29276. /** Destructor. */
  29277. virtual ~Listener() {}
  29278. /** Called when the user changes the text in some way. */
  29279. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  29280. /** Called when the user presses the return key. */
  29281. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  29282. /** Called when the user presses the escape key. */
  29283. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  29284. /** Called when the text editor loses focus. */
  29285. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  29286. };
  29287. /** Registers a listener to be told when things happen to the text.
  29288. @see removeListener
  29289. */
  29290. void addListener (Listener* newListener);
  29291. /** Deregisters a listener.
  29292. @see addListener
  29293. */
  29294. void removeListener (Listener* listenerToRemove);
  29295. /** Returns the entire contents of the editor. */
  29296. const String getText() const;
  29297. /** Returns a section of the contents of the editor. */
  29298. const String getTextInRange (const Range<int>& textRange) const;
  29299. /** Returns true if there are no characters in the editor.
  29300. This is more efficient than calling getText().isEmpty().
  29301. */
  29302. bool isEmpty() const;
  29303. /** Sets the entire content of the editor.
  29304. This will clear the editor and insert the given text (using the current text colour
  29305. and font). You can set the current text colour using
  29306. @code setColour (TextEditor::textColourId, ...);
  29307. @endcode
  29308. @param newText the text to add
  29309. @param sendTextChangeMessage if true, this will cause a change message to
  29310. be sent to all the listeners.
  29311. @see insertText
  29312. */
  29313. void setText (const String& newText,
  29314. bool sendTextChangeMessage = true);
  29315. /** Returns a Value object that can be used to get or set the text.
  29316. Bear in mind that this operate quite slowly if your text box contains large
  29317. amounts of text, as it needs to dynamically build the string that's involved. It's
  29318. best used for small text boxes.
  29319. */
  29320. Value& getTextValue();
  29321. /** Inserts some text at the current cursor position.
  29322. If a section of the text is highlighted, it will be replaced by
  29323. this string, otherwise it will be inserted.
  29324. To delete a section of text, you can use setHighlightedRegion() to
  29325. highlight it, and call insertTextAtCursor (String::empty).
  29326. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  29327. */
  29328. void insertTextAtCaret (const String& textToInsert);
  29329. /** Deletes all the text from the editor. */
  29330. void clear();
  29331. /** Deletes the currently selected region, and puts it on the clipboard.
  29332. @see copy, paste, SystemClipboard
  29333. */
  29334. void cut();
  29335. /** Copies any currently selected region to the clipboard.
  29336. @see cut, paste, SystemClipboard
  29337. */
  29338. void copy();
  29339. /** Pastes the contents of the clipboard into the editor at the cursor position.
  29340. @see cut, copy, SystemClipboard
  29341. */
  29342. void paste();
  29343. /** Moves the caret to be in front of a given character.
  29344. @see getCaretPosition
  29345. */
  29346. void setCaretPosition (int newIndex);
  29347. /** Returns the current index of the caret.
  29348. @see setCaretPosition
  29349. */
  29350. int getCaretPosition() const;
  29351. /** Attempts to scroll the text editor so that the caret ends up at
  29352. a specified position.
  29353. This won't affect the caret's position within the text, it tries to scroll
  29354. the entire editor vertically and horizontally so that the caret is sitting
  29355. at the given position (relative to the top-left of this component).
  29356. Depending on the amount of text available, it might not be possible to
  29357. scroll far enough for the caret to reach this exact position, but it
  29358. will go as far as it can in that direction.
  29359. */
  29360. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  29361. /** Get the graphical position of the caret.
  29362. The rectangle returned is relative to the component's top-left corner.
  29363. @see scrollEditorToPositionCaret
  29364. */
  29365. const Rectangle<int> getCaretRectangle();
  29366. /** Selects a section of the text. */
  29367. void setHighlightedRegion (const Range<int>& newSelection);
  29368. /** Returns the range of characters that are selected.
  29369. If nothing is selected, this will return an empty range.
  29370. @see setHighlightedRegion
  29371. */
  29372. const Range<int> getHighlightedRegion() const { return selection; }
  29373. /** Returns the section of text that is currently selected. */
  29374. const String getHighlightedText() const;
  29375. /** Finds the index of the character at a given position.
  29376. The co-ordinates are relative to the component's top-left.
  29377. */
  29378. int getTextIndexAt (int x, int y);
  29379. /** Counts the number of characters in the text.
  29380. This is quicker than getting the text as a string if you just need to know
  29381. the length.
  29382. */
  29383. int getTotalNumChars() const;
  29384. /** Returns the total width of the text, as it is currently laid-out.
  29385. This may be larger than the size of the TextEditor, and can change when
  29386. the TextEditor is resized or the text changes.
  29387. */
  29388. int getTextWidth() const;
  29389. /** Returns the maximum height of the text, as it is currently laid-out.
  29390. This may be larger than the size of the TextEditor, and can change when
  29391. the TextEditor is resized or the text changes.
  29392. */
  29393. int getTextHeight() const;
  29394. /** Changes the size of the gap at the top and left-edge of the editor.
  29395. By default there's a gap of 4 pixels.
  29396. */
  29397. void setIndents (int newLeftIndent, int newTopIndent);
  29398. /** Changes the size of border left around the edge of the component.
  29399. @see getBorder
  29400. */
  29401. void setBorder (const BorderSize& border);
  29402. /** Returns the size of border around the edge of the component.
  29403. @see setBorder
  29404. */
  29405. const BorderSize getBorder() const;
  29406. /** Used to disable the auto-scrolling which keeps the cursor visible.
  29407. If true (the default), the editor will scroll when the cursor moves offscreen. If
  29408. set to false, it won't.
  29409. */
  29410. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  29411. /** @internal */
  29412. void paint (Graphics& g);
  29413. /** @internal */
  29414. void paintOverChildren (Graphics& g);
  29415. /** @internal */
  29416. void mouseDown (const MouseEvent& e);
  29417. /** @internal */
  29418. void mouseUp (const MouseEvent& e);
  29419. /** @internal */
  29420. void mouseDrag (const MouseEvent& e);
  29421. /** @internal */
  29422. void mouseDoubleClick (const MouseEvent& e);
  29423. /** @internal */
  29424. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  29425. /** @internal */
  29426. bool keyPressed (const KeyPress& key);
  29427. /** @internal */
  29428. bool keyStateChanged (bool isKeyDown);
  29429. /** @internal */
  29430. void focusGained (FocusChangeType cause);
  29431. /** @internal */
  29432. void focusLost (FocusChangeType cause);
  29433. /** @internal */
  29434. void resized();
  29435. /** @internal */
  29436. void enablementChanged();
  29437. /** @internal */
  29438. void colourChanged();
  29439. /** @internal */
  29440. bool isTextInputActive() const;
  29441. /** This adds the items to the popup menu.
  29442. By default it adds the cut/copy/paste items, but you can override this if
  29443. you need to replace these with your own items.
  29444. If you want to add your own items to the existing ones, you can override this,
  29445. call the base class's addPopupMenuItems() method, then append your own items.
  29446. When the menu has been shown, performPopupMenuAction() will be called to
  29447. perform the item that the user has chosen.
  29448. The default menu items will be added using item IDs in the range
  29449. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  29450. menu IDs.
  29451. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  29452. a pointer to the info about it, or may be null if the menu is being triggered
  29453. by some other means.
  29454. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  29455. */
  29456. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  29457. const MouseEvent* mouseClickEvent);
  29458. /** This is called to perform one of the items that was shown on the popup menu.
  29459. If you've overridden addPopupMenuItems(), you should also override this
  29460. to perform the actions that you've added.
  29461. If you've overridden addPopupMenuItems() but have still left the default items
  29462. on the menu, remember to call the superclass's performPopupMenuAction()
  29463. so that it can perform the default actions if that's what the user clicked on.
  29464. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  29465. */
  29466. virtual void performPopupMenuAction (int menuItemID);
  29467. protected:
  29468. /** Scrolls the minimum distance needed to get the caret into view. */
  29469. void scrollToMakeSureCursorIsVisible();
  29470. /** @internal */
  29471. void moveCaret (int newCaretPos);
  29472. /** @internal */
  29473. void moveCursorTo (int newPosition, bool isSelecting);
  29474. /** Used internally to dispatch a text-change message. */
  29475. void textChanged();
  29476. /** Begins a new transaction in the UndoManager.
  29477. */
  29478. void newTransaction();
  29479. /** Used internally to trigger an undo or redo. */
  29480. void doUndoRedo (bool isRedo);
  29481. /** Can be overridden to intercept return key presses directly */
  29482. virtual void returnPressed();
  29483. /** Can be overridden to intercept escape key presses directly */
  29484. virtual void escapePressed();
  29485. /** @internal */
  29486. void handleCommandMessage (int commandId);
  29487. private:
  29488. class Iterator;
  29489. class UniformTextSection;
  29490. class TextHolderComponent;
  29491. class InsertAction;
  29492. class RemoveAction;
  29493. friend class InsertAction;
  29494. friend class RemoveAction;
  29495. ScopedPointer <Viewport> viewport;
  29496. TextHolderComponent* textHolder;
  29497. BorderSize borderSize;
  29498. bool readOnly : 1;
  29499. bool multiline : 1;
  29500. bool wordWrap : 1;
  29501. bool returnKeyStartsNewLine : 1;
  29502. bool caretVisible : 1;
  29503. bool popupMenuEnabled : 1;
  29504. bool selectAllTextWhenFocused : 1;
  29505. bool scrollbarVisible : 1;
  29506. bool wasFocused : 1;
  29507. bool caretFlashState : 1;
  29508. bool keepCursorOnScreen : 1;
  29509. bool tabKeyUsed : 1;
  29510. bool menuActive : 1;
  29511. bool valueTextNeedsUpdating : 1;
  29512. UndoManager undoManager;
  29513. float cursorX, cursorY, cursorHeight;
  29514. int maxTextLength;
  29515. Range<int> selection;
  29516. int leftIndent, topIndent;
  29517. unsigned int lastTransactionTime;
  29518. Font currentFont;
  29519. mutable int totalNumChars;
  29520. int caretPosition;
  29521. Array <UniformTextSection*> sections;
  29522. String textToShowWhenEmpty;
  29523. Colour colourForTextWhenEmpty;
  29524. juce_wchar passwordCharacter;
  29525. Value textValue;
  29526. enum
  29527. {
  29528. notDragging,
  29529. draggingSelectionStart,
  29530. draggingSelectionEnd
  29531. } dragType;
  29532. String allowedCharacters;
  29533. ListenerList <Listener> listeners;
  29534. void coalesceSimilarSections();
  29535. void splitSection (int sectionIndex, int charToSplitAt);
  29536. void clearInternal (UndoManager* um);
  29537. void insert (const String& text, int insertIndex, const Font& font,
  29538. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  29539. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  29540. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  29541. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  29542. void updateCaretPosition();
  29543. void textWasChangedByValue();
  29544. int indexAtPosition (float x, float y);
  29545. int findWordBreakAfter (int position) const;
  29546. int findWordBreakBefore (int position) const;
  29547. friend class TextHolderComponent;
  29548. friend class TextEditorViewport;
  29549. void drawContent (Graphics& g);
  29550. void updateTextHolderSize();
  29551. float getWordWrapWidth() const;
  29552. void timerCallbackInt();
  29553. void repaintCaret();
  29554. void repaintText (const Range<int>& range);
  29555. UndoManager* getUndoManager() throw();
  29556. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  29557. };
  29558. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  29559. typedef TextEditor::Listener TextEditorListener;
  29560. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  29561. /*** End of inlined file: juce_TextEditor.h ***/
  29562. #if JUCE_VC6
  29563. #define Listener ButtonListener
  29564. #endif
  29565. /**
  29566. A component that displays a text string, and can optionally become a text
  29567. editor when clicked.
  29568. */
  29569. class JUCE_API Label : public Component,
  29570. public SettableTooltipClient,
  29571. protected TextEditorListener,
  29572. private ComponentListener,
  29573. private ValueListener
  29574. {
  29575. public:
  29576. /** Creates a Label.
  29577. @param componentName the name to give the component
  29578. @param labelText the text to show in the label
  29579. */
  29580. Label (const String& componentName = String::empty,
  29581. const String& labelText = String::empty);
  29582. /** Destructor. */
  29583. ~Label();
  29584. /** Changes the label text.
  29585. If broadcastChangeMessage is true and the new text is different to the current
  29586. text, then the class will broadcast a change message to any Label::Listener objects
  29587. that are registered.
  29588. */
  29589. void setText (const String& newText, bool broadcastChangeMessage);
  29590. /** Returns the label's current text.
  29591. @param returnActiveEditorContents if this is true and the label is currently
  29592. being edited, then this method will return the
  29593. text as it's being shown in the editor. If false,
  29594. then the value returned here won't be updated until
  29595. the user has finished typing and pressed the return
  29596. key.
  29597. */
  29598. const String getText (bool returnActiveEditorContents = false) const;
  29599. /** Returns the text content as a Value object.
  29600. You can call Value::referTo() on this object to make the label read and control
  29601. a Value object that you supply.
  29602. */
  29603. Value& getTextValue() { return textValue; }
  29604. /** Changes the font to use to draw the text.
  29605. @see getFont
  29606. */
  29607. void setFont (const Font& newFont);
  29608. /** Returns the font currently being used.
  29609. @see setFont
  29610. */
  29611. const Font& getFont() const throw();
  29612. /** A set of colour IDs to use to change the colour of various aspects of the label.
  29613. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29614. methods.
  29615. Note that you can also use the constants from TextEditor::ColourIds to change the
  29616. colour of the text editor that is opened when a label is editable.
  29617. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29618. */
  29619. enum ColourIds
  29620. {
  29621. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  29622. textColourId = 0x1000281, /**< The colour for the text. */
  29623. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  29624. Leave this transparent to not have an outline. */
  29625. };
  29626. /** Sets the style of justification to be used for positioning the text.
  29627. (The default is Justification::centredLeft)
  29628. */
  29629. void setJustificationType (const Justification& justification);
  29630. /** Returns the type of justification, as set in setJustificationType(). */
  29631. const Justification getJustificationType() const throw() { return justification; }
  29632. /** Changes the gap that is left between the edge of the component and the text.
  29633. By default there's a small gap left at the sides of the component to allow for
  29634. the drawing of the border, but you can change this if necessary.
  29635. */
  29636. void setBorderSize (int horizontalBorder, int verticalBorder);
  29637. /** Returns the size of the horizontal gap being left around the text.
  29638. */
  29639. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  29640. /** Returns the size of the vertical gap being left around the text.
  29641. */
  29642. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  29643. /** Makes this label "stick to" another component.
  29644. This will cause the label to follow another component around, staying
  29645. either to its left or above it.
  29646. @param owner the component to follow
  29647. @param onLeft if true, the label will stay on the left of its component; if
  29648. false, it will stay above it.
  29649. */
  29650. void attachToComponent (Component* owner, bool onLeft);
  29651. /** If this label has been attached to another component using attachToComponent, this
  29652. returns the other component.
  29653. Returns 0 if the label is not attached.
  29654. */
  29655. Component* getAttachedComponent() const;
  29656. /** If the label is attached to the left of another component, this returns true.
  29657. Returns false if the label is above the other component. This is only relevent if
  29658. attachToComponent() has been called.
  29659. */
  29660. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  29661. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  29662. using ellipsis.
  29663. @see Graphics::drawFittedText
  29664. */
  29665. void setMinimumHorizontalScale (float newScale);
  29666. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  29667. /**
  29668. A class for receiving events from a Label.
  29669. You can register a Label::Listener with a Label using the Label::addListener()
  29670. method, and it will be called when the text of the label changes, either because
  29671. of a call to Label::setText() or by the user editing the text (if the label is
  29672. editable).
  29673. @see Label::addListener, Label::removeListener
  29674. */
  29675. class JUCE_API Listener
  29676. {
  29677. public:
  29678. /** Destructor. */
  29679. virtual ~Listener() {}
  29680. /** Called when a Label's text has changed.
  29681. */
  29682. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  29683. };
  29684. /** Registers a listener that will be called when the label's text changes. */
  29685. void addListener (Listener* listener);
  29686. /** Deregisters a previously-registered listener. */
  29687. void removeListener (Listener* listener);
  29688. /** Makes the label turn into a TextEditor when clicked.
  29689. By default this is turned off.
  29690. If turned on, then single- or double-clicking will turn the label into
  29691. an editor. If the user then changes the text, then the ChangeBroadcaster
  29692. base class will be used to send change messages to any listeners that
  29693. have registered.
  29694. If the user changes the text, the textWasEdited() method will be called
  29695. afterwards, and subclasses can override this if they need to do anything
  29696. special.
  29697. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  29698. @param editOnDoubleClick if true, a double-click is needed to start editing
  29699. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  29700. edited will discard any changes; if false, then this will
  29701. commit the changes.
  29702. @see showEditor, setEditorColours, TextEditor
  29703. */
  29704. void setEditable (bool editOnSingleClick,
  29705. bool editOnDoubleClick = false,
  29706. bool lossOfFocusDiscardsChanges = false);
  29707. /** Returns true if this option was set using setEditable(). */
  29708. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  29709. /** Returns true if this option was set using setEditable(). */
  29710. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  29711. /** Returns true if this option has been set in a call to setEditable(). */
  29712. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  29713. /** Returns true if the user can edit this label's text. */
  29714. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  29715. /** Makes the editor appear as if the label had been clicked by the user.
  29716. @see textWasEdited, setEditable
  29717. */
  29718. void showEditor();
  29719. /** Hides the editor if it was being shown.
  29720. @param discardCurrentEditorContents if true, the label's text will be
  29721. reset to whatever it was before the editor
  29722. was shown; if false, the current contents of the
  29723. editor will be used to set the label's text
  29724. before it is hidden.
  29725. */
  29726. void hideEditor (bool discardCurrentEditorContents);
  29727. /** Returns true if the editor is currently focused and active. */
  29728. bool isBeingEdited() const throw();
  29729. protected:
  29730. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  29731. Subclasses can override this if they need to customise this component in some way.
  29732. */
  29733. virtual TextEditor* createEditorComponent();
  29734. /** Called after the user changes the text. */
  29735. virtual void textWasEdited();
  29736. /** Called when the text has been altered. */
  29737. virtual void textWasChanged();
  29738. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  29739. virtual void editorShown (TextEditor* editorComponent);
  29740. /** Called when the text editor is going to be deleted, after editing has finished. */
  29741. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  29742. /** @internal */
  29743. void paint (Graphics& g);
  29744. /** @internal */
  29745. void resized();
  29746. /** @internal */
  29747. void mouseUp (const MouseEvent& e);
  29748. /** @internal */
  29749. void mouseDoubleClick (const MouseEvent& e);
  29750. /** @internal */
  29751. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  29752. /** @internal */
  29753. void componentParentHierarchyChanged (Component& component);
  29754. /** @internal */
  29755. void componentVisibilityChanged (Component& component);
  29756. /** @internal */
  29757. void inputAttemptWhenModal();
  29758. /** @internal */
  29759. void focusGained (FocusChangeType);
  29760. /** @internal */
  29761. void enablementChanged();
  29762. /** @internal */
  29763. KeyboardFocusTraverser* createFocusTraverser();
  29764. /** @internal */
  29765. void textEditorTextChanged (TextEditor& editor);
  29766. /** @internal */
  29767. void textEditorReturnKeyPressed (TextEditor& editor);
  29768. /** @internal */
  29769. void textEditorEscapeKeyPressed (TextEditor& editor);
  29770. /** @internal */
  29771. void textEditorFocusLost (TextEditor& editor);
  29772. /** @internal */
  29773. void colourChanged();
  29774. /** @internal */
  29775. void valueChanged (Value&);
  29776. private:
  29777. Value textValue;
  29778. String lastTextValue;
  29779. Font font;
  29780. Justification justification;
  29781. ScopedPointer<TextEditor> editor;
  29782. ListenerList<Listener> listeners;
  29783. WeakReference<Component> ownerComponent;
  29784. int horizontalBorderSize, verticalBorderSize;
  29785. float minimumHorizontalScale;
  29786. bool editSingleClick : 1;
  29787. bool editDoubleClick : 1;
  29788. bool lossOfFocusDiscardsChanges : 1;
  29789. bool leftOfOwnerComp : 1;
  29790. bool updateFromTextEditorContents();
  29791. void callChangeListeners();
  29792. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  29793. };
  29794. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  29795. typedef Label::Listener LabelListener;
  29796. #if JUCE_VC6
  29797. #undef Listener
  29798. #endif
  29799. #endif // __JUCE_LABEL_JUCEHEADER__
  29800. /*** End of inlined file: juce_Label.h ***/
  29801. #if JUCE_VC6
  29802. #define Listener SliderListener
  29803. #endif
  29804. /**
  29805. A component that lets the user choose from a drop-down list of choices.
  29806. The combo-box has a list of text strings, each with an associated id number,
  29807. that will be shown in the drop-down list when the user clicks on the component.
  29808. The currently selected choice is displayed in the combo-box, and this can
  29809. either be read-only text, or editable.
  29810. To find out when the user selects a different item or edits the text, you
  29811. can register a ComboBox::Listener to receive callbacks.
  29812. @see ComboBox::Listener
  29813. */
  29814. class JUCE_API ComboBox : public Component,
  29815. public SettableTooltipClient,
  29816. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  29817. public ValueListener,
  29818. private AsyncUpdater
  29819. {
  29820. public:
  29821. /** Creates a combo-box.
  29822. On construction, the text field will be empty, so you should call the
  29823. setSelectedId() or setText() method to choose the initial value before
  29824. displaying it.
  29825. @param componentName the name to set for the component (see Component::setName())
  29826. */
  29827. explicit ComboBox (const String& componentName = String::empty);
  29828. /** Destructor. */
  29829. ~ComboBox();
  29830. /** Sets whether the test in the combo-box is editable.
  29831. The default state for a new ComboBox is non-editable, and can only be changed
  29832. by choosing from the drop-down list.
  29833. */
  29834. void setEditableText (bool isEditable);
  29835. /** Returns true if the text is directly editable.
  29836. @see setEditableText
  29837. */
  29838. bool isTextEditable() const throw();
  29839. /** Sets the style of justification to be used for positioning the text.
  29840. The default is Justification::centredLeft. The text is displayed using a
  29841. Label component inside the ComboBox.
  29842. */
  29843. void setJustificationType (const Justification& justification);
  29844. /** Returns the current justification for the text box.
  29845. @see setJustificationType
  29846. */
  29847. const Justification getJustificationType() const throw();
  29848. /** Adds an item to be shown in the drop-down list.
  29849. @param newItemText the text of the item to show in the list
  29850. @param newItemId an associated ID number that can be set or retrieved - see
  29851. getSelectedId() and setSelectedId(). Note that this value can not
  29852. be 0!
  29853. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  29854. */
  29855. void addItem (const String& newItemText, int newItemId);
  29856. /** Adds a separator line to the drop-down list.
  29857. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  29858. */
  29859. void addSeparator();
  29860. /** Adds a heading to the drop-down list, so that you can group the items into
  29861. different sections.
  29862. The headings are indented slightly differently to set them apart from the
  29863. items on the list, and obviously can't be selected. You might want to add
  29864. separators between your sections too.
  29865. @see addItem, addSeparator
  29866. */
  29867. void addSectionHeading (const String& headingName);
  29868. /** This allows items in the drop-down list to be selectively disabled.
  29869. When you add an item, it's enabled by default, but you can call this
  29870. method to change its status.
  29871. If you disable an item which is already selected, this won't change the
  29872. current selection - it just stops the user choosing that item from the list.
  29873. */
  29874. void setItemEnabled (int itemId, bool shouldBeEnabled);
  29875. /** Changes the text for an existing item.
  29876. */
  29877. void changeItemText (int itemId, const String& newText);
  29878. /** Removes all the items from the drop-down list.
  29879. If this call causes the content to be cleared, then a change-message
  29880. will be broadcast unless dontSendChangeMessage is true.
  29881. @see addItem, removeItem, getNumItems
  29882. */
  29883. void clear (bool dontSendChangeMessage = false);
  29884. /** Returns the number of items that have been added to the list.
  29885. Note that this doesn't include headers or separators.
  29886. */
  29887. int getNumItems() const throw();
  29888. /** Returns the text for one of the items in the list.
  29889. Note that this doesn't include headers or separators.
  29890. @param index the item's index from 0 to (getNumItems() - 1)
  29891. */
  29892. const String getItemText (int index) const;
  29893. /** Returns the ID for one of the items in the list.
  29894. Note that this doesn't include headers or separators.
  29895. @param index the item's index from 0 to (getNumItems() - 1)
  29896. */
  29897. int getItemId (int index) const throw();
  29898. /** Returns the index in the list of a particular item ID.
  29899. If no such ID is found, this will return -1.
  29900. */
  29901. int indexOfItemId (int itemId) const throw();
  29902. /** Returns the ID of the item that's currently shown in the box.
  29903. If no item is selected, or if the text is editable and the user
  29904. has entered something which isn't one of the items in the list, then
  29905. this will return 0.
  29906. @see setSelectedId, getSelectedItemIndex, getText
  29907. */
  29908. int getSelectedId() const throw();
  29909. /** Returns a Value object that can be used to get or set the selected item's ID.
  29910. You can call Value::referTo() on this object to make the combo box control
  29911. another Value object.
  29912. */
  29913. Value& getSelectedIdAsValue() { return currentId; }
  29914. /** Sets one of the items to be the current selection.
  29915. This will set the ComboBox's text to that of the item that matches
  29916. this ID.
  29917. @param newItemId the new item to select
  29918. @param dontSendChangeMessage if set to true, this method won't trigger a
  29919. change notification
  29920. @see getSelectedId, setSelectedItemIndex, setText
  29921. */
  29922. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  29923. /** Returns the index of the item that's currently shown in the box.
  29924. If no item is selected, or if the text is editable and the user
  29925. has entered something which isn't one of the items in the list, then
  29926. this will return -1.
  29927. @see setSelectedItemIndex, getSelectedId, getText
  29928. */
  29929. int getSelectedItemIndex() const;
  29930. /** Sets one of the items to be the current selection.
  29931. This will set the ComboBox's text to that of the item at the given
  29932. index in the list.
  29933. @param newItemIndex the new item to select
  29934. @param dontSendChangeMessage if set to true, this method won't trigger a
  29935. change notification
  29936. @see getSelectedItemIndex, setSelectedId, setText
  29937. */
  29938. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  29939. /** Returns the text that is currently shown in the combo-box's text field.
  29940. If the ComboBox has editable text, then this text may have been edited
  29941. by the user; otherwise it will be one of the items from the list, or
  29942. possibly an empty string if nothing was selected.
  29943. @see setText, getSelectedId, getSelectedItemIndex
  29944. */
  29945. const String getText() const;
  29946. /** Sets the contents of the combo-box's text field.
  29947. The text passed-in will be set as the current text regardless of whether
  29948. it is one of the items in the list. If the current text isn't one of the
  29949. items, then getSelectedId() will return -1, otherwise it wil return
  29950. the approriate ID.
  29951. @param newText the text to select
  29952. @param dontSendChangeMessage if set to true, this method won't trigger a
  29953. change notification
  29954. @see getText
  29955. */
  29956. void setText (const String& newText, bool dontSendChangeMessage = false);
  29957. /** Programmatically opens the text editor to allow the user to edit the current item.
  29958. This is the same effect as when the box is clicked-on.
  29959. @see Label::showEditor();
  29960. */
  29961. void showEditor();
  29962. /** Pops up the combo box's list. */
  29963. void showPopup();
  29964. /**
  29965. A class for receiving events from a ComboBox.
  29966. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  29967. method, and it will be called when the selected item in the box changes.
  29968. @see ComboBox::addListener, ComboBox::removeListener
  29969. */
  29970. class JUCE_API Listener
  29971. {
  29972. public:
  29973. /** Destructor. */
  29974. virtual ~Listener() {}
  29975. /** Called when a ComboBox has its selected item changed. */
  29976. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  29977. };
  29978. /** Registers a listener that will be called when the box's content changes. */
  29979. void addListener (Listener* listener);
  29980. /** Deregisters a previously-registered listener. */
  29981. void removeListener (Listener* listener);
  29982. /** Sets a message to display when there is no item currently selected.
  29983. @see getTextWhenNothingSelected
  29984. */
  29985. void setTextWhenNothingSelected (const String& newMessage);
  29986. /** Returns the text that is shown when no item is selected.
  29987. @see setTextWhenNothingSelected
  29988. */
  29989. const String getTextWhenNothingSelected() const;
  29990. /** Sets the message to show when there are no items in the list, and the user clicks
  29991. on the drop-down box.
  29992. By default it just says "no choices", but this lets you change it to something more
  29993. meaningful.
  29994. */
  29995. void setTextWhenNoChoicesAvailable (const String& newMessage);
  29996. /** Returns the text shown when no items have been added to the list.
  29997. @see setTextWhenNoChoicesAvailable
  29998. */
  29999. const String getTextWhenNoChoicesAvailable() const;
  30000. /** Gives the ComboBox a tooltip. */
  30001. void setTooltip (const String& newTooltip);
  30002. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  30003. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30004. methods.
  30005. To change the colours of the menu that pops up
  30006. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30007. */
  30008. enum ColourIds
  30009. {
  30010. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  30011. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  30012. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  30013. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  30014. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  30015. };
  30016. /** @internal */
  30017. void labelTextChanged (Label*);
  30018. /** @internal */
  30019. void enablementChanged();
  30020. /** @internal */
  30021. void colourChanged();
  30022. /** @internal */
  30023. void focusGained (Component::FocusChangeType cause);
  30024. /** @internal */
  30025. void focusLost (Component::FocusChangeType cause);
  30026. /** @internal */
  30027. void handleAsyncUpdate();
  30028. /** @internal */
  30029. const String getTooltip() { return label->getTooltip(); }
  30030. /** @internal */
  30031. void mouseDown (const MouseEvent&);
  30032. /** @internal */
  30033. void mouseDrag (const MouseEvent&);
  30034. /** @internal */
  30035. void mouseUp (const MouseEvent&);
  30036. /** @internal */
  30037. void lookAndFeelChanged();
  30038. /** @internal */
  30039. void paint (Graphics&);
  30040. /** @internal */
  30041. void resized();
  30042. /** @internal */
  30043. bool keyStateChanged (bool isKeyDown);
  30044. /** @internal */
  30045. bool keyPressed (const KeyPress&);
  30046. /** @internal */
  30047. void valueChanged (Value&);
  30048. private:
  30049. struct ItemInfo
  30050. {
  30051. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  30052. bool isSeparator() const throw();
  30053. bool isRealItem() const throw();
  30054. String name;
  30055. int itemId;
  30056. bool isEnabled : 1, isHeading : 1;
  30057. };
  30058. class Callback;
  30059. friend class Callback;
  30060. OwnedArray <ItemInfo> items;
  30061. Value currentId;
  30062. int lastCurrentId;
  30063. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  30064. ListenerList <Listener> listeners;
  30065. ScopedPointer<Label> label;
  30066. String textWhenNothingSelected, noChoicesMessage;
  30067. ItemInfo* getItemForId (int itemId) const throw();
  30068. ItemInfo* getItemForIndex (int index) const throw();
  30069. bool selectIfEnabled (int index);
  30070. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  30071. };
  30072. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  30073. typedef ComboBox::Listener ComboBoxListener;
  30074. #if JUCE_VC6
  30075. #undef Listener
  30076. #endif
  30077. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  30078. /*** End of inlined file: juce_ComboBox.h ***/
  30079. /**
  30080. Manages the state of some audio and midi i/o devices.
  30081. This class keeps tracks of a currently-selected audio device, through
  30082. with which it continuously streams data from an audio callback, as well as
  30083. one or more midi inputs.
  30084. The idea is that your application will create one global instance of this object,
  30085. and let it take care of creating and deleting specific types of audio devices
  30086. internally. So when the device is changed, your callbacks will just keep running
  30087. without having to worry about this.
  30088. The manager can save and reload all of its device settings as XML, which
  30089. makes it very easy for you to save and reload the audio setup of your
  30090. application.
  30091. And to make it easy to let the user change its settings, there's a component
  30092. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  30093. device selection/sample-rate/latency controls.
  30094. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  30095. call addAudioCallback() to register your audio callback with it, and use that to process
  30096. your audio data.
  30097. The manager also acts as a handy hub for incoming midi messages, allowing a
  30098. listener to register for messages from either a specific midi device, or from whatever
  30099. the current default midi input device is. The listener then doesn't have to worry about
  30100. re-registering with different midi devices if they are changed or deleted.
  30101. And yet another neat trick is that amount of CPU time being used is measured and
  30102. available with the getCpuUsage() method.
  30103. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  30104. listeners whenever one of its settings is changed.
  30105. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  30106. */
  30107. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  30108. {
  30109. public:
  30110. /** Creates a default AudioDeviceManager.
  30111. Initially no audio device will be selected. You should call the initialise() method
  30112. and register an audio callback with setAudioCallback() before it'll be able to
  30113. actually make any noise.
  30114. */
  30115. AudioDeviceManager();
  30116. /** Destructor. */
  30117. ~AudioDeviceManager();
  30118. /**
  30119. This structure holds a set of properties describing the current audio setup.
  30120. An AudioDeviceManager uses this class to save/load its current settings, and to
  30121. specify your preferred options when opening a device.
  30122. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  30123. */
  30124. struct JUCE_API AudioDeviceSetup
  30125. {
  30126. /** Creates an AudioDeviceSetup object.
  30127. The default constructor sets all the member variables to indicate default values.
  30128. You can then fill-in any values you want to before passing the object to
  30129. AudioDeviceManager::initialise().
  30130. */
  30131. AudioDeviceSetup();
  30132. bool operator== (const AudioDeviceSetup& other) const;
  30133. /** The name of the audio device used for output.
  30134. The name has to be one of the ones listed by the AudioDeviceManager's currently
  30135. selected device type.
  30136. This may be the same as the input device.
  30137. An empty string indicates the default device.
  30138. */
  30139. String outputDeviceName;
  30140. /** The name of the audio device used for input.
  30141. This may be the same as the output device.
  30142. An empty string indicates the default device.
  30143. */
  30144. String inputDeviceName;
  30145. /** The current sample rate.
  30146. This rate is used for both the input and output devices.
  30147. A value of 0 indicates the default rate.
  30148. */
  30149. double sampleRate;
  30150. /** The buffer size, in samples.
  30151. This buffer size is used for both the input and output devices.
  30152. A value of 0 indicates the default buffer size.
  30153. */
  30154. int bufferSize;
  30155. /** The set of active input channels.
  30156. The bits that are set in this array indicate the channels of the
  30157. input device that are active.
  30158. If useDefaultInputChannels is true, this value is ignored.
  30159. */
  30160. BigInteger inputChannels;
  30161. /** If this is true, it indicates that the inputChannels array
  30162. should be ignored, and instead, the device's default channels
  30163. should be used.
  30164. */
  30165. bool useDefaultInputChannels;
  30166. /** The set of active output channels.
  30167. The bits that are set in this array indicate the channels of the
  30168. input device that are active.
  30169. If useDefaultOutputChannels is true, this value is ignored.
  30170. */
  30171. BigInteger outputChannels;
  30172. /** If this is true, it indicates that the outputChannels array
  30173. should be ignored, and instead, the device's default channels
  30174. should be used.
  30175. */
  30176. bool useDefaultOutputChannels;
  30177. };
  30178. /** Opens a set of audio devices ready for use.
  30179. This will attempt to open either a default audio device, or one that was
  30180. previously saved as XML.
  30181. @param numInputChannelsNeeded a minimum number of input channels needed
  30182. by your app.
  30183. @param numOutputChannelsNeeded a minimum number of output channels to open
  30184. @param savedState either a previously-saved state that was produced
  30185. by createStateXml(), or 0 if you want the manager
  30186. to choose the best device to open.
  30187. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  30188. fails to open, then a default device will be used
  30189. instead. If false, then on failure, no device is
  30190. opened.
  30191. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  30192. name, then that will be used as the default device
  30193. (assuming that there wasn't one specified in the XML).
  30194. The string can actually be a simple wildcard, containing "*"
  30195. and "?" characters
  30196. @param preferredSetupOptions if this is non-null, the structure will be used as the
  30197. set of preferred settings when opening the device. If you
  30198. use this parameter, the preferredDefaultDeviceName
  30199. field will be ignored
  30200. @returns an error message if anything went wrong, or an empty string if it worked ok.
  30201. */
  30202. const String initialise (int numInputChannelsNeeded,
  30203. int numOutputChannelsNeeded,
  30204. const XmlElement* savedState,
  30205. bool selectDefaultDeviceOnFailure,
  30206. const String& preferredDefaultDeviceName = String::empty,
  30207. const AudioDeviceSetup* preferredSetupOptions = 0);
  30208. /** Returns some XML representing the current state of the manager.
  30209. This stores the current device, its samplerate, block size, etc, and
  30210. can be restored later with initialise().
  30211. */
  30212. XmlElement* createStateXml() const;
  30213. /** Returns the current device properties that are in use.
  30214. @see setAudioDeviceSetup
  30215. */
  30216. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  30217. /** Changes the current device or its settings.
  30218. If you want to change a device property, like the current sample rate or
  30219. block size, you can call getAudioDeviceSetup() to retrieve the current
  30220. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  30221. and pass it back into this method to apply the new settings.
  30222. @param newSetup the settings that you'd like to use
  30223. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  30224. settings will be taken as having been explicitly chosen by the
  30225. user, and the next time createStateXml() is called, these settings
  30226. will be returned. If it's false, then the device is treated as a
  30227. temporary or default device, and a call to createStateXml() will
  30228. return either the last settings that were made with treatAsChosenDevice
  30229. as true, or the last XML settings that were passed into initialise().
  30230. @returns an error message if anything went wrong, or an empty string if it worked ok.
  30231. @see getAudioDeviceSetup
  30232. */
  30233. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  30234. bool treatAsChosenDevice);
  30235. /** Returns the currently-active audio device. */
  30236. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  30237. /** Returns the type of audio device currently in use.
  30238. @see setCurrentAudioDeviceType
  30239. */
  30240. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  30241. /** Returns the currently active audio device type object.
  30242. Don't keep a copy of this pointer - it's owned by the device manager and could
  30243. change at any time.
  30244. */
  30245. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  30246. /** Changes the class of audio device being used.
  30247. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  30248. this because there's only one type: CoreAudio.
  30249. For a list of types, see getAvailableDeviceTypes().
  30250. */
  30251. void setCurrentAudioDeviceType (const String& type,
  30252. bool treatAsChosenDevice);
  30253. /** Closes the currently-open device.
  30254. You can call restartLastAudioDevice() later to reopen it in the same state
  30255. that it was just in.
  30256. */
  30257. void closeAudioDevice();
  30258. /** Tries to reload the last audio device that was running.
  30259. Note that this only reloads the last device that was running before
  30260. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  30261. and can only be called after a device has been opened with SetAudioDevice().
  30262. If a device is already open, this call will do nothing.
  30263. */
  30264. void restartLastAudioDevice();
  30265. /** Registers an audio callback to be used.
  30266. The manager will redirect callbacks from whatever audio device is currently
  30267. in use to all registered callback objects. If more than one callback is
  30268. active, they will all be given the same input data, and their outputs will
  30269. be summed.
  30270. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  30271. object before returning.
  30272. To remove a callback, use removeAudioCallback().
  30273. */
  30274. void addAudioCallback (AudioIODeviceCallback* newCallback);
  30275. /** Deregisters a previously added callback.
  30276. If necessary, this method will invoke audioDeviceStopped() on the callback
  30277. object before returning.
  30278. @see addAudioCallback
  30279. */
  30280. void removeAudioCallback (AudioIODeviceCallback* callback);
  30281. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  30282. Returns a value between 0 and 1.0
  30283. */
  30284. double getCpuUsage() const;
  30285. /** Enables or disables a midi input device.
  30286. The list of devices can be obtained with the MidiInput::getDevices() method.
  30287. Any incoming messages from enabled input devices will be forwarded on to all the
  30288. listeners that have been registered with the addMidiInputCallback() method. They
  30289. can either register for messages from a particular device, or from just the
  30290. "default" midi input.
  30291. Routing the midi input via an AudioDeviceManager means that when a listener
  30292. registers for the default midi input, this default device can be changed by the
  30293. manager without the listeners having to know about it or re-register.
  30294. It also means that a listener can stay registered for a midi input that is disabled
  30295. or not present, so that when the input is re-enabled, the listener will start
  30296. receiving messages again.
  30297. @see addMidiInputCallback, isMidiInputEnabled
  30298. */
  30299. void setMidiInputEnabled (const String& midiInputDeviceName,
  30300. bool enabled);
  30301. /** Returns true if a given midi input device is being used.
  30302. @see setMidiInputEnabled
  30303. */
  30304. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  30305. /** Registers a listener for callbacks when midi events arrive from a midi input.
  30306. The device name can be empty to indicate that it wants events from whatever the
  30307. current "default" device is. Or it can be the name of one of the midi input devices
  30308. (see MidiInput::getDevices() for the names).
  30309. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  30310. events forwarded on to listeners.
  30311. */
  30312. void addMidiInputCallback (const String& midiInputDeviceName,
  30313. MidiInputCallback* callback);
  30314. /** Removes a listener that was previously registered with addMidiInputCallback().
  30315. */
  30316. void removeMidiInputCallback (const String& midiInputDeviceName,
  30317. MidiInputCallback* callback);
  30318. /** Sets a midi output device to use as the default.
  30319. The list of devices can be obtained with the MidiOutput::getDevices() method.
  30320. The specified device will be opened automatically and can be retrieved with the
  30321. getDefaultMidiOutput() method.
  30322. Pass in an empty string to deselect all devices. For the default device, you
  30323. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  30324. @see getDefaultMidiOutput, getDefaultMidiOutputName
  30325. */
  30326. void setDefaultMidiOutput (const String& deviceName);
  30327. /** Returns the name of the default midi output.
  30328. @see setDefaultMidiOutput, getDefaultMidiOutput
  30329. */
  30330. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  30331. /** Returns the current default midi output device.
  30332. If no device has been selected, or the device can't be opened, this will
  30333. return 0.
  30334. @see getDefaultMidiOutputName
  30335. */
  30336. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  30337. /** Returns a list of the types of device supported.
  30338. */
  30339. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  30340. /** Creates a list of available types.
  30341. This will add a set of new AudioIODeviceType objects to the specified list, to
  30342. represent each available types of device.
  30343. You can override this if your app needs to do something specific, like avoid
  30344. using DirectSound devices, etc.
  30345. */
  30346. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  30347. /** Plays a beep through the current audio device.
  30348. This is here to allow the audio setup UI panels to easily include a "test"
  30349. button so that the user can check where the audio is coming from.
  30350. */
  30351. void playTestSound();
  30352. /** Turns on level-measuring.
  30353. When enabled, the device manager will measure the peak input level
  30354. across all channels, and you can get this level by calling getCurrentInputLevel().
  30355. This is mainly intended for audio setup UI panels to use to create a mic
  30356. level display, so that the user can check that they've selected the right
  30357. device.
  30358. A simple filter is used to make the level decay smoothly, but this is
  30359. only intended for giving rough feedback, and not for any kind of accurate
  30360. measurement.
  30361. */
  30362. void enableInputLevelMeasurement (bool enableMeasurement);
  30363. /** Returns the current input level.
  30364. To use this, you must first enable it by calling enableInputLevelMeasurement().
  30365. See enableInputLevelMeasurement() for more info.
  30366. */
  30367. double getCurrentInputLevel() const;
  30368. /** Returns the a lock that can be used to synchronise access to the audio callback.
  30369. Obviously while this is locked, you're blocking the audio thread from running, so
  30370. it must only be used for very brief periods when absolutely necessary.
  30371. */
  30372. CriticalSection& getAudioCallbackLock() throw() { return audioCallbackLock; }
  30373. /** Returns the a lock that can be used to synchronise access to the midi callback.
  30374. Obviously while this is locked, you're blocking the midi system from running, so
  30375. it must only be used for very brief periods when absolutely necessary.
  30376. */
  30377. CriticalSection& getMidiCallbackLock() throw() { return midiCallbackLock; }
  30378. private:
  30379. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  30380. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  30381. AudioDeviceSetup currentSetup;
  30382. ScopedPointer <AudioIODevice> currentAudioDevice;
  30383. SortedSet <AudioIODeviceCallback*> callbacks;
  30384. int numInputChansNeeded, numOutputChansNeeded;
  30385. String currentDeviceType;
  30386. BigInteger inputChannels, outputChannels;
  30387. ScopedPointer <XmlElement> lastExplicitSettings;
  30388. mutable bool listNeedsScanning;
  30389. bool useInputNames;
  30390. int inputLevelMeasurementEnabledCount;
  30391. double inputLevel;
  30392. ScopedPointer <AudioSampleBuffer> testSound;
  30393. int testSoundPosition;
  30394. AudioSampleBuffer tempBuffer;
  30395. StringArray midiInsFromXml;
  30396. OwnedArray <MidiInput> enabledMidiInputs;
  30397. Array <MidiInputCallback*> midiCallbacks;
  30398. Array <MidiInput*> midiCallbackDevices;
  30399. String defaultMidiOutputName;
  30400. ScopedPointer <MidiOutput> defaultMidiOutput;
  30401. CriticalSection audioCallbackLock, midiCallbackLock;
  30402. double cpuUsageMs, timeToCpuScale;
  30403. class CallbackHandler : public AudioIODeviceCallback,
  30404. public MidiInputCallback
  30405. {
  30406. public:
  30407. AudioDeviceManager* owner;
  30408. void audioDeviceIOCallback (const float** inputChannelData,
  30409. int totalNumInputChannels,
  30410. float** outputChannelData,
  30411. int totalNumOutputChannels,
  30412. int numSamples);
  30413. void audioDeviceAboutToStart (AudioIODevice*);
  30414. void audioDeviceStopped();
  30415. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  30416. };
  30417. CallbackHandler callbackHandler;
  30418. friend class CallbackHandler;
  30419. void audioDeviceIOCallbackInt (const float** inputChannelData,
  30420. int totalNumInputChannels,
  30421. float** outputChannelData,
  30422. int totalNumOutputChannels,
  30423. int numSamples);
  30424. void audioDeviceAboutToStartInt (AudioIODevice* device);
  30425. void audioDeviceStoppedInt();
  30426. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  30427. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  30428. const BigInteger& ins, const BigInteger& outs);
  30429. void stopDevice();
  30430. void updateXml();
  30431. void createDeviceTypesIfNeeded();
  30432. void scanDevicesIfNeeded();
  30433. void deleteCurrentDevice();
  30434. double chooseBestSampleRate (double preferred) const;
  30435. int chooseBestBufferSize (int preferred) const;
  30436. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  30437. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  30438. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  30439. };
  30440. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  30441. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  30442. #endif
  30443. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  30444. #endif
  30445. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  30446. #endif
  30447. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  30448. #endif
  30449. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  30450. #endif
  30451. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  30452. #endif
  30453. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  30454. #endif
  30455. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  30456. /*** Start of inlined file: juce_Decibels.h ***/
  30457. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  30458. #define __JUCE_DECIBELS_JUCEHEADER__
  30459. /**
  30460. This class contains some helpful static methods for dealing with decibel values.
  30461. */
  30462. class Decibels
  30463. {
  30464. public:
  30465. /** Converts a dBFS value to its equivalent gain level.
  30466. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  30467. decibel value lower than minusInfinityDb will return a gain of 0.
  30468. */
  30469. template <typename Type>
  30470. static Type decibelsToGain (const Type decibels,
  30471. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  30472. {
  30473. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  30474. : Type();
  30475. }
  30476. /** Converts a gain level into a dBFS value.
  30477. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  30478. If the gain is 0 (or negative), then the method will return the value
  30479. provided as minusInfinityDb.
  30480. */
  30481. template <typename Type>
  30482. static Type gainToDecibels (const Type gain,
  30483. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  30484. {
  30485. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log (gain) * (Type) 20.0)
  30486. : minusInfinityDb;
  30487. }
  30488. /** Converts a decibel reading to a string, with the 'dB' suffix.
  30489. If the decibel value is lower than minusInfinityDb, the return value will
  30490. be "-INF dB".
  30491. */
  30492. template <typename Type>
  30493. static const String toString (const Type decibels,
  30494. const int decimalPlaces = 2,
  30495. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  30496. {
  30497. String s;
  30498. if (decibels <= minusInfinityDb)
  30499. {
  30500. s = "-INF dB";
  30501. }
  30502. else
  30503. {
  30504. if (decibels >= Type())
  30505. s << '+';
  30506. s << String (decibels, decimalPlaces) << " dB";
  30507. }
  30508. return s;
  30509. }
  30510. private:
  30511. enum
  30512. {
  30513. defaultMinusInfinitydB = -100
  30514. };
  30515. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  30516. JUCE_DECLARE_NON_COPYABLE (Decibels);
  30517. };
  30518. #endif // __JUCE_DECIBELS_JUCEHEADER__
  30519. /*** End of inlined file: juce_Decibels.h ***/
  30520. #endif
  30521. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  30522. #endif
  30523. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  30524. #endif
  30525. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  30526. /*** Start of inlined file: juce_MidiFile.h ***/
  30527. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  30528. #define __JUCE_MIDIFILE_JUCEHEADER__
  30529. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  30530. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  30531. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  30532. /**
  30533. A sequence of timestamped midi messages.
  30534. This allows the sequence to be manipulated, and also to be read from and
  30535. written to a standard midi file.
  30536. @see MidiMessage, MidiFile
  30537. */
  30538. class JUCE_API MidiMessageSequence
  30539. {
  30540. public:
  30541. /** Creates an empty midi sequence object. */
  30542. MidiMessageSequence();
  30543. /** Creates a copy of another sequence. */
  30544. MidiMessageSequence (const MidiMessageSequence& other);
  30545. /** Replaces this sequence with another one. */
  30546. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  30547. /** Destructor. */
  30548. ~MidiMessageSequence();
  30549. /** Structure used to hold midi events in the sequence.
  30550. These structures act as 'handles' on the events as they are moved about in
  30551. the list, and make it quick to find the matching note-offs for note-on events.
  30552. @see MidiMessageSequence::getEventPointer
  30553. */
  30554. class MidiEventHolder
  30555. {
  30556. public:
  30557. /** Destructor. */
  30558. ~MidiEventHolder();
  30559. /** The message itself, whose timestamp is used to specify the event's time.
  30560. */
  30561. MidiMessage message;
  30562. /** The matching note-off event (if this is a note-on event).
  30563. If this isn't a note-on, this pointer will be null.
  30564. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  30565. note-offs up-to-date after events have been moved around in the sequence
  30566. or deleted.
  30567. */
  30568. MidiEventHolder* noteOffObject;
  30569. private:
  30570. friend class MidiMessageSequence;
  30571. MidiEventHolder (const MidiMessage& message);
  30572. JUCE_LEAK_DETECTOR (MidiEventHolder);
  30573. };
  30574. /** Clears the sequence. */
  30575. void clear();
  30576. /** Returns the number of events in the sequence. */
  30577. int getNumEvents() const;
  30578. /** Returns a pointer to one of the events. */
  30579. MidiEventHolder* getEventPointer (int index) const;
  30580. /** Returns the time of the note-up that matches the note-on at this index.
  30581. If the event at this index isn't a note-on, it'll just return 0.
  30582. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  30583. */
  30584. double getTimeOfMatchingKeyUp (int index) const;
  30585. /** Returns the index of the note-up that matches the note-on at this index.
  30586. If the event at this index isn't a note-on, it'll just return -1.
  30587. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  30588. */
  30589. int getIndexOfMatchingKeyUp (int index) const;
  30590. /** Returns the index of an event. */
  30591. int getIndexOf (MidiEventHolder* event) const;
  30592. /** Returns the index of the first event on or after the given timestamp.
  30593. If the time is beyond the end of the sequence, this will return the
  30594. number of events.
  30595. */
  30596. int getNextIndexAtTime (double timeStamp) const;
  30597. /** Returns the timestamp of the first event in the sequence.
  30598. @see getEndTime
  30599. */
  30600. double getStartTime() const;
  30601. /** Returns the timestamp of the last event in the sequence.
  30602. @see getStartTime
  30603. */
  30604. double getEndTime() const;
  30605. /** Returns the timestamp of the event at a given index.
  30606. If the index is out-of-range, this will return 0.0
  30607. */
  30608. double getEventTime (int index) const;
  30609. /** Inserts a midi message into the sequence.
  30610. The index at which the new message gets inserted will depend on its timestamp,
  30611. because the sequence is kept sorted.
  30612. Remember to call updateMatchedPairs() after adding note-on events.
  30613. @param newMessage the new message to add (an internal copy will be made)
  30614. @param timeAdjustment an optional value to add to the timestamp of the message
  30615. that will be inserted
  30616. @see updateMatchedPairs
  30617. */
  30618. void addEvent (const MidiMessage& newMessage,
  30619. double timeAdjustment = 0);
  30620. /** Deletes one of the events in the sequence.
  30621. Remember to call updateMatchedPairs() after removing events.
  30622. @param index the index of the event to delete
  30623. @param deleteMatchingNoteUp whether to also remove the matching note-off
  30624. if the event you're removing is a note-on
  30625. */
  30626. void deleteEvent (int index, bool deleteMatchingNoteUp);
  30627. /** Merges another sequence into this one.
  30628. Remember to call updateMatchedPairs() after using this method.
  30629. @param other the sequence to add from
  30630. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  30631. as they are read from the other sequence
  30632. @param firstAllowableDestTime events will not be added if their time is earlier
  30633. than this time. (This is after their time has been adjusted
  30634. by the timeAdjustmentDelta)
  30635. @param endOfAllowableDestTimes events will not be added if their time is equal to
  30636. or greater than this time. (This is after their time has
  30637. been adjusted by the timeAdjustmentDelta)
  30638. */
  30639. void addSequence (const MidiMessageSequence& other,
  30640. double timeAdjustmentDelta,
  30641. double firstAllowableDestTime,
  30642. double endOfAllowableDestTimes);
  30643. /** Makes sure all the note-on and note-off pairs are up-to-date.
  30644. Call this after moving messages about or deleting/adding messages, and it
  30645. will scan the list and make sure all the note-offs in the MidiEventHolder
  30646. structures are pointing at the correct ones.
  30647. */
  30648. void updateMatchedPairs();
  30649. /** Copies all the messages for a particular midi channel to another sequence.
  30650. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  30651. @param destSequence the sequence that the chosen events should be copied to
  30652. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  30653. channel) will also be copied across.
  30654. @see extractSysExMessages
  30655. */
  30656. void extractMidiChannelMessages (int channelNumberToExtract,
  30657. MidiMessageSequence& destSequence,
  30658. bool alsoIncludeMetaEvents) const;
  30659. /** Copies all midi sys-ex messages to another sequence.
  30660. @param destSequence this is the sequence to which any sys-exes in this sequence
  30661. will be added
  30662. @see extractMidiChannelMessages
  30663. */
  30664. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  30665. /** Removes any messages in this sequence that have a specific midi channel.
  30666. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  30667. */
  30668. void deleteMidiChannelMessages (int channelNumberToRemove);
  30669. /** Removes any sys-ex messages from this sequence.
  30670. */
  30671. void deleteSysExMessages();
  30672. /** Adds an offset to the timestamps of all events in the sequence.
  30673. @param deltaTime the amount to add to each timestamp.
  30674. */
  30675. void addTimeToMessages (double deltaTime);
  30676. /** Scans through the sequence to determine the state of any midi controllers at
  30677. a given time.
  30678. This will create a sequence of midi controller changes that can be
  30679. used to set all midi controllers to the state they would be in at the
  30680. specified time within this sequence.
  30681. As well as controllers, it will also recreate the midi program number
  30682. and pitch bend position.
  30683. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  30684. for other channels will be ignored.
  30685. @param time the time at which you want to find out the state - there are
  30686. no explicit units for this time measurement, it's the same units
  30687. as used for the timestamps of the messages
  30688. @param resultMessages an array to which midi controller-change messages will be added. This
  30689. will be the minimum number of controller changes to recreate the
  30690. state at the required time.
  30691. */
  30692. void createControllerUpdatesForTime (int channelNumber, double time,
  30693. OwnedArray<MidiMessage>& resultMessages);
  30694. /** Swaps this sequence with another one. */
  30695. void swapWith (MidiMessageSequence& other) throw();
  30696. /** @internal */
  30697. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  30698. const MidiMessageSequence::MidiEventHolder* second) throw();
  30699. private:
  30700. friend class MidiFile;
  30701. OwnedArray <MidiEventHolder> list;
  30702. void sort();
  30703. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  30704. };
  30705. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  30706. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  30707. /**
  30708. Reads/writes standard midi format files.
  30709. To read a midi file, create a MidiFile object and call its readFrom() method. You
  30710. can then get the individual midi tracks from it using the getTrack() method.
  30711. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  30712. to it using the addTrack() method, and then call its writeTo() method to stream
  30713. it out.
  30714. @see MidiMessageSequence
  30715. */
  30716. class JUCE_API MidiFile
  30717. {
  30718. public:
  30719. /** Creates an empty MidiFile object.
  30720. */
  30721. MidiFile();
  30722. /** Destructor. */
  30723. ~MidiFile();
  30724. /** Returns the number of tracks in the file.
  30725. @see getTrack, addTrack
  30726. */
  30727. int getNumTracks() const throw();
  30728. /** Returns a pointer to one of the tracks in the file.
  30729. @returns a pointer to the track, or 0 if the index is out-of-range
  30730. @see getNumTracks, addTrack
  30731. */
  30732. const MidiMessageSequence* getTrack (int index) const throw();
  30733. /** Adds a midi track to the file.
  30734. This will make its own internal copy of the sequence that is passed-in.
  30735. @see getNumTracks, getTrack
  30736. */
  30737. void addTrack (const MidiMessageSequence& trackSequence);
  30738. /** Removes all midi tracks from the file.
  30739. @see getNumTracks
  30740. */
  30741. void clear();
  30742. /** Returns the raw time format code that will be written to a stream.
  30743. After reading a midi file, this method will return the time-format that
  30744. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  30745. or setSmpteTimeFormat() methods.
  30746. If the value returned is positive, it indicates the number of midi ticks
  30747. per quarter-note - see setTicksPerQuarterNote().
  30748. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  30749. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  30750. */
  30751. short getTimeFormat() const throw();
  30752. /** Sets the time format to use when this file is written to a stream.
  30753. If this is called, the file will be written as bars/beats using the
  30754. specified resolution, rather than SMPTE absolute times, as would be
  30755. used if setSmpteTimeFormat() had been called instead.
  30756. @param ticksPerQuarterNote e.g. 96, 960
  30757. @see setSmpteTimeFormat
  30758. */
  30759. void setTicksPerQuarterNote (int ticksPerQuarterNote) throw();
  30760. /** Sets the time format to use when this file is written to a stream.
  30761. If this is called, the file will be written using absolute times, rather
  30762. than bars/beats as would be the case if setTicksPerBeat() had been called
  30763. instead.
  30764. @param framesPerSecond must be 24, 25, 29 or 30
  30765. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  30766. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  30767. timing, setSmpteTimeFormat (25, 40)
  30768. @see setTicksPerBeat
  30769. */
  30770. void setSmpteTimeFormat (int framesPerSecond,
  30771. int subframeResolution) throw();
  30772. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  30773. Useful for finding the positions of all the tempo changes in a file.
  30774. @param tempoChangeEvents a list to which all the events will be added
  30775. */
  30776. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  30777. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  30778. Useful for finding the positions of all the tempo changes in a file.
  30779. @param timeSigEvents a list to which all the events will be added
  30780. */
  30781. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  30782. /** Returns the latest timestamp in any of the tracks.
  30783. (Useful for finding the length of the file).
  30784. */
  30785. double getLastTimestamp() const;
  30786. /** Reads a midi file format stream.
  30787. After calling this, you can get the tracks that were read from the file by using the
  30788. getNumTracks() and getTrack() methods.
  30789. The timestamps of the midi events in the tracks will represent their positions in
  30790. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  30791. method.
  30792. @returns true if the stream was read successfully
  30793. */
  30794. bool readFrom (InputStream& sourceStream);
  30795. /** Writes the midi tracks as a standard midi file.
  30796. @returns true if the operation succeeded.
  30797. */
  30798. bool writeTo (OutputStream& destStream);
  30799. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  30800. This will use the midi time format and tempo/time signature info in the
  30801. tracks to convert all the timestamps to absolute values in seconds.
  30802. */
  30803. void convertTimestampTicksToSeconds();
  30804. private:
  30805. OwnedArray <MidiMessageSequence> tracks;
  30806. short timeFormat;
  30807. void readNextTrack (const uint8* data, int size);
  30808. void writeTrack (OutputStream& mainOut, int trackNum);
  30809. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  30810. };
  30811. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  30812. /*** End of inlined file: juce_MidiFile.h ***/
  30813. #endif
  30814. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  30815. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  30816. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  30817. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  30818. class MidiKeyboardState;
  30819. /**
  30820. Receives events from a MidiKeyboardState object.
  30821. @see MidiKeyboardState
  30822. */
  30823. class JUCE_API MidiKeyboardStateListener
  30824. {
  30825. public:
  30826. MidiKeyboardStateListener() throw() {}
  30827. virtual ~MidiKeyboardStateListener() {}
  30828. /** Called when one of the MidiKeyboardState's keys is pressed.
  30829. This will be called synchronously when the state is either processing a
  30830. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  30831. when a note is being played with its MidiKeyboardState::noteOn() method.
  30832. Note that this callback could happen from an audio callback thread, so be
  30833. careful not to block, and avoid any UI activity in the callback.
  30834. */
  30835. virtual void handleNoteOn (MidiKeyboardState* source,
  30836. int midiChannel, int midiNoteNumber, float velocity) = 0;
  30837. /** Called when one of the MidiKeyboardState's keys is released.
  30838. This will be called synchronously when the state is either processing a
  30839. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  30840. when a note is being played with its MidiKeyboardState::noteOff() method.
  30841. Note that this callback could happen from an audio callback thread, so be
  30842. careful not to block, and avoid any UI activity in the callback.
  30843. */
  30844. virtual void handleNoteOff (MidiKeyboardState* source,
  30845. int midiChannel, int midiNoteNumber) = 0;
  30846. };
  30847. /**
  30848. Represents a piano keyboard, keeping track of which keys are currently pressed.
  30849. This object can parse a stream of midi events, using them to update its idea
  30850. of which keys are pressed for each individiual midi channel.
  30851. When keys go up or down, it can broadcast these events to listener objects.
  30852. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  30853. methods, and midi messages for these events will be merged into the
  30854. midi stream that gets processed by processNextMidiBuffer().
  30855. */
  30856. class JUCE_API MidiKeyboardState
  30857. {
  30858. public:
  30859. MidiKeyboardState();
  30860. ~MidiKeyboardState();
  30861. /** Resets the state of the object.
  30862. All internal data for all the channels is reset, but no events are sent as a
  30863. result.
  30864. If you want to release any keys that are currently down, and to send out note-up
  30865. midi messages for this, use the allNotesOff() method instead.
  30866. */
  30867. void reset();
  30868. /** Returns true if the given midi key is currently held down for the given midi channel.
  30869. The channel number must be between 1 and 16. If you want to see if any notes are
  30870. on for a range of channels, use the isNoteOnForChannels() method.
  30871. */
  30872. bool isNoteOn (int midiChannel, int midiNoteNumber) const throw();
  30873. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  30874. The channel mask has a bit set for each midi channel you want to test for - bit
  30875. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  30876. If a note is on for at least one of the specified channels, this returns true.
  30877. */
  30878. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const throw();
  30879. /** Turns a specified note on.
  30880. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  30881. next call to processNextMidiBuffer().
  30882. It will also trigger a synchronous callback to the listeners to tell them that the key has
  30883. gone down.
  30884. */
  30885. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  30886. /** Turns a specified note off.
  30887. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  30888. next call to processNextMidiBuffer().
  30889. It will also trigger a synchronous callback to the listeners to tell them that the key has
  30890. gone up.
  30891. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  30892. */
  30893. void noteOff (int midiChannel, int midiNoteNumber);
  30894. /** This will turn off any currently-down notes for the given midi channel.
  30895. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  30896. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  30897. and events being added to the midi stream.
  30898. */
  30899. void allNotesOff (int midiChannel);
  30900. /** Looks at a key-up/down event and uses it to update the state of this object.
  30901. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  30902. instead.
  30903. */
  30904. void processNextMidiEvent (const MidiMessage& message);
  30905. /** Scans a midi stream for up/down events and adds its own events to it.
  30906. This will look for any up/down events and use them to update the internal state,
  30907. synchronously making suitable callbacks to the listeners.
  30908. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  30909. and noteOff() calls will be added into the buffer.
  30910. Only the section of the buffer whose timestamps are between startSample and
  30911. (startSample + numSamples) will be affected, and any events added will be placed
  30912. between these times.
  30913. If you're going to use this method, you'll need to keep calling it regularly for
  30914. it to work satisfactorily.
  30915. To process a single midi event at a time, use the processNextMidiEvent() method
  30916. instead.
  30917. */
  30918. void processNextMidiBuffer (MidiBuffer& buffer,
  30919. int startSample,
  30920. int numSamples,
  30921. bool injectIndirectEvents);
  30922. /** Registers a listener for callbacks when keys go up or down.
  30923. @see removeListener
  30924. */
  30925. void addListener (MidiKeyboardStateListener* listener);
  30926. /** Deregisters a listener.
  30927. @see addListener
  30928. */
  30929. void removeListener (MidiKeyboardStateListener* listener);
  30930. private:
  30931. CriticalSection lock;
  30932. uint16 noteStates [128];
  30933. MidiBuffer eventsToAdd;
  30934. Array <MidiKeyboardStateListener*> listeners;
  30935. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  30936. void noteOffInternal (int midiChannel, int midiNoteNumber);
  30937. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  30938. };
  30939. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  30940. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  30941. #endif
  30942. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  30943. #endif
  30944. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  30945. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  30946. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  30947. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  30948. /**
  30949. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  30950. processing by a block-based audio callback.
  30951. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  30952. so it can easily use a midi input or keyboard component as its source.
  30953. @see MidiMessage, MidiInput
  30954. */
  30955. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  30956. public MidiInputCallback
  30957. {
  30958. public:
  30959. /** Creates a MidiMessageCollector. */
  30960. MidiMessageCollector();
  30961. /** Destructor. */
  30962. ~MidiMessageCollector();
  30963. /** Clears any messages from the queue.
  30964. You need to call this method before starting to use the collector, so that
  30965. it knows the correct sample rate to use.
  30966. */
  30967. void reset (double sampleRate);
  30968. /** Takes an incoming real-time message and adds it to the queue.
  30969. The message's timestamp is taken, and it will be ready for retrieval as part
  30970. of the block returned by the next call to removeNextBlockOfMessages().
  30971. This method is fully thread-safe when overlapping calls are made with
  30972. removeNextBlockOfMessages().
  30973. */
  30974. void addMessageToQueue (const MidiMessage& message);
  30975. /** Removes all the pending messages from the queue as a buffer.
  30976. This will also correct the messages' timestamps to make sure they're in
  30977. the range 0 to numSamples - 1.
  30978. This call should be made regularly by something like an audio processing
  30979. callback, because the time that it happens is used in calculating the
  30980. midi event positions.
  30981. This method is fully thread-safe when overlapping calls are made with
  30982. addMessageToQueue().
  30983. */
  30984. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  30985. /** @internal */
  30986. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  30987. /** @internal */
  30988. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  30989. /** @internal */
  30990. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  30991. private:
  30992. double lastCallbackTime;
  30993. CriticalSection midiCallbackLock;
  30994. MidiBuffer incomingMessages;
  30995. double sampleRate;
  30996. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  30997. };
  30998. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  30999. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  31000. #endif
  31001. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  31002. #endif
  31003. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  31004. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  31005. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  31006. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  31007. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  31008. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  31009. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  31010. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  31011. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  31012. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  31013. /*** Start of inlined file: juce_AudioProcessor.h ***/
  31014. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  31015. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  31016. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  31017. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  31018. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  31019. class AudioProcessor;
  31020. /**
  31021. Base class for the component that acts as the GUI for an AudioProcessor.
  31022. Derive your editor component from this class, and create an instance of it
  31023. by overriding the AudioProcessor::createEditor() method.
  31024. @see AudioProcessor, GenericAudioProcessorEditor
  31025. */
  31026. class JUCE_API AudioProcessorEditor : public Component
  31027. {
  31028. protected:
  31029. /** Creates an editor for the specified processor.
  31030. */
  31031. AudioProcessorEditor (AudioProcessor* owner);
  31032. public:
  31033. /** Destructor. */
  31034. ~AudioProcessorEditor();
  31035. /** Returns a pointer to the processor that this editor represents. */
  31036. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  31037. private:
  31038. AudioProcessor* const owner;
  31039. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  31040. };
  31041. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  31042. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  31043. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  31044. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  31045. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  31046. class AudioProcessor;
  31047. /**
  31048. Base class for listeners that want to know about changes to an AudioProcessor.
  31049. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  31050. @see AudioProcessor
  31051. */
  31052. class JUCE_API AudioProcessorListener
  31053. {
  31054. public:
  31055. /** Destructor. */
  31056. virtual ~AudioProcessorListener() {}
  31057. /** Receives a callback when a parameter is changed.
  31058. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  31059. many audio processors will change their parameter during their audio callback.
  31060. This means that not only has your handler code got to be completely thread-safe,
  31061. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  31062. this event on your message thread, use this callback to trigger an AsyncUpdater
  31063. or ChangeBroadcaster which you can respond to on the message thread.
  31064. */
  31065. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  31066. int parameterIndex,
  31067. float newValue) = 0;
  31068. /** Called to indicate that something else in the plugin has changed, like its
  31069. program, number of parameters, etc.
  31070. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  31071. call it during their audio callback. This means that not only has your handler code
  31072. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  31073. blocking. If you need to handle this event on your message thread, use this callback
  31074. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  31075. message thread.
  31076. */
  31077. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  31078. /** Indicates that a parameter change gesture has started.
  31079. E.g. if the user is dragging a slider, this would be called when they first
  31080. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  31081. called when they release it.
  31082. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  31083. call it during their audio callback. This means that not only has your handler code
  31084. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  31085. blocking. If you need to handle this event on your message thread, use this callback
  31086. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  31087. message thread.
  31088. @see audioProcessorParameterChangeGestureEnd
  31089. */
  31090. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  31091. int parameterIndex);
  31092. /** Indicates that a parameter change gesture has finished.
  31093. E.g. if the user is dragging a slider, this would be called when they release
  31094. the mouse button.
  31095. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  31096. call it during their audio callback. This means that not only has your handler code
  31097. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  31098. blocking. If you need to handle this event on your message thread, use this callback
  31099. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  31100. message thread.
  31101. @see audioProcessorParameterChangeGestureBegin
  31102. */
  31103. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  31104. int parameterIndex);
  31105. };
  31106. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  31107. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  31108. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  31109. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  31110. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  31111. /**
  31112. A subclass of AudioPlayHead can supply information about the position and
  31113. status of a moving play head during audio playback.
  31114. One of these can be supplied to an AudioProcessor object so that it can find
  31115. out about the position of the audio that it is rendering.
  31116. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  31117. */
  31118. class JUCE_API AudioPlayHead
  31119. {
  31120. protected:
  31121. AudioPlayHead() {}
  31122. public:
  31123. virtual ~AudioPlayHead() {}
  31124. /** Frame rate types. */
  31125. enum FrameRateType
  31126. {
  31127. fps24 = 0,
  31128. fps25 = 1,
  31129. fps2997 = 2,
  31130. fps30 = 3,
  31131. fps2997drop = 4,
  31132. fps30drop = 5,
  31133. fpsUnknown = 99
  31134. };
  31135. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  31136. */
  31137. struct CurrentPositionInfo
  31138. {
  31139. /** The tempo in BPM */
  31140. double bpm;
  31141. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  31142. int timeSigNumerator;
  31143. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  31144. int timeSigDenominator;
  31145. /** The current play position, in seconds from the start of the edit. */
  31146. double timeInSeconds;
  31147. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  31148. double editOriginTime;
  31149. /** The current play position in pulses-per-quarter-note.
  31150. This is the number of quarter notes since the edit start.
  31151. */
  31152. double ppqPosition;
  31153. /** The position of the start of the last bar, in pulses-per-quarter-note.
  31154. This is the number of quarter notes from the start of the edit to the
  31155. start of the current bar.
  31156. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  31157. it's not available, the value will be 0.
  31158. */
  31159. double ppqPositionOfLastBarStart;
  31160. /** The video frame rate, if applicable. */
  31161. FrameRateType frameRate;
  31162. /** True if the transport is currently playing. */
  31163. bool isPlaying;
  31164. /** True if the transport is currently recording.
  31165. (When isRecording is true, then isPlaying will also be true).
  31166. */
  31167. bool isRecording;
  31168. bool operator== (const CurrentPositionInfo& other) const throw();
  31169. bool operator!= (const CurrentPositionInfo& other) const throw();
  31170. void resetToDefault();
  31171. };
  31172. /** Fills-in the given structure with details about the transport's
  31173. position at the start of the current processing block.
  31174. */
  31175. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  31176. };
  31177. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  31178. /*** End of inlined file: juce_AudioPlayHead.h ***/
  31179. /**
  31180. Base class for audio processing filters or plugins.
  31181. This is intended to act as a base class of audio filter that is general enough to
  31182. be wrapped as a VST, AU, RTAS, etc, or used internally.
  31183. It is also used by the plugin hosting code as the wrapper around an instance
  31184. of a loaded plugin.
  31185. Derive your filter class from this base class, and if you're building a plugin,
  31186. you should implement a global function called createPluginFilter() which creates
  31187. and returns a new instance of your subclass.
  31188. */
  31189. class JUCE_API AudioProcessor
  31190. {
  31191. protected:
  31192. /** Constructor.
  31193. You can also do your initialisation tasks in the initialiseFilterInfo()
  31194. call, which will be made after this object has been created.
  31195. */
  31196. AudioProcessor();
  31197. public:
  31198. /** Destructor. */
  31199. virtual ~AudioProcessor();
  31200. /** Returns the name of this processor.
  31201. */
  31202. virtual const String getName() const = 0;
  31203. /** Called before playback starts, to let the filter prepare itself.
  31204. The sample rate is the target sample rate, and will remain constant until
  31205. playback stops.
  31206. The estimatedSamplesPerBlock value is a HINT about the typical number of
  31207. samples that will be processed for each callback, but isn't any kind
  31208. of guarantee. The actual block sizes that the host uses may be different
  31209. each time the callback happens, and may be more or less than this value.
  31210. */
  31211. virtual void prepareToPlay (double sampleRate,
  31212. int estimatedSamplesPerBlock) = 0;
  31213. /** Called after playback has stopped, to let the filter free up any resources it
  31214. no longer needs.
  31215. */
  31216. virtual void releaseResources() = 0;
  31217. /** Renders the next block.
  31218. When this method is called, the buffer contains a number of channels which is
  31219. at least as great as the maximum number of input and output channels that
  31220. this filter is using. It will be filled with the filter's input data and
  31221. should be replaced with the filter's output.
  31222. So for example if your filter has 2 input channels and 4 output channels, then
  31223. the buffer will contain 4 channels, the first two being filled with the
  31224. input data. Your filter should read these, do its processing, and replace
  31225. the contents of all 4 channels with its output.
  31226. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  31227. all filled with data, and your filter should overwrite the first 2 of these
  31228. with its output. But be VERY careful not to write anything to the last 3
  31229. channels, as these might be mapped to memory that the host assumes is read-only!
  31230. Note that if you have more outputs than inputs, then only those channels that
  31231. correspond to an input channel are guaranteed to contain sensible data - e.g.
  31232. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  31233. but the last two channels may contain garbage, so you should be careful not to
  31234. let this pass through without being overwritten or cleared.
  31235. Also note that the buffer may have more channels than are strictly necessary,
  31236. but your should only read/write from the ones that your filter is supposed to
  31237. be using.
  31238. The number of samples in these buffers is NOT guaranteed to be the same for every
  31239. callback, and may be more or less than the estimated value given to prepareToPlay().
  31240. Your code must be able to cope with variable-sized blocks, or you're going to get
  31241. clicks and crashes!
  31242. If the filter is receiving a midi input, then the midiMessages array will be filled
  31243. with the midi messages for this block. Each message's timestamp will indicate the
  31244. message's time, as a number of samples from the start of the block.
  31245. Any messages left in the midi buffer when this method has finished are assumed to
  31246. be the filter's midi output. This means that your filter should be careful to
  31247. clear any incoming messages from the array if it doesn't want them to be passed-on.
  31248. Be very careful about what you do in this callback - it's going to be called by
  31249. the audio thread, so any kind of interaction with the UI is absolutely
  31250. out of the question. If you change a parameter in here and need to tell your UI to
  31251. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  31252. the UI components register as listeners, and then call sendChangeMessage() inside the
  31253. processBlock() method to send out an asynchronous message. You could also use
  31254. the AsyncUpdater class in a similar way.
  31255. */
  31256. virtual void processBlock (AudioSampleBuffer& buffer,
  31257. MidiBuffer& midiMessages) = 0;
  31258. /** Returns the current AudioPlayHead object that should be used to find
  31259. out the state and position of the playhead.
  31260. You can call this from your processBlock() method, and use the AudioPlayHead
  31261. object to get the details about the time of the start of the block currently
  31262. being processed.
  31263. If the host hasn't supplied a playhead object, this will return 0.
  31264. */
  31265. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  31266. /** Returns the current sample rate.
  31267. This can be called from your processBlock() method - it's not guaranteed
  31268. to be valid at any other time, and may return 0 if it's unknown.
  31269. */
  31270. double getSampleRate() const throw() { return sampleRate; }
  31271. /** Returns the current typical block size that is being used.
  31272. This can be called from your processBlock() method - it's not guaranteed
  31273. to be valid at any other time.
  31274. Remember it's not the ONLY block size that may be used when calling
  31275. processBlock, it's just the normal one. The actual block sizes used may be
  31276. larger or smaller than this, and will vary between successive calls.
  31277. */
  31278. int getBlockSize() const throw() { return blockSize; }
  31279. /** Returns the number of input channels that the host will be sending the filter.
  31280. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  31281. number of channels that your filter would prefer to have, and this method lets
  31282. you know how many the host is actually using.
  31283. Note that this method is only valid during or after the prepareToPlay()
  31284. method call. Until that point, the number of channels will be unknown.
  31285. */
  31286. int getNumInputChannels() const throw() { return numInputChannels; }
  31287. /** Returns the number of output channels that the host will be sending the filter.
  31288. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  31289. number of channels that your filter would prefer to have, and this method lets
  31290. you know how many the host is actually using.
  31291. Note that this method is only valid during or after the prepareToPlay()
  31292. method call. Until that point, the number of channels will be unknown.
  31293. */
  31294. int getNumOutputChannels() const throw() { return numOutputChannels; }
  31295. /** Returns the name of one of the input channels, as returned by the host.
  31296. The host might not supply very useful names for channels, and this might be
  31297. something like "1", "2", "left", "right", etc.
  31298. */
  31299. virtual const String getInputChannelName (int channelIndex) const = 0;
  31300. /** Returns the name of one of the output channels, as returned by the host.
  31301. The host might not supply very useful names for channels, and this might be
  31302. something like "1", "2", "left", "right", etc.
  31303. */
  31304. virtual const String getOutputChannelName (int channelIndex) const = 0;
  31305. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  31306. virtual bool isInputChannelStereoPair (int index) const = 0;
  31307. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  31308. virtual bool isOutputChannelStereoPair (int index) const = 0;
  31309. /** This returns the number of samples delay that the filter imposes on the audio
  31310. passing through it.
  31311. The host will call this to find the latency - the filter itself should set this value
  31312. by calling setLatencySamples() as soon as it can during its initialisation.
  31313. */
  31314. int getLatencySamples() const throw() { return latencySamples; }
  31315. /** The filter should call this to set the number of samples delay that it introduces.
  31316. The filter should call this as soon as it can during initialisation, and can call it
  31317. later if the value changes.
  31318. */
  31319. void setLatencySamples (int newLatency);
  31320. /** Returns true if the processor wants midi messages. */
  31321. virtual bool acceptsMidi() const = 0;
  31322. /** Returns true if the processor produces midi messages. */
  31323. virtual bool producesMidi() const = 0;
  31324. /** This returns a critical section that will automatically be locked while the host
  31325. is calling the processBlock() method.
  31326. Use it from your UI or other threads to lock access to variables that are used
  31327. by the process callback, but obviously be careful not to keep it locked for
  31328. too long, because that could cause stuttering playback. If you need to do something
  31329. that'll take a long time and need the processing to stop while it happens, use the
  31330. suspendProcessing() method instead.
  31331. @see suspendProcessing
  31332. */
  31333. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  31334. /** Enables and disables the processing callback.
  31335. If you need to do something time-consuming on a thread and would like to make sure
  31336. the audio processing callback doesn't happen until you've finished, use this
  31337. to disable the callback and re-enable it again afterwards.
  31338. E.g.
  31339. @code
  31340. void loadNewPatch()
  31341. {
  31342. suspendProcessing (true);
  31343. ..do something that takes ages..
  31344. suspendProcessing (false);
  31345. }
  31346. @endcode
  31347. If the host tries to make an audio callback while processing is suspended, the
  31348. filter will return an empty buffer, but won't block the audio thread like it would
  31349. do if you use the getCallbackLock() critical section to synchronise access.
  31350. If you're going to use this, your processBlock() method must call isSuspended() and
  31351. check whether it's suspended or not. If it is, then it should skip doing any real
  31352. processing, either emitting silence or passing the input through unchanged.
  31353. @see getCallbackLock
  31354. */
  31355. void suspendProcessing (bool shouldBeSuspended);
  31356. /** Returns true if processing is currently suspended.
  31357. @see suspendProcessing
  31358. */
  31359. bool isSuspended() const throw() { return suspended; }
  31360. /** A plugin can override this to be told when it should reset any playing voices.
  31361. The default implementation does nothing, but a host may call this to tell the
  31362. plugin that it should stop any tails or sounds that have been left running.
  31363. */
  31364. virtual void reset();
  31365. /** Returns true if the processor is being run in an offline mode for rendering.
  31366. If the processor is being run live on realtime signals, this returns false.
  31367. If the mode is unknown, this will assume it's realtime and return false.
  31368. This value may be unreliable until the prepareToPlay() method has been called,
  31369. and could change each time prepareToPlay() is called.
  31370. @see setNonRealtime()
  31371. */
  31372. bool isNonRealtime() const throw() { return nonRealtime; }
  31373. /** Called by the host to tell this processor whether it's being used in a non-realime
  31374. capacity for offline rendering or bouncing.
  31375. Whatever value is passed-in will be
  31376. */
  31377. void setNonRealtime (bool isNonRealtime) throw();
  31378. /** Creates the filter's UI.
  31379. This can return 0 if you want a UI-less filter, in which case the host may create
  31380. a generic UI that lets the user twiddle the parameters directly.
  31381. If you do want to pass back a component, the component should be created and set to
  31382. the correct size before returning it. If you implement this method, you must
  31383. also implement the hasEditor() method and make it return true.
  31384. Remember not to do anything silly like allowing your filter to keep a pointer to
  31385. the component that gets created - it could be deleted later without any warning, which
  31386. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  31387. The correct way to handle the connection between an editor component and its
  31388. filter is to use something like a ChangeBroadcaster so that the editor can
  31389. register itself as a listener, and be told when a change occurs. This lets them
  31390. safely unregister themselves when they are deleted.
  31391. Here are a few things to bear in mind when writing an editor:
  31392. - Initially there won't be an editor, until the user opens one, or they might
  31393. not open one at all. Your filter mustn't rely on it being there.
  31394. - An editor object may be deleted and a replacement one created again at any time.
  31395. - It's safe to assume that an editor will be deleted before its filter.
  31396. @see hasEditor
  31397. */
  31398. virtual AudioProcessorEditor* createEditor() = 0;
  31399. /** Your filter must override this and return true if it can create an editor component.
  31400. @see createEditor
  31401. */
  31402. virtual bool hasEditor() const = 0;
  31403. /** Returns the active editor, if there is one.
  31404. Bear in mind this can return 0, even if an editor has previously been
  31405. opened.
  31406. */
  31407. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  31408. /** Returns the active editor, or if there isn't one, it will create one.
  31409. This may call createEditor() internally to create the component.
  31410. */
  31411. AudioProcessorEditor* createEditorIfNeeded();
  31412. /** This must return the correct value immediately after the object has been
  31413. created, and mustn't change the number of parameters later.
  31414. */
  31415. virtual int getNumParameters() = 0;
  31416. /** Returns the name of a particular parameter. */
  31417. virtual const String getParameterName (int parameterIndex) = 0;
  31418. /** Called by the host to find out the value of one of the filter's parameters.
  31419. The host will expect the value returned to be between 0 and 1.0.
  31420. This could be called quite frequently, so try to make your code efficient.
  31421. It's also likely to be called by non-UI threads, so the code in here should
  31422. be thread-aware.
  31423. */
  31424. virtual float getParameter (int parameterIndex) = 0;
  31425. /** Returns the value of a parameter as a text string. */
  31426. virtual const String getParameterText (int parameterIndex) = 0;
  31427. /** The host will call this method to change the value of one of the filter's parameters.
  31428. The host may call this at any time, including during the audio processing
  31429. callback, so the filter has to process this very fast and avoid blocking.
  31430. If you want to set the value of a parameter internally, e.g. from your
  31431. editor component, then don't call this directly - instead, use the
  31432. setParameterNotifyingHost() method, which will also send a message to
  31433. the host telling it about the change. If the message isn't sent, the host
  31434. won't be able to automate your parameters properly.
  31435. The value passed will be between 0 and 1.0.
  31436. */
  31437. virtual void setParameter (int parameterIndex,
  31438. float newValue) = 0;
  31439. /** Your filter can call this when it needs to change one of its parameters.
  31440. This could happen when the editor or some other internal operation changes
  31441. a parameter. This method will call the setParameter() method to change the
  31442. value, and will then send a message to the host telling it about the change.
  31443. Note that to make sure the host correctly handles automation, you should call
  31444. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  31445. tell the host when the user has started and stopped changing the parameter.
  31446. */
  31447. void setParameterNotifyingHost (int parameterIndex,
  31448. float newValue);
  31449. /** Returns true if the host can automate this parameter.
  31450. By default, this returns true for all parameters.
  31451. */
  31452. virtual bool isParameterAutomatable (int parameterIndex) const;
  31453. /** Should return true if this parameter is a "meta" parameter.
  31454. A meta-parameter is a parameter that changes other params. It is used
  31455. by some hosts (e.g. AudioUnit hosts).
  31456. By default this returns false.
  31457. */
  31458. virtual bool isMetaParameter (int parameterIndex) const;
  31459. /** Sends a signal to the host to tell it that the user is about to start changing this
  31460. parameter.
  31461. This allows the host to know when a parameter is actively being held by the user, and
  31462. it may use this information to help it record automation.
  31463. If you call this, it must be matched by a later call to endParameterChangeGesture().
  31464. */
  31465. void beginParameterChangeGesture (int parameterIndex);
  31466. /** Tells the host that the user has finished changing this parameter.
  31467. This allows the host to know when a parameter is actively being held by the user, and
  31468. it may use this information to help it record automation.
  31469. A call to this method must follow a call to beginParameterChangeGesture().
  31470. */
  31471. void endParameterChangeGesture (int parameterIndex);
  31472. /** The filter can call this when something (apart from a parameter value) has changed.
  31473. It sends a hint to the host that something like the program, number of parameters,
  31474. etc, has changed, and that it should update itself.
  31475. */
  31476. void updateHostDisplay();
  31477. /** Returns the number of preset programs the filter supports.
  31478. The value returned must be valid as soon as this object is created, and
  31479. must not change over its lifetime.
  31480. This value shouldn't be less than 1.
  31481. */
  31482. virtual int getNumPrograms() = 0;
  31483. /** Returns the number of the currently active program.
  31484. */
  31485. virtual int getCurrentProgram() = 0;
  31486. /** Called by the host to change the current program.
  31487. */
  31488. virtual void setCurrentProgram (int index) = 0;
  31489. /** Must return the name of a given program. */
  31490. virtual const String getProgramName (int index) = 0;
  31491. /** Called by the host to rename a program.
  31492. */
  31493. virtual void changeProgramName (int index, const String& newName) = 0;
  31494. /** The host will call this method when it wants to save the filter's internal state.
  31495. This must copy any info about the filter's state into the block of memory provided,
  31496. so that the host can store this and later restore it using setStateInformation().
  31497. Note that there's also a getCurrentProgramStateInformation() method, which only
  31498. stores the current program, not the state of the entire filter.
  31499. See also the helper function copyXmlToBinary() for storing settings as XML.
  31500. @see getCurrentProgramStateInformation
  31501. */
  31502. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  31503. /** The host will call this method if it wants to save the state of just the filter's
  31504. current program.
  31505. Unlike getStateInformation, this should only return the current program's state.
  31506. Not all hosts support this, and if you don't implement it, the base class
  31507. method just calls getStateInformation() instead. If you do implement it, be
  31508. sure to also implement getCurrentProgramStateInformation.
  31509. @see getStateInformation, setCurrentProgramStateInformation
  31510. */
  31511. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  31512. /** This must restore the filter's state from a block of data previously created
  31513. using getStateInformation().
  31514. Note that there's also a setCurrentProgramStateInformation() method, which tries
  31515. to restore just the current program, not the state of the entire filter.
  31516. See also the helper function getXmlFromBinary() for loading settings as XML.
  31517. @see setCurrentProgramStateInformation
  31518. */
  31519. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  31520. /** The host will call this method if it wants to restore the state of just the filter's
  31521. current program.
  31522. Not all hosts support this, and if you don't implement it, the base class
  31523. method just calls setStateInformation() instead. If you do implement it, be
  31524. sure to also implement getCurrentProgramStateInformation.
  31525. @see setStateInformation, getCurrentProgramStateInformation
  31526. */
  31527. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  31528. /** Adds a listener that will be called when an aspect of this processor changes. */
  31529. void addListener (AudioProcessorListener* newListener);
  31530. /** Removes a previously added listener. */
  31531. void removeListener (AudioProcessorListener* listenerToRemove);
  31532. /** Tells the processor to use this playhead object.
  31533. The processor will not take ownership of the object, so the caller must delete it when
  31534. it is no longer being used.
  31535. */
  31536. void setPlayHead (AudioPlayHead* newPlayHead) throw();
  31537. /** Not for public use - this is called before deleting an editor component. */
  31538. void editorBeingDeleted (AudioProcessorEditor* editor) throw();
  31539. /** Not for public use - this is called to initialise the processor before playing. */
  31540. void setPlayConfigDetails (int numIns, int numOuts,
  31541. double sampleRate,
  31542. int blockSize) throw();
  31543. protected:
  31544. /** Helper function that just converts an xml element into a binary blob.
  31545. Use this in your filter's getStateInformation() method if you want to
  31546. store its state as xml.
  31547. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  31548. from a binary blob.
  31549. */
  31550. static void copyXmlToBinary (const XmlElement& xml,
  31551. JUCE_NAMESPACE::MemoryBlock& destData);
  31552. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  31553. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  31554. an XmlElement object that the caller must delete when no longer needed.
  31555. */
  31556. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  31557. /** @internal */
  31558. AudioPlayHead* playHead;
  31559. /** @internal */
  31560. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  31561. private:
  31562. Array <AudioProcessorListener*> listeners;
  31563. Component::SafePointer<AudioProcessorEditor> activeEditor;
  31564. double sampleRate;
  31565. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  31566. bool suspended, nonRealtime;
  31567. CriticalSection callbackLock, listenerLock;
  31568. #if JUCE_DEBUG
  31569. BigInteger changingParams;
  31570. #endif
  31571. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  31572. };
  31573. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  31574. /*** End of inlined file: juce_AudioProcessor.h ***/
  31575. /*** Start of inlined file: juce_PluginDescription.h ***/
  31576. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  31577. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  31578. /**
  31579. A small class to represent some facts about a particular type of plugin.
  31580. This class is for storing and managing the details about a plugin without
  31581. actually having to load an instance of it.
  31582. A KnownPluginList contains a list of PluginDescription objects.
  31583. @see KnownPluginList
  31584. */
  31585. class JUCE_API PluginDescription
  31586. {
  31587. public:
  31588. PluginDescription();
  31589. PluginDescription (const PluginDescription& other);
  31590. PluginDescription& operator= (const PluginDescription& other);
  31591. ~PluginDescription();
  31592. /** The name of the plugin. */
  31593. String name;
  31594. /** A more descriptive name for the plugin.
  31595. This may be the same as the 'name' field, but some plugins may provide an
  31596. alternative name.
  31597. */
  31598. String descriptiveName;
  31599. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  31600. */
  31601. String pluginFormatName;
  31602. /** A category, such as "Dynamics", "Reverbs", etc.
  31603. */
  31604. String category;
  31605. /** The manufacturer. */
  31606. String manufacturerName;
  31607. /** The version. This string doesn't have any particular format. */
  31608. String version;
  31609. /** Either the file containing the plugin module, or some other unique way
  31610. of identifying it.
  31611. E.g. for an AU, this would be an ID string that the component manager
  31612. could use to retrieve the plugin. For a VST, it's the file path.
  31613. */
  31614. String fileOrIdentifier;
  31615. /** The last time the plugin file was changed.
  31616. This is handy when scanning for new or changed plugins.
  31617. */
  31618. Time lastFileModTime;
  31619. /** A unique ID for the plugin.
  31620. Note that this might not be unique between formats, e.g. a VST and some
  31621. other format might actually have the same id.
  31622. @see createIdentifierString
  31623. */
  31624. int uid;
  31625. /** True if the plugin identifies itself as a synthesiser. */
  31626. bool isInstrument;
  31627. /** The number of inputs. */
  31628. int numInputChannels;
  31629. /** The number of outputs. */
  31630. int numOutputChannels;
  31631. /** Returns true if the two descriptions refer the the same plugin.
  31632. This isn't quite as simple as them just having the same file (because of
  31633. shell plugins).
  31634. */
  31635. bool isDuplicateOf (const PluginDescription& other) const;
  31636. /** Returns a string that can be saved and used to uniquely identify the
  31637. plugin again.
  31638. This contains less info than the XML encoding, and is independent of the
  31639. plugin's file location, so can be used to store a plugin ID for use
  31640. across different machines.
  31641. */
  31642. const String createIdentifierString() const;
  31643. /** Creates an XML object containing these details.
  31644. @see loadFromXml
  31645. */
  31646. XmlElement* createXml() const;
  31647. /** Reloads the info in this structure from an XML record that was previously
  31648. saved with createXML().
  31649. Returns true if the XML was a valid plugin description.
  31650. */
  31651. bool loadFromXml (const XmlElement& xml);
  31652. private:
  31653. JUCE_LEAK_DETECTOR (PluginDescription);
  31654. };
  31655. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  31656. /*** End of inlined file: juce_PluginDescription.h ***/
  31657. /**
  31658. Base class for an active instance of a plugin.
  31659. This derives from the AudioProcessor class, and adds some extra functionality
  31660. that helps when wrapping dynamically loaded plugins.
  31661. @see AudioProcessor, AudioPluginFormat
  31662. */
  31663. class JUCE_API AudioPluginInstance : public AudioProcessor
  31664. {
  31665. public:
  31666. /** Destructor.
  31667. Make sure that you delete any UI components that belong to this plugin before
  31668. deleting the plugin.
  31669. */
  31670. virtual ~AudioPluginInstance();
  31671. /** Fills-in the appropriate parts of this plugin description object.
  31672. */
  31673. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  31674. /** Returns a pointer to some kind of platform-specific data about the plugin.
  31675. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  31676. cast to an AudioUnit handle.
  31677. */
  31678. virtual void* getPlatformSpecificData();
  31679. protected:
  31680. AudioPluginInstance();
  31681. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  31682. };
  31683. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  31684. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  31685. class PluginDescription;
  31686. /**
  31687. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  31688. Use the static getNumFormats() and getFormat() calls to find the types
  31689. of format that are available.
  31690. */
  31691. class JUCE_API AudioPluginFormat
  31692. {
  31693. public:
  31694. /** Destructor. */
  31695. virtual ~AudioPluginFormat();
  31696. /** Returns the format name.
  31697. E.g. "VST", "AudioUnit", etc.
  31698. */
  31699. virtual const String getName() const = 0;
  31700. /** This tries to create descriptions for all the plugin types available in
  31701. a binary module file.
  31702. The file will be some kind of DLL or bundle.
  31703. Normally there will only be one type returned, but some plugins
  31704. (e.g. VST shells) can use a single DLL to create a set of different plugin
  31705. subtypes, so in that case, each subtype is returned as a separate object.
  31706. */
  31707. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  31708. const String& fileOrIdentifier) = 0;
  31709. /** Tries to recreate a type from a previously generated PluginDescription.
  31710. @see PluginDescription::createInstance
  31711. */
  31712. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  31713. /** Should do a quick check to see if this file or directory might be a plugin of
  31714. this format.
  31715. This is for searching for potential files, so it shouldn't actually try to
  31716. load the plugin or do anything time-consuming.
  31717. */
  31718. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  31719. /** Returns a readable version of the name of the plugin that this identifier refers to.
  31720. */
  31721. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  31722. /** Checks whether this plugin could possibly be loaded.
  31723. It doesn't actually need to load it, just to check whether the file or component
  31724. still exists.
  31725. */
  31726. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  31727. /** Searches a suggested set of directories for any plugins in this format.
  31728. The path might be ignored, e.g. by AUs, which are found by the OS rather
  31729. than manually.
  31730. */
  31731. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  31732. bool recursive) = 0;
  31733. /** Returns the typical places to look for this kind of plugin.
  31734. Note that if this returns no paths, it means that the format can't be scanned-for
  31735. (i.e. it's an internal format that doesn't live in files)
  31736. */
  31737. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  31738. protected:
  31739. AudioPluginFormat() throw();
  31740. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  31741. };
  31742. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  31743. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  31744. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  31745. /**
  31746. Implements a plugin format manager for AudioUnits.
  31747. */
  31748. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  31749. {
  31750. public:
  31751. AudioUnitPluginFormat();
  31752. ~AudioUnitPluginFormat();
  31753. const String getName() const { return "AudioUnit"; }
  31754. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  31755. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  31756. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  31757. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  31758. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  31759. bool doesPluginStillExist (const PluginDescription& desc);
  31760. const FileSearchPath getDefaultLocationsToSearch();
  31761. private:
  31762. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  31763. };
  31764. #endif
  31765. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  31766. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  31767. #endif
  31768. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  31769. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  31770. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  31771. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  31772. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  31773. // Sorry, this file is just a placeholder at the moment!...
  31774. /**
  31775. Implements a plugin format manager for DirectX plugins.
  31776. */
  31777. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  31778. {
  31779. public:
  31780. DirectXPluginFormat();
  31781. ~DirectXPluginFormat();
  31782. const String getName() const { return "DirectX"; }
  31783. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  31784. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  31785. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  31786. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  31787. const FileSearchPath getDefaultLocationsToSearch();
  31788. private:
  31789. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  31790. };
  31791. #endif
  31792. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  31793. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  31794. #endif
  31795. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  31796. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  31797. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  31798. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  31799. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  31800. // Sorry, this file is just a placeholder at the moment!...
  31801. /**
  31802. Implements a plugin format manager for DirectX plugins.
  31803. */
  31804. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  31805. {
  31806. public:
  31807. LADSPAPluginFormat();
  31808. ~LADSPAPluginFormat();
  31809. const String getName() const { return "LADSPA"; }
  31810. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  31811. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  31812. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  31813. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  31814. const FileSearchPath getDefaultLocationsToSearch();
  31815. private:
  31816. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  31817. };
  31818. #endif
  31819. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  31820. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  31821. #endif
  31822. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  31823. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  31824. #ifdef __aeffect__
  31825. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  31826. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  31827. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  31828. events to the list.
  31829. This is used by both the VST hosting code and the plugin wrapper.
  31830. */
  31831. class VSTMidiEventList
  31832. {
  31833. public:
  31834. VSTMidiEventList()
  31835. : numEventsUsed (0), numEventsAllocated (0)
  31836. {
  31837. }
  31838. ~VSTMidiEventList()
  31839. {
  31840. freeEvents();
  31841. }
  31842. void clear()
  31843. {
  31844. numEventsUsed = 0;
  31845. if (events != 0)
  31846. events->numEvents = 0;
  31847. }
  31848. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  31849. {
  31850. ensureSize (numEventsUsed + 1);
  31851. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  31852. events->numEvents = ++numEventsUsed;
  31853. if (numBytes <= 4)
  31854. {
  31855. if (e->type == kVstSysExType)
  31856. {
  31857. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  31858. e->type = kVstMidiType;
  31859. e->byteSize = sizeof (VstMidiEvent);
  31860. e->noteLength = 0;
  31861. e->noteOffset = 0;
  31862. e->detune = 0;
  31863. e->noteOffVelocity = 0;
  31864. }
  31865. e->deltaFrames = frameOffset;
  31866. memcpy (e->midiData, midiData, numBytes);
  31867. }
  31868. else
  31869. {
  31870. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  31871. if (se->type == kVstSysExType)
  31872. delete[] se->sysexDump;
  31873. se->sysexDump = new char [numBytes];
  31874. memcpy (se->sysexDump, midiData, numBytes);
  31875. se->type = kVstSysExType;
  31876. se->byteSize = sizeof (VstMidiSysexEvent);
  31877. se->deltaFrames = frameOffset;
  31878. se->flags = 0;
  31879. se->dumpBytes = numBytes;
  31880. se->resvd1 = 0;
  31881. se->resvd2 = 0;
  31882. }
  31883. }
  31884. // Handy method to pull the events out of an event buffer supplied by the host
  31885. // or plugin.
  31886. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  31887. {
  31888. for (int i = 0; i < events->numEvents; ++i)
  31889. {
  31890. const VstEvent* const e = events->events[i];
  31891. if (e != 0)
  31892. {
  31893. if (e->type == kVstMidiType)
  31894. {
  31895. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  31896. 4, e->deltaFrames);
  31897. }
  31898. else if (e->type == kVstSysExType)
  31899. {
  31900. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  31901. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  31902. e->deltaFrames);
  31903. }
  31904. }
  31905. }
  31906. }
  31907. void ensureSize (int numEventsNeeded)
  31908. {
  31909. if (numEventsNeeded > numEventsAllocated)
  31910. {
  31911. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  31912. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  31913. if (events == 0)
  31914. events.calloc (size, 1);
  31915. else
  31916. events.realloc (size, 1);
  31917. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  31918. {
  31919. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  31920. (int) sizeof (VstMidiSysexEvent)));
  31921. e->type = kVstMidiType;
  31922. e->byteSize = sizeof (VstMidiEvent);
  31923. events->events[i] = (VstEvent*) e;
  31924. }
  31925. numEventsAllocated = numEventsNeeded;
  31926. }
  31927. }
  31928. void freeEvents()
  31929. {
  31930. if (events != 0)
  31931. {
  31932. for (int i = numEventsAllocated; --i >= 0;)
  31933. {
  31934. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  31935. if (e->type == kVstSysExType)
  31936. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  31937. juce_free (e);
  31938. }
  31939. events.free();
  31940. numEventsUsed = 0;
  31941. numEventsAllocated = 0;
  31942. }
  31943. }
  31944. HeapBlock <VstEvents> events;
  31945. private:
  31946. int numEventsUsed, numEventsAllocated;
  31947. };
  31948. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  31949. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  31950. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  31951. #endif
  31952. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  31953. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  31954. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  31955. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  31956. #if JUCE_PLUGINHOST_VST
  31957. /**
  31958. Implements a plugin format manager for VSTs.
  31959. */
  31960. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  31961. {
  31962. public:
  31963. VSTPluginFormat();
  31964. ~VSTPluginFormat();
  31965. const String getName() const { return "VST"; }
  31966. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  31967. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  31968. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  31969. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  31970. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  31971. bool doesPluginStillExist (const PluginDescription& desc);
  31972. const FileSearchPath getDefaultLocationsToSearch();
  31973. private:
  31974. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  31975. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  31976. };
  31977. #endif
  31978. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  31979. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  31980. #endif
  31981. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  31982. #endif
  31983. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  31984. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  31985. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  31986. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  31987. /**
  31988. This maintains a list of known AudioPluginFormats.
  31989. @see AudioPluginFormat
  31990. */
  31991. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  31992. {
  31993. public:
  31994. AudioPluginFormatManager();
  31995. /** Destructor. */
  31996. ~AudioPluginFormatManager();
  31997. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  31998. /** Adds any formats that it knows about, e.g. VST.
  31999. */
  32000. void addDefaultFormats();
  32001. /** Returns the number of types of format that are available.
  32002. Use getFormat() to get one of them.
  32003. */
  32004. int getNumFormats();
  32005. /** Returns one of the available formats.
  32006. @see getNumFormats
  32007. */
  32008. AudioPluginFormat* getFormat (int index);
  32009. /** Adds a format to the list.
  32010. The object passed in will be owned and deleted by the manager.
  32011. */
  32012. void addFormat (AudioPluginFormat* format);
  32013. /** Tries to load the type for this description, by trying all the formats
  32014. that this manager knows about.
  32015. The caller is responsible for deleting the object that is returned.
  32016. If it can't load the plugin, it returns 0 and leaves a message in the
  32017. errorMessage string.
  32018. */
  32019. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  32020. String& errorMessage) const;
  32021. /** Checks that the file or component for this plugin actually still exists.
  32022. (This won't try to load the plugin)
  32023. */
  32024. bool doesPluginStillExist (const PluginDescription& description) const;
  32025. private:
  32026. OwnedArray <AudioPluginFormat> formats;
  32027. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  32028. };
  32029. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  32030. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  32031. #endif
  32032. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32033. #endif
  32034. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  32035. /*** Start of inlined file: juce_KnownPluginList.h ***/
  32036. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  32037. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  32038. /**
  32039. Manages a list of plugin types.
  32040. This can be easily edited, saved and loaded, and used to create instances of
  32041. the plugin types in it.
  32042. @see PluginListComponent
  32043. */
  32044. class JUCE_API KnownPluginList : public ChangeBroadcaster
  32045. {
  32046. public:
  32047. /** Creates an empty list.
  32048. */
  32049. KnownPluginList();
  32050. /** Destructor. */
  32051. ~KnownPluginList();
  32052. /** Clears the list. */
  32053. void clear();
  32054. /** Returns the number of types currently in the list.
  32055. @see getType
  32056. */
  32057. int getNumTypes() const throw() { return types.size(); }
  32058. /** Returns one of the types.
  32059. @see getNumTypes
  32060. */
  32061. PluginDescription* getType (int index) const throw() { return types [index]; }
  32062. /** Looks for a type in the list which comes from this file.
  32063. */
  32064. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  32065. /** Looks for a type in the list which matches a plugin type ID.
  32066. The identifierString parameter must have been created by
  32067. PluginDescription::createIdentifierString().
  32068. */
  32069. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  32070. /** Adds a type manually from its description. */
  32071. bool addType (const PluginDescription& type);
  32072. /** Removes a type. */
  32073. void removeType (int index);
  32074. /** Looks for all types that can be loaded from a given file, and adds them
  32075. to the list.
  32076. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  32077. re-tested if it's not already in the list, or if the file's modification
  32078. time has changed since the list was created. If dontRescanIfAlreadyInList is
  32079. false, the file will always be reloaded and tested.
  32080. Returns true if any new types were added, and all the types found in this
  32081. file (even if it was already known and hasn't been re-scanned) get returned
  32082. in the array.
  32083. */
  32084. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  32085. bool dontRescanIfAlreadyInList,
  32086. OwnedArray <PluginDescription>& typesFound,
  32087. AudioPluginFormat& formatToUse);
  32088. /** Returns true if the specified file is already known about and if it
  32089. hasn't been modified since our entry was created.
  32090. */
  32091. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  32092. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  32093. If any types are found in the files, their descriptions are returned in the array.
  32094. */
  32095. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  32096. OwnedArray <PluginDescription>& typesFound);
  32097. /** Sort methods used to change the order of the plugins in the list.
  32098. */
  32099. enum SortMethod
  32100. {
  32101. defaultOrder = 0,
  32102. sortAlphabetically,
  32103. sortByCategory,
  32104. sortByManufacturer,
  32105. sortByFileSystemLocation
  32106. };
  32107. /** Adds all the plugin types to a popup menu so that the user can select one.
  32108. Depending on the sort method, it may add sub-menus for categories,
  32109. manufacturers, etc.
  32110. Use getIndexChosenByMenu() to find out the type that was chosen.
  32111. */
  32112. void addToMenu (PopupMenu& menu,
  32113. const SortMethod sortMethod) const;
  32114. /** Converts a menu item index that has been chosen into its index in this list.
  32115. Returns -1 if it's not an ID that was used.
  32116. @see addToMenu
  32117. */
  32118. int getIndexChosenByMenu (int menuResultCode) const;
  32119. /** Sorts the list. */
  32120. void sort (const SortMethod method);
  32121. /** Creates some XML that can be used to store the state of this list.
  32122. */
  32123. XmlElement* createXml() const;
  32124. /** Recreates the state of this list from its stored XML format.
  32125. */
  32126. void recreateFromXml (const XmlElement& xml);
  32127. private:
  32128. OwnedArray <PluginDescription> types;
  32129. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  32130. };
  32131. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  32132. /*** End of inlined file: juce_KnownPluginList.h ***/
  32133. #endif
  32134. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  32135. #endif
  32136. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  32137. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  32138. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  32139. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  32140. /**
  32141. Scans a directory for plugins, and adds them to a KnownPluginList.
  32142. To use one of these, create it and call scanNextFile() repeatedly, until
  32143. it returns false.
  32144. */
  32145. class JUCE_API PluginDirectoryScanner
  32146. {
  32147. public:
  32148. /**
  32149. Creates a scanner.
  32150. @param listToAddResultsTo this will get the new types added to it.
  32151. @param formatToLookFor this is the type of format that you want to look for
  32152. @param directoriesToSearch the path to search
  32153. @param searchRecursively true to search recursively
  32154. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  32155. be used as a file to store the names of any plugins
  32156. that crash during initialisation. If there are
  32157. any plugins listed in it, then these will always
  32158. be scanned after all other possible files have
  32159. been tried - in this way, even if there's a few
  32160. dodgy plugins in your path, then a couple of rescans
  32161. will still manage to find all the proper plugins.
  32162. It's probably best to choose a file in the user's
  32163. application data directory (alongside your app's
  32164. settings file) for this. The file format it uses
  32165. is just a list of filenames of the modules that
  32166. failed.
  32167. */
  32168. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  32169. AudioPluginFormat& formatToLookFor,
  32170. FileSearchPath directoriesToSearch,
  32171. bool searchRecursively,
  32172. const File& deadMansPedalFile);
  32173. /** Destructor. */
  32174. ~PluginDirectoryScanner();
  32175. /** Tries the next likely-looking file.
  32176. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  32177. re-tested if it's not already in the list, or if the file's modification
  32178. time has changed since the list was created. If dontRescanIfAlreadyInList is
  32179. false, the file will always be reloaded and tested.
  32180. Returns false when there are no more files to try.
  32181. */
  32182. bool scanNextFile (bool dontRescanIfAlreadyInList);
  32183. /** Skips over the next file without scanning it.
  32184. Returns false when there are no more files to try.
  32185. */
  32186. bool skipNextFile();
  32187. /** Returns the description of the plugin that will be scanned during the next
  32188. call to scanNextFile().
  32189. This is handy if you want to show the user which file is currently getting
  32190. scanned.
  32191. */
  32192. const String getNextPluginFileThatWillBeScanned() const;
  32193. /** Returns the estimated progress, between 0 and 1.
  32194. */
  32195. float getProgress() const { return progress; }
  32196. /** This returns a list of all the filenames of things that looked like being
  32197. a plugin file, but which failed to open for some reason.
  32198. */
  32199. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  32200. private:
  32201. KnownPluginList& list;
  32202. AudioPluginFormat& format;
  32203. StringArray filesOrIdentifiersToScan;
  32204. File deadMansPedalFile;
  32205. StringArray failedFiles;
  32206. int nextIndex;
  32207. float progress;
  32208. const StringArray getDeadMansPedalFile();
  32209. void setDeadMansPedalFile (const StringArray& newContents);
  32210. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  32211. };
  32212. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  32213. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  32214. #endif
  32215. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  32216. /*** Start of inlined file: juce_PluginListComponent.h ***/
  32217. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  32218. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  32219. /*** Start of inlined file: juce_ListBox.h ***/
  32220. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  32221. #define __JUCE_LISTBOX_JUCEHEADER__
  32222. class ListViewport;
  32223. /**
  32224. A subclass of this is used to drive a ListBox.
  32225. @see ListBox
  32226. */
  32227. class JUCE_API ListBoxModel
  32228. {
  32229. public:
  32230. /** Destructor. */
  32231. virtual ~ListBoxModel() {}
  32232. /** This has to return the number of items in the list.
  32233. @see ListBox::getNumRows()
  32234. */
  32235. virtual int getNumRows() = 0;
  32236. /** This method must be implemented to draw a row of the list.
  32237. */
  32238. virtual void paintListBoxItem (int rowNumber,
  32239. Graphics& g,
  32240. int width, int height,
  32241. bool rowIsSelected) = 0;
  32242. /** This is used to create or update a custom component to go in a row of the list.
  32243. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  32244. and handle mouse clicks with listBoxItemClicked().
  32245. This method will be called whenever a custom component might need to be updated - e.g.
  32246. when the table is changed, or TableListBox::updateContent() is called.
  32247. If you don't need a custom component for the specified row, then return 0.
  32248. If you do want a custom component, and the existingComponentToUpdate is null, then
  32249. this method must create a suitable new component and return it.
  32250. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  32251. by this method. In this case, the method must either update it to make sure it's correctly representing
  32252. the given row (which may be different from the one that the component was created for), or it can
  32253. delete this component and return a new one.
  32254. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  32255. */
  32256. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  32257. Component* existingComponentToUpdate);
  32258. /** This can be overridden to react to the user clicking on a row.
  32259. @see listBoxItemDoubleClicked
  32260. */
  32261. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  32262. /** This can be overridden to react to the user double-clicking on a row.
  32263. @see listBoxItemClicked
  32264. */
  32265. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  32266. /** This can be overridden to react to the user double-clicking on a part of the list where
  32267. there are no rows.
  32268. @see listBoxItemClicked
  32269. */
  32270. virtual void backgroundClicked();
  32271. /** Override this to be informed when rows are selected or deselected.
  32272. This will be called whenever a row is selected or deselected. If a range of
  32273. rows is selected all at once, this will just be called once for that event.
  32274. @param lastRowSelected the last row that the user selected. If no
  32275. rows are currently selected, this may be -1.
  32276. */
  32277. virtual void selectedRowsChanged (int lastRowSelected);
  32278. /** Override this to be informed when the delete key is pressed.
  32279. If no rows are selected when they press the key, this won't be called.
  32280. @param lastRowSelected the last row that had been selected when they pressed the
  32281. key - if there are multiple selections, this might not be
  32282. very useful
  32283. */
  32284. virtual void deleteKeyPressed (int lastRowSelected);
  32285. /** Override this to be informed when the return key is pressed.
  32286. If no rows are selected when they press the key, this won't be called.
  32287. @param lastRowSelected the last row that had been selected when they pressed the
  32288. key - if there are multiple selections, this might not be
  32289. very useful
  32290. */
  32291. virtual void returnKeyPressed (int lastRowSelected);
  32292. /** Override this to be informed when the list is scrolled.
  32293. This might be caused by the user moving the scrollbar, or by programmatic changes
  32294. to the list position.
  32295. */
  32296. virtual void listWasScrolled();
  32297. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  32298. If this returns a non-empty name then when the user drags a row, the listbox will
  32299. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  32300. a drag-and-drop operation, using this string as the source description, with the listbox
  32301. itself as the source component.
  32302. @see DragAndDropContainer::startDragging
  32303. */
  32304. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  32305. /** You can override this to provide tool tips for specific rows.
  32306. @see TooltipClient
  32307. */
  32308. virtual const String getTooltipForRow (int row);
  32309. };
  32310. /**
  32311. A list of items that can be scrolled vertically.
  32312. To create a list, you'll need to create a subclass of ListBoxModel. This can
  32313. either paint each row of the list and respond to events via callbacks, or for
  32314. more specialised tasks, it can supply a custom component to fill each row.
  32315. @see ComboBox, TableListBox
  32316. */
  32317. class JUCE_API ListBox : public Component,
  32318. public SettableTooltipClient
  32319. {
  32320. public:
  32321. /** Creates a ListBox.
  32322. The model pointer passed-in can be null, in which case you can set it later
  32323. with setModel().
  32324. */
  32325. ListBox (const String& componentName = String::empty,
  32326. ListBoxModel* model = 0);
  32327. /** Destructor. */
  32328. ~ListBox();
  32329. /** Changes the current data model to display. */
  32330. void setModel (ListBoxModel* newModel);
  32331. /** Returns the current list model. */
  32332. ListBoxModel* getModel() const throw() { return model; }
  32333. /** Causes the list to refresh its content.
  32334. Call this when the number of rows in the list changes, or if you want it
  32335. to call refreshComponentForRow() on all the row components.
  32336. Be careful not to call it from a different thread, though, as it's not
  32337. thread-safe.
  32338. */
  32339. void updateContent();
  32340. /** Turns on multiple-selection of rows.
  32341. By default this is disabled.
  32342. When your row component gets clicked you'll need to call the
  32343. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  32344. clicked and to get it to do the appropriate selection based on whether
  32345. the ctrl/shift keys are held down.
  32346. */
  32347. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  32348. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  32349. This function is here primarily for the ComboBox class to use, but might be
  32350. useful for some other purpose too.
  32351. */
  32352. void setMouseMoveSelectsRows (bool shouldSelect);
  32353. /** Selects a row.
  32354. If the row is already selected, this won't do anything.
  32355. @param rowNumber the row to select
  32356. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  32357. the selected row is off-screen, it'll scroll to make
  32358. sure that row is on-screen
  32359. @param deselectOthersFirst if true and there are multiple selections, these will
  32360. first be deselected before this item is selected
  32361. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  32362. deselectAllRows, selectRangeOfRows
  32363. */
  32364. void selectRow (int rowNumber,
  32365. bool dontScrollToShowThisRow = false,
  32366. bool deselectOthersFirst = true);
  32367. /** Selects a set of rows.
  32368. This will add these rows to the current selection, so you might need to
  32369. clear the current selection first with deselectAllRows()
  32370. @param firstRow the first row to select (inclusive)
  32371. @param lastRow the last row to select (inclusive)
  32372. */
  32373. void selectRangeOfRows (int firstRow,
  32374. int lastRow);
  32375. /** Deselects a row.
  32376. If it's not currently selected, this will do nothing.
  32377. @see selectRow, deselectAllRows
  32378. */
  32379. void deselectRow (int rowNumber);
  32380. /** Deselects any currently selected rows.
  32381. @see deselectRow
  32382. */
  32383. void deselectAllRows();
  32384. /** Selects or deselects a row.
  32385. If the row's currently selected, this deselects it, and vice-versa.
  32386. */
  32387. void flipRowSelection (int rowNumber);
  32388. /** Returns a sparse set indicating the rows that are currently selected.
  32389. @see setSelectedRows
  32390. */
  32391. const SparseSet<int> getSelectedRows() const;
  32392. /** Sets the rows that should be selected, based on an explicit set of ranges.
  32393. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  32394. method will be called. If it's false, no notification will be sent to the model.
  32395. @see getSelectedRows
  32396. */
  32397. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  32398. bool sendNotificationEventToModel = true);
  32399. /** Checks whether a row is selected.
  32400. */
  32401. bool isRowSelected (int rowNumber) const;
  32402. /** Returns the number of rows that are currently selected.
  32403. @see getSelectedRow, isRowSelected, getLastRowSelected
  32404. */
  32405. int getNumSelectedRows() const;
  32406. /** Returns the row number of a selected row.
  32407. This will return the row number of the Nth selected row. The row numbers returned will
  32408. be sorted in order from low to high.
  32409. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  32410. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  32411. selected
  32412. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  32413. */
  32414. int getSelectedRow (int index = 0) const;
  32415. /** Returns the last row that the user selected.
  32416. This isn't the same as the highest row number that is currently selected - if the user
  32417. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  32418. If nothing is selected, it will return -1.
  32419. */
  32420. int getLastRowSelected() const;
  32421. /** Multiply-selects rows based on the modifier keys.
  32422. If no modifier keys are down, this will select the given row and
  32423. deselect any others.
  32424. If the ctrl (or command on the Mac) key is down, it'll flip the
  32425. state of the selected row.
  32426. If the shift key is down, it'll select up to the given row from the
  32427. last row selected.
  32428. @see selectRow
  32429. */
  32430. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  32431. const ModifierKeys& modifiers,
  32432. bool isMouseUpEvent);
  32433. /** Scrolls the list to a particular position.
  32434. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  32435. 1.0 scrolls to the bottom.
  32436. If the total number of rows all fit onto the screen at once, then this
  32437. method won't do anything.
  32438. @see getVerticalPosition
  32439. */
  32440. void setVerticalPosition (double newProportion);
  32441. /** Returns the current vertical position as a proportion of the total.
  32442. This can be used in conjunction with setVerticalPosition() to save and restore
  32443. the list's position. It returns a value in the range 0 to 1.
  32444. @see setVerticalPosition
  32445. */
  32446. double getVerticalPosition() const;
  32447. /** Scrolls if necessary to make sure that a particular row is visible.
  32448. */
  32449. void scrollToEnsureRowIsOnscreen (int row);
  32450. /** Returns a pointer to the scrollbar.
  32451. (Unlikely to be useful for most people).
  32452. */
  32453. ScrollBar* getVerticalScrollBar() const throw();
  32454. /** Returns a pointer to the scrollbar.
  32455. (Unlikely to be useful for most people).
  32456. */
  32457. ScrollBar* getHorizontalScrollBar() const throw();
  32458. /** Finds the row index that contains a given x,y position.
  32459. The position is relative to the ListBox's top-left.
  32460. If no row exists at this position, the method will return -1.
  32461. @see getComponentForRowNumber
  32462. */
  32463. int getRowContainingPosition (int x, int y) const throw();
  32464. /** Finds a row index that would be the most suitable place to insert a new
  32465. item for a given position.
  32466. This is useful when the user is e.g. dragging and dropping onto the listbox,
  32467. because it lets you easily choose the best position to insert the item that
  32468. they drop, based on where they drop it.
  32469. If the position is out of range, this will return -1. If the position is
  32470. beyond the end of the list, it will return getNumRows() to indicate the end
  32471. of the list.
  32472. @see getComponentForRowNumber
  32473. */
  32474. int getInsertionIndexForPosition (int x, int y) const throw();
  32475. /** Returns the position of one of the rows, relative to the top-left of
  32476. the listbox.
  32477. This may be off-screen, and the range of the row number that is passed-in is
  32478. not checked to see if it's a valid row.
  32479. */
  32480. const Rectangle<int> getRowPosition (int rowNumber,
  32481. bool relativeToComponentTopLeft) const throw();
  32482. /** Finds the row component for a given row in the list.
  32483. The component returned will have been created using createRowComponent().
  32484. If the component for this row is off-screen or if the row is out-of-range,
  32485. this will return 0.
  32486. @see getRowContainingPosition
  32487. */
  32488. Component* getComponentForRowNumber (int rowNumber) const throw();
  32489. /** Returns the row number that the given component represents.
  32490. If the component isn't one of the list's rows, this will return -1.
  32491. */
  32492. int getRowNumberOfComponent (Component* rowComponent) const throw();
  32493. /** Returns the width of a row (which may be less than the width of this component
  32494. if there's a scrollbar).
  32495. */
  32496. int getVisibleRowWidth() const throw();
  32497. /** Sets the height of each row in the list.
  32498. The default height is 22 pixels.
  32499. @see getRowHeight
  32500. */
  32501. void setRowHeight (int newHeight);
  32502. /** Returns the height of a row in the list.
  32503. @see setRowHeight
  32504. */
  32505. int getRowHeight() const throw() { return rowHeight; }
  32506. /** Returns the number of rows actually visible.
  32507. This is the number of whole rows which will fit on-screen, so the value might
  32508. be more than the actual number of rows in the list.
  32509. */
  32510. int getNumRowsOnScreen() const throw();
  32511. /** A set of colour IDs to use to change the colour of various aspects of the label.
  32512. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32513. methods.
  32514. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32515. */
  32516. enum ColourIds
  32517. {
  32518. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  32519. Make this transparent if you don't want the background to be filled. */
  32520. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  32521. Make this transparent to not have an outline. */
  32522. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  32523. };
  32524. /** Sets the thickness of a border that will be drawn around the box.
  32525. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  32526. @see outlineColourId
  32527. */
  32528. void setOutlineThickness (int outlineThickness);
  32529. /** Returns the thickness of outline that will be drawn around the listbox.
  32530. @see setOutlineColour
  32531. */
  32532. int getOutlineThickness() const throw() { return outlineThickness; }
  32533. /** Sets a component that the list should use as a header.
  32534. This will position the given component at the top of the list, maintaining the
  32535. height of the component passed-in, but rescaling it horizontally to match the
  32536. width of the items in the listbox.
  32537. The component will be deleted when setHeaderComponent() is called with a
  32538. different component, or when the listbox is deleted.
  32539. */
  32540. void setHeaderComponent (Component* newHeaderComponent);
  32541. /** Changes the width of the rows in the list.
  32542. This can be used to make the list's row components wider than the list itself - the
  32543. width of the rows will be either the width of the list or this value, whichever is
  32544. greater, and if the rows become wider than the list, a horizontal scrollbar will
  32545. appear.
  32546. The default value for this is 0, which means that the rows will always
  32547. be the same width as the list.
  32548. */
  32549. void setMinimumContentWidth (int newMinimumWidth);
  32550. /** Returns the space currently available for the row items, taking into account
  32551. borders, scrollbars, etc.
  32552. */
  32553. int getVisibleContentWidth() const throw();
  32554. /** Repaints one of the rows.
  32555. This is a lightweight alternative to calling updateContent, and just causes a
  32556. repaint of the row's area.
  32557. */
  32558. void repaintRow (int rowNumber) throw();
  32559. /** This fairly obscure method creates an image that just shows the currently
  32560. selected row components.
  32561. It's a handy method for doing drag-and-drop, as it can be passed to the
  32562. DragAndDropContainer for use as the drag image.
  32563. Note that it will make the row components temporarily invisible, so if you're
  32564. using custom components this could affect them if they're sensitive to that
  32565. sort of thing.
  32566. @see Component::createComponentSnapshot
  32567. */
  32568. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  32569. /** Returns the viewport that this ListBox uses.
  32570. You may need to use this to change parameters such as whether scrollbars
  32571. are shown, etc.
  32572. */
  32573. Viewport* getViewport() const throw();
  32574. /** @internal */
  32575. bool keyPressed (const KeyPress& key);
  32576. /** @internal */
  32577. bool keyStateChanged (bool isKeyDown);
  32578. /** @internal */
  32579. void paint (Graphics& g);
  32580. /** @internal */
  32581. void paintOverChildren (Graphics& g);
  32582. /** @internal */
  32583. void resized();
  32584. /** @internal */
  32585. void visibilityChanged();
  32586. /** @internal */
  32587. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  32588. /** @internal */
  32589. void mouseMove (const MouseEvent&);
  32590. /** @internal */
  32591. void mouseExit (const MouseEvent&);
  32592. /** @internal */
  32593. void mouseUp (const MouseEvent&);
  32594. /** @internal */
  32595. void colourChanged();
  32596. /** @internal */
  32597. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  32598. private:
  32599. friend class ListViewport;
  32600. friend class TableListBox;
  32601. ListBoxModel* model;
  32602. ScopedPointer<ListViewport> viewport;
  32603. ScopedPointer<Component> headerComponent;
  32604. int totalItems, rowHeight, minimumRowWidth;
  32605. int outlineThickness;
  32606. int lastRowSelected;
  32607. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  32608. SparseSet <int> selected;
  32609. void selectRowInternal (int rowNumber,
  32610. bool dontScrollToShowThisRow,
  32611. bool deselectOthersFirst,
  32612. bool isMouseClick);
  32613. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  32614. };
  32615. #endif // __JUCE_LISTBOX_JUCEHEADER__
  32616. /*** End of inlined file: juce_ListBox.h ***/
  32617. /*** Start of inlined file: juce_TextButton.h ***/
  32618. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  32619. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  32620. /**
  32621. A button that uses the standard lozenge-shaped background with a line of
  32622. text on it.
  32623. @see Button, DrawableButton
  32624. */
  32625. class JUCE_API TextButton : public Button
  32626. {
  32627. public:
  32628. /** Creates a TextButton.
  32629. @param buttonName the text to put in the button (the component's name is also
  32630. initially set to this string, but these can be changed later
  32631. using the setName() and setButtonText() methods)
  32632. @param toolTip an optional string to use as a toolip
  32633. @see Button
  32634. */
  32635. TextButton (const String& buttonName = String::empty,
  32636. const String& toolTip = String::empty);
  32637. /** Destructor. */
  32638. ~TextButton();
  32639. /** A set of colour IDs to use to change the colour of various aspects of the button.
  32640. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32641. methods.
  32642. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32643. */
  32644. enum ColourIds
  32645. {
  32646. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  32647. 'off'). The look-and-feel class might re-interpret this to add
  32648. effects, etc. */
  32649. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  32650. 'on'). The look-and-feel class might re-interpret this to add
  32651. effects, etc. */
  32652. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  32653. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  32654. };
  32655. /** Resizes the button to fit neatly around its current text.
  32656. If newHeight is >= 0, the button's height will be changed to this
  32657. value. If it's less than zero, its height will be unaffected.
  32658. */
  32659. void changeWidthToFitText (int newHeight = -1);
  32660. /** This can be overridden to use different fonts than the default one.
  32661. Note that you'll need to set the font's size appropriately, too.
  32662. */
  32663. virtual const Font getFont();
  32664. protected:
  32665. /** @internal */
  32666. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  32667. /** @internal */
  32668. void colourChanged();
  32669. private:
  32670. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  32671. };
  32672. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  32673. /*** End of inlined file: juce_TextButton.h ***/
  32674. /**
  32675. A component displaying a list of plugins, with options to scan for them,
  32676. add, remove and sort them.
  32677. */
  32678. class JUCE_API PluginListComponent : public Component,
  32679. public ListBoxModel,
  32680. public ChangeListener,
  32681. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  32682. public Timer
  32683. {
  32684. public:
  32685. /**
  32686. Creates the list component.
  32687. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  32688. The properties file, if supplied, is used to store the user's last search paths.
  32689. */
  32690. PluginListComponent (KnownPluginList& listToRepresent,
  32691. const File& deadMansPedalFile,
  32692. PropertiesFile* propertiesToUse);
  32693. /** Destructor. */
  32694. ~PluginListComponent();
  32695. /** @internal */
  32696. void resized();
  32697. /** @internal */
  32698. bool isInterestedInFileDrag (const StringArray& files);
  32699. /** @internal */
  32700. void filesDropped (const StringArray& files, int, int);
  32701. /** @internal */
  32702. int getNumRows();
  32703. /** @internal */
  32704. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  32705. /** @internal */
  32706. void deleteKeyPressed (int lastRowSelected);
  32707. /** @internal */
  32708. void buttonClicked (Button* b);
  32709. /** @internal */
  32710. void changeListenerCallback (ChangeBroadcaster*);
  32711. /** @internal */
  32712. void timerCallback();
  32713. private:
  32714. KnownPluginList& list;
  32715. File deadMansPedalFile;
  32716. ListBox listBox;
  32717. TextButton optionsButton;
  32718. PropertiesFile* propertiesToUse;
  32719. int typeToScan;
  32720. void scanFor (AudioPluginFormat* format);
  32721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  32722. };
  32723. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  32724. /*** End of inlined file: juce_PluginListComponent.h ***/
  32725. #endif
  32726. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  32727. #endif
  32728. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32729. #endif
  32730. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32731. #endif
  32732. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  32733. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  32734. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  32735. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  32736. /**
  32737. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  32738. Use one of these objects if you want to wire-up a set of AudioProcessors
  32739. and play back the result.
  32740. Processors can be added to the graph as "nodes" using addNode(), and once
  32741. added, you can connect any of their input or output channels to other
  32742. nodes using addConnection().
  32743. To play back a graph through an audio device, you might want to use an
  32744. AudioProcessorPlayer object.
  32745. */
  32746. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  32747. public AsyncUpdater
  32748. {
  32749. public:
  32750. /** Creates an empty graph.
  32751. */
  32752. AudioProcessorGraph();
  32753. /** Destructor.
  32754. Any processor objects that have been added to the graph will also be deleted.
  32755. */
  32756. ~AudioProcessorGraph();
  32757. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  32758. To create a node, call AudioProcessorGraph::addNode().
  32759. */
  32760. class JUCE_API Node : public ReferenceCountedObject
  32761. {
  32762. public:
  32763. /** Destructor.
  32764. */
  32765. ~Node();
  32766. /** The ID number assigned to this node.
  32767. This is assigned by the graph that owns it, and can't be changed.
  32768. */
  32769. const uint32 id;
  32770. /** The actual processor object that this node represents. */
  32771. AudioProcessor* getProcessor() const throw() { return processor; }
  32772. /** A set of user-definable properties that are associated with this node.
  32773. This can be used to attach values to the node for whatever purpose seems
  32774. useful. For example, you might store an x and y position if your application
  32775. is displaying the nodes on-screen.
  32776. */
  32777. NamedValueSet properties;
  32778. /** A convenient typedef for referring to a pointer to a node object.
  32779. */
  32780. typedef ReferenceCountedObjectPtr <Node> Ptr;
  32781. private:
  32782. friend class AudioProcessorGraph;
  32783. const ScopedPointer<AudioProcessor> processor;
  32784. bool isPrepared;
  32785. Node (uint32 id, AudioProcessor* processor);
  32786. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  32787. void unprepare();
  32788. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  32789. };
  32790. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  32791. To create a connection, use AudioProcessorGraph::addConnection().
  32792. */
  32793. struct JUCE_API Connection
  32794. {
  32795. public:
  32796. /** The ID number of the node which is the input source for this connection.
  32797. @see AudioProcessorGraph::getNodeForId
  32798. */
  32799. uint32 sourceNodeId;
  32800. /** The index of the output channel of the source node from which this
  32801. connection takes its data.
  32802. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  32803. it is referring to the source node's midi output. Otherwise, it is the zero-based
  32804. index of an audio output channel in the source node.
  32805. */
  32806. int sourceChannelIndex;
  32807. /** The ID number of the node which is the destination for this connection.
  32808. @see AudioProcessorGraph::getNodeForId
  32809. */
  32810. uint32 destNodeId;
  32811. /** The index of the input channel of the destination node to which this
  32812. connection delivers its data.
  32813. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  32814. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  32815. index of an audio input channel in the destination node.
  32816. */
  32817. int destChannelIndex;
  32818. private:
  32819. JUCE_LEAK_DETECTOR (Connection);
  32820. };
  32821. /** Deletes all nodes and connections from this graph.
  32822. Any processor objects in the graph will be deleted.
  32823. */
  32824. void clear();
  32825. /** Returns the number of nodes in the graph. */
  32826. int getNumNodes() const { return nodes.size(); }
  32827. /** Returns a pointer to one of the nodes in the graph.
  32828. This will return 0 if the index is out of range.
  32829. @see getNodeForId
  32830. */
  32831. Node* getNode (const int index) const { return nodes [index]; }
  32832. /** Searches the graph for a node with the given ID number and returns it.
  32833. If no such node was found, this returns 0.
  32834. @see getNode
  32835. */
  32836. Node* getNodeForId (const uint32 nodeId) const;
  32837. /** Adds a node to the graph.
  32838. This creates a new node in the graph, for the specified processor. Once you have
  32839. added a processor to the graph, the graph owns it and will delete it later when
  32840. it is no longer needed.
  32841. The optional nodeId parameter lets you specify an ID to use for the node, but
  32842. if the value is already in use, this new node will overwrite the old one.
  32843. If this succeeds, it returns a pointer to the newly-created node.
  32844. */
  32845. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  32846. /** Deletes a node within the graph which has the specified ID.
  32847. This will also delete any connections that are attached to this node.
  32848. */
  32849. bool removeNode (uint32 nodeId);
  32850. /** Returns the number of connections in the graph. */
  32851. int getNumConnections() const { return connections.size(); }
  32852. /** Returns a pointer to one of the connections in the graph. */
  32853. const Connection* getConnection (int index) const { return connections [index]; }
  32854. /** Searches for a connection between some specified channels.
  32855. If no such connection is found, this returns 0.
  32856. */
  32857. const Connection* getConnectionBetween (uint32 sourceNodeId,
  32858. int sourceChannelIndex,
  32859. uint32 destNodeId,
  32860. int destChannelIndex) const;
  32861. /** Returns true if there is a connection between any of the channels of
  32862. two specified nodes.
  32863. */
  32864. bool isConnected (uint32 possibleSourceNodeId,
  32865. uint32 possibleDestNodeId) const;
  32866. /** Returns true if it would be legal to connect the specified points.
  32867. */
  32868. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  32869. uint32 destNodeId, int destChannelIndex) const;
  32870. /** Attempts to connect two specified channels of two nodes.
  32871. If this isn't allowed (e.g. because you're trying to connect a midi channel
  32872. to an audio one or other such nonsense), then it'll return false.
  32873. */
  32874. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  32875. uint32 destNodeId, int destChannelIndex);
  32876. /** Deletes the connection with the specified index.
  32877. Returns true if a connection was actually deleted.
  32878. */
  32879. void removeConnection (int index);
  32880. /** Deletes any connection between two specified points.
  32881. Returns true if a connection was actually deleted.
  32882. */
  32883. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  32884. uint32 destNodeId, int destChannelIndex);
  32885. /** Removes all connections from the specified node.
  32886. */
  32887. bool disconnectNode (uint32 nodeId);
  32888. /** Performs a sanity checks of all the connections.
  32889. This might be useful if some of the processors are doing things like changing
  32890. their channel counts, which could render some connections obsolete.
  32891. */
  32892. bool removeIllegalConnections();
  32893. /** A special number that represents the midi channel of a node.
  32894. This is used as a channel index value if you want to refer to the midi input
  32895. or output instead of an audio channel.
  32896. */
  32897. static const int midiChannelIndex;
  32898. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  32899. in order to use the audio that comes into and out of the graph itself.
  32900. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  32901. node in the graph which delivers the audio that is coming into the parent
  32902. graph. This allows you to stream the data to other nodes and process the
  32903. incoming audio.
  32904. Likewise, one of these in "output" mode can be sent data which it will add to
  32905. the sum of data being sent to the graph's output.
  32906. @see AudioProcessorGraph
  32907. */
  32908. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  32909. {
  32910. public:
  32911. /** Specifies the mode in which this processor will operate.
  32912. */
  32913. enum IODeviceType
  32914. {
  32915. audioInputNode, /**< In this mode, the processor has output channels
  32916. representing all the audio input channels that are
  32917. coming into its parent audio graph. */
  32918. audioOutputNode, /**< In this mode, the processor has input channels
  32919. representing all the audio output channels that are
  32920. going out of its parent audio graph. */
  32921. midiInputNode, /**< In this mode, the processor has a midi output which
  32922. delivers the same midi data that is arriving at its
  32923. parent graph. */
  32924. midiOutputNode /**< In this mode, the processor has a midi input and
  32925. any data sent to it will be passed out of the parent
  32926. graph. */
  32927. };
  32928. /** Returns the mode of this processor. */
  32929. IODeviceType getType() const { return type; }
  32930. /** Returns the parent graph to which this processor belongs, or 0 if it
  32931. hasn't yet been added to one. */
  32932. AudioProcessorGraph* getParentGraph() const { return graph; }
  32933. /** True if this is an audio or midi input. */
  32934. bool isInput() const;
  32935. /** True if this is an audio or midi output. */
  32936. bool isOutput() const;
  32937. AudioGraphIOProcessor (const IODeviceType type);
  32938. ~AudioGraphIOProcessor();
  32939. const String getName() const;
  32940. void fillInPluginDescription (PluginDescription& d) const;
  32941. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  32942. void releaseResources();
  32943. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  32944. const String getInputChannelName (int channelIndex) const;
  32945. const String getOutputChannelName (int channelIndex) const;
  32946. bool isInputChannelStereoPair (int index) const;
  32947. bool isOutputChannelStereoPair (int index) const;
  32948. bool acceptsMidi() const;
  32949. bool producesMidi() const;
  32950. bool hasEditor() const;
  32951. AudioProcessorEditor* createEditor();
  32952. int getNumParameters();
  32953. const String getParameterName (int);
  32954. float getParameter (int);
  32955. const String getParameterText (int);
  32956. void setParameter (int, float);
  32957. int getNumPrograms();
  32958. int getCurrentProgram();
  32959. void setCurrentProgram (int);
  32960. const String getProgramName (int);
  32961. void changeProgramName (int, const String&);
  32962. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  32963. void setStateInformation (const void* data, int sizeInBytes);
  32964. /** @internal */
  32965. void setParentGraph (AudioProcessorGraph* graph);
  32966. private:
  32967. const IODeviceType type;
  32968. AudioProcessorGraph* graph;
  32969. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  32970. };
  32971. // AudioProcessor methods:
  32972. const String getName() const;
  32973. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  32974. void releaseResources();
  32975. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  32976. const String getInputChannelName (int channelIndex) const;
  32977. const String getOutputChannelName (int channelIndex) const;
  32978. bool isInputChannelStereoPair (int index) const;
  32979. bool isOutputChannelStereoPair (int index) const;
  32980. bool acceptsMidi() const;
  32981. bool producesMidi() const;
  32982. bool hasEditor() const { return false; }
  32983. AudioProcessorEditor* createEditor() { return 0; }
  32984. int getNumParameters() { return 0; }
  32985. const String getParameterName (int) { return String::empty; }
  32986. float getParameter (int) { return 0; }
  32987. const String getParameterText (int) { return String::empty; }
  32988. void setParameter (int, float) { }
  32989. int getNumPrograms() { return 0; }
  32990. int getCurrentProgram() { return 0; }
  32991. void setCurrentProgram (int) { }
  32992. const String getProgramName (int) { return String::empty; }
  32993. void changeProgramName (int, const String&) { }
  32994. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  32995. void setStateInformation (const void* data, int sizeInBytes);
  32996. /** @internal */
  32997. void handleAsyncUpdate();
  32998. private:
  32999. ReferenceCountedArray <Node> nodes;
  33000. OwnedArray <Connection> connections;
  33001. int lastNodeId;
  33002. AudioSampleBuffer renderingBuffers;
  33003. OwnedArray <MidiBuffer> midiBuffers;
  33004. CriticalSection renderLock;
  33005. Array<void*> renderingOps;
  33006. friend class AudioGraphIOProcessor;
  33007. AudioSampleBuffer* currentAudioInputBuffer;
  33008. AudioSampleBuffer currentAudioOutputBuffer;
  33009. MidiBuffer* currentMidiInputBuffer;
  33010. MidiBuffer currentMidiOutputBuffer;
  33011. void clearRenderingSequence();
  33012. void buildRenderingSequence();
  33013. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  33014. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  33015. };
  33016. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  33017. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  33018. #endif
  33019. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  33020. #endif
  33021. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  33022. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  33023. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  33024. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  33025. /**
  33026. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  33027. To use one of these, just make it the callback used by your AudioIODevice, and
  33028. give it a processor to use by calling setProcessor().
  33029. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  33030. input to send both streams through the processor.
  33031. @see AudioProcessor, AudioProcessorGraph
  33032. */
  33033. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  33034. public MidiInputCallback
  33035. {
  33036. public:
  33037. /**
  33038. */
  33039. AudioProcessorPlayer();
  33040. /** Destructor. */
  33041. virtual ~AudioProcessorPlayer();
  33042. /** Sets the processor that should be played.
  33043. The processor that is passed in will not be deleted or owned by this object.
  33044. To stop anything playing, pass in 0 to this method.
  33045. */
  33046. void setProcessor (AudioProcessor* processorToPlay);
  33047. /** Returns the current audio processor that is being played.
  33048. */
  33049. AudioProcessor* getCurrentProcessor() const { return processor; }
  33050. /** Returns a midi message collector that you can pass midi messages to if you
  33051. want them to be injected into the midi stream that is being sent to the
  33052. processor.
  33053. */
  33054. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  33055. /** @internal */
  33056. void audioDeviceIOCallback (const float** inputChannelData,
  33057. int totalNumInputChannels,
  33058. float** outputChannelData,
  33059. int totalNumOutputChannels,
  33060. int numSamples);
  33061. /** @internal */
  33062. void audioDeviceAboutToStart (AudioIODevice* device);
  33063. /** @internal */
  33064. void audioDeviceStopped();
  33065. /** @internal */
  33066. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  33067. private:
  33068. AudioProcessor* processor;
  33069. CriticalSection lock;
  33070. double sampleRate;
  33071. int blockSize;
  33072. bool isPrepared;
  33073. int numInputChans, numOutputChans;
  33074. float* channels [128];
  33075. AudioSampleBuffer tempBuffer;
  33076. MidiBuffer incomingMidi;
  33077. MidiMessageCollector messageCollector;
  33078. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  33079. };
  33080. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  33081. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  33082. #endif
  33083. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  33084. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  33085. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  33086. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  33087. /*** Start of inlined file: juce_PropertyPanel.h ***/
  33088. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  33089. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  33090. /*** Start of inlined file: juce_PropertyComponent.h ***/
  33091. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  33092. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  33093. class EditableProperty;
  33094. /**
  33095. A base class for a component that goes in a PropertyPanel and displays one of
  33096. an item's properties.
  33097. Subclasses of this are used to display a property in various forms, e.g. a
  33098. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  33099. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  33100. A subclass must implement the refresh() method which will be called to tell the
  33101. component to update itself, and is also responsible for calling this it when the
  33102. item that it refers to is changed.
  33103. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  33104. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  33105. */
  33106. class JUCE_API PropertyComponent : public Component,
  33107. public SettableTooltipClient
  33108. {
  33109. public:
  33110. /** Creates a PropertyComponent.
  33111. @param propertyName the name is stored as this component's name, and is
  33112. used as the name displayed next to this component in
  33113. a property panel
  33114. @param preferredHeight the height that the component should be given - some
  33115. items may need to be larger than a normal row height.
  33116. This value can also be set if a subclass changes the
  33117. preferredHeight member variable.
  33118. */
  33119. PropertyComponent (const String& propertyName,
  33120. int preferredHeight = 25);
  33121. /** Destructor. */
  33122. ~PropertyComponent();
  33123. /** Returns this item's preferred height.
  33124. This value is specified either in the constructor or by a subclass changing the
  33125. preferredHeight member variable.
  33126. */
  33127. int getPreferredHeight() const throw() { return preferredHeight; }
  33128. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  33129. /** Updates the property component if the item it refers to has changed.
  33130. A subclass must implement this method, and other objects may call it to
  33131. force it to refresh itself.
  33132. The subclass should be economical in the amount of work is done, so for
  33133. example it should check whether it really needs to do a repaint rather than
  33134. just doing one every time this method is called, as it may be called when
  33135. the value being displayed hasn't actually changed.
  33136. */
  33137. virtual void refresh() = 0;
  33138. /** The default paint method fills the background and draws a label for the
  33139. item's name.
  33140. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  33141. */
  33142. void paint (Graphics& g);
  33143. /** The default resize method positions any child component to the right of this
  33144. one, based on the look and feel's default label size.
  33145. */
  33146. void resized();
  33147. /** By default, this just repaints the component. */
  33148. void enablementChanged();
  33149. protected:
  33150. /** Used by the PropertyPanel to determine how high this component needs to be.
  33151. A subclass can update this value in its constructor but shouldn't alter it later
  33152. as changes won't necessarily be picked up.
  33153. */
  33154. int preferredHeight;
  33155. private:
  33156. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  33157. };
  33158. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  33159. /*** End of inlined file: juce_PropertyComponent.h ***/
  33160. /**
  33161. A panel that holds a list of PropertyComponent objects.
  33162. This panel displays a list of PropertyComponents, and allows them to be organised
  33163. into collapsible sections.
  33164. To use, simply create one of these and add your properties to it with addProperties()
  33165. or addSection().
  33166. @see PropertyComponent
  33167. */
  33168. class JUCE_API PropertyPanel : public Component
  33169. {
  33170. public:
  33171. /** Creates an empty property panel. */
  33172. PropertyPanel();
  33173. /** Destructor. */
  33174. ~PropertyPanel();
  33175. /** Deletes all property components from the panel.
  33176. */
  33177. void clear();
  33178. /** Adds a set of properties to the panel.
  33179. The components in the list will be owned by this object and will be automatically
  33180. deleted later on when no longer needed.
  33181. These properties are added without them being inside a named section. If you
  33182. want them to be kept together in a collapsible section, use addSection() instead.
  33183. */
  33184. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  33185. /** Adds a set of properties to the panel.
  33186. These properties are added at the bottom of the list, under a section heading with
  33187. a plus/minus button that allows it to be opened and closed.
  33188. The components in the list will be owned by this object and will be automatically
  33189. deleted later on when no longer needed.
  33190. To add properies without them being in a section, use addProperties().
  33191. */
  33192. void addSection (const String& sectionTitle,
  33193. const Array <PropertyComponent*>& newPropertyComponents,
  33194. bool shouldSectionInitiallyBeOpen = true);
  33195. /** Calls the refresh() method of all PropertyComponents in the panel */
  33196. void refreshAll() const;
  33197. /** Returns a list of all the names of sections in the panel.
  33198. These are the sections that have been added with addSection().
  33199. */
  33200. const StringArray getSectionNames() const;
  33201. /** Returns true if the section at this index is currently open.
  33202. The index is from 0 up to the number of items returned by getSectionNames().
  33203. */
  33204. bool isSectionOpen (int sectionIndex) const;
  33205. /** Opens or closes one of the sections.
  33206. The index is from 0 up to the number of items returned by getSectionNames().
  33207. */
  33208. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  33209. /** Enables or disables one of the sections.
  33210. The index is from 0 up to the number of items returned by getSectionNames().
  33211. */
  33212. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  33213. /** Saves the current state of open/closed sections so it can be restored later.
  33214. The caller is responsible for deleting the object that is returned.
  33215. To restore this state, use restoreOpennessState().
  33216. @see restoreOpennessState
  33217. */
  33218. XmlElement* getOpennessState() const;
  33219. /** Restores a previously saved arrangement of open/closed sections.
  33220. This will try to restore a snapshot of the panel's state that was created by
  33221. the getOpennessState() method. If any of the sections named in the original
  33222. XML aren't present, they will be ignored.
  33223. @see getOpennessState
  33224. */
  33225. void restoreOpennessState (const XmlElement& newState);
  33226. /** Sets a message to be displayed when there are no properties in the panel.
  33227. The default message is "nothing selected".
  33228. */
  33229. void setMessageWhenEmpty (const String& newMessage);
  33230. /** Returns the message that is displayed when there are no properties.
  33231. @see setMessageWhenEmpty
  33232. */
  33233. const String& getMessageWhenEmpty() const;
  33234. /** @internal */
  33235. void paint (Graphics& g);
  33236. /** @internal */
  33237. void resized();
  33238. private:
  33239. Viewport viewport;
  33240. class PropertyHolderComponent;
  33241. PropertyHolderComponent* propertyHolderComponent;
  33242. String messageWhenEmpty;
  33243. void updatePropHolderLayout() const;
  33244. void updatePropHolderLayout (int width) const;
  33245. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  33246. };
  33247. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  33248. /*** End of inlined file: juce_PropertyPanel.h ***/
  33249. /**
  33250. A type of UI component that displays the parameters of an AudioProcessor as
  33251. a simple list of sliders.
  33252. This can be used for showing an editor for a processor that doesn't supply
  33253. its own custom editor.
  33254. @see AudioProcessor
  33255. */
  33256. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  33257. {
  33258. public:
  33259. GenericAudioProcessorEditor (AudioProcessor* owner);
  33260. ~GenericAudioProcessorEditor();
  33261. void paint (Graphics& g);
  33262. void resized();
  33263. private:
  33264. PropertyPanel panel;
  33265. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  33266. };
  33267. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  33268. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  33269. #endif
  33270. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  33271. /*** Start of inlined file: juce_Sampler.h ***/
  33272. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  33273. #define __JUCE_SAMPLER_JUCEHEADER__
  33274. /*** Start of inlined file: juce_Synthesiser.h ***/
  33275. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  33276. #define __JUCE_SYNTHESISER_JUCEHEADER__
  33277. /**
  33278. Describes one of the sounds that a Synthesiser can play.
  33279. A synthesiser can contain one or more sounds, and a sound can choose which
  33280. midi notes and channels can trigger it.
  33281. The SynthesiserSound is a passive class that just describes what the sound is -
  33282. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  33283. more than one SynthesiserVoice to play the same sound at the same time.
  33284. @see Synthesiser, SynthesiserVoice
  33285. */
  33286. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  33287. {
  33288. protected:
  33289. SynthesiserSound();
  33290. public:
  33291. /** Destructor. */
  33292. virtual ~SynthesiserSound();
  33293. /** Returns true if this sound should be played when a given midi note is pressed.
  33294. The Synthesiser will use this information when deciding which sounds to trigger
  33295. for a given note.
  33296. */
  33297. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  33298. /** Returns true if the sound should be triggered by midi events on a given channel.
  33299. The Synthesiser will use this information when deciding which sounds to trigger
  33300. for a given note.
  33301. */
  33302. virtual bool appliesToChannel (const int midiChannel) = 0;
  33303. /**
  33304. */
  33305. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  33306. private:
  33307. JUCE_LEAK_DETECTOR (SynthesiserSound);
  33308. };
  33309. /**
  33310. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  33311. A voice plays a single sound at a time, and a synthesiser holds an array of
  33312. voices so that it can play polyphonically.
  33313. @see Synthesiser, SynthesiserSound
  33314. */
  33315. class JUCE_API SynthesiserVoice
  33316. {
  33317. public:
  33318. /** Creates a voice. */
  33319. SynthesiserVoice();
  33320. /** Destructor. */
  33321. virtual ~SynthesiserVoice();
  33322. /** Returns the midi note that this voice is currently playing.
  33323. Returns a value less than 0 if no note is playing.
  33324. */
  33325. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  33326. /** Returns the sound that this voice is currently playing.
  33327. Returns 0 if it's not playing.
  33328. */
  33329. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  33330. /** Must return true if this voice object is capable of playing the given sound.
  33331. If there are different classes of sound, and different classes of voice, a voice can
  33332. choose which ones it wants to take on.
  33333. A typical implementation of this method may just return true if there's only one type
  33334. of voice and sound, or it might check the type of the sound object passed-in and
  33335. see if it's one that it understands.
  33336. */
  33337. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  33338. /** Called to start a new note.
  33339. This will be called during the rendering callback, so must be fast and thread-safe.
  33340. */
  33341. virtual void startNote (const int midiNoteNumber,
  33342. const float velocity,
  33343. SynthesiserSound* sound,
  33344. const int currentPitchWheelPosition) = 0;
  33345. /** Called to stop a note.
  33346. This will be called during the rendering callback, so must be fast and thread-safe.
  33347. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  33348. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  33349. and allow the synth to reassign it another sound.
  33350. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  33351. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  33352. finishes playing (during the rendering callback), it must make sure that it calls
  33353. clearCurrentNote().
  33354. */
  33355. virtual void stopNote (const bool allowTailOff) = 0;
  33356. /** Called to let the voice know that the pitch wheel has been moved.
  33357. This will be called during the rendering callback, so must be fast and thread-safe.
  33358. */
  33359. virtual void pitchWheelMoved (const int newValue) = 0;
  33360. /** Called to let the voice know that a midi controller has been moved.
  33361. This will be called during the rendering callback, so must be fast and thread-safe.
  33362. */
  33363. virtual void controllerMoved (const int controllerNumber,
  33364. const int newValue) = 0;
  33365. /** Renders the next block of data for this voice.
  33366. The output audio data must be added to the current contents of the buffer provided.
  33367. Only the region of the buffer between startSample and (startSample + numSamples)
  33368. should be altered by this method.
  33369. If the voice is currently silent, it should just return without doing anything.
  33370. If the sound that the voice is playing finishes during the course of this rendered
  33371. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  33372. The size of the blocks that are rendered can change each time it is called, and may
  33373. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  33374. the voice's methods will be called to tell it about note and controller events.
  33375. */
  33376. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  33377. int startSample,
  33378. int numSamples) = 0;
  33379. /** Returns true if the voice is currently playing a sound which is mapped to the given
  33380. midi channel.
  33381. If it's not currently playing, this will return false.
  33382. */
  33383. bool isPlayingChannel (int midiChannel) const;
  33384. /** Changes the voice's reference sample rate.
  33385. The rate is set so that subclasses know the output rate and can set their pitch
  33386. accordingly.
  33387. This method is called by the synth, and subclasses can access the current rate with
  33388. the currentSampleRate member.
  33389. */
  33390. void setCurrentPlaybackSampleRate (double newRate);
  33391. protected:
  33392. /** Returns the current target sample rate at which rendering is being done.
  33393. This is available for subclasses so they can pitch things correctly.
  33394. */
  33395. double getSampleRate() const { return currentSampleRate; }
  33396. /** Resets the state of this voice after a sound has finished playing.
  33397. The subclass must call this when it finishes playing a note and becomes available
  33398. to play new ones.
  33399. It must either call it in the stopNote() method, or if the voice is tailing off,
  33400. then it should call it later during the renderNextBlock method, as soon as it
  33401. finishes its tail-off.
  33402. It can also be called at any time during the render callback if the sound happens
  33403. to have finished, e.g. if it's playing a sample and the sample finishes.
  33404. */
  33405. void clearCurrentNote();
  33406. private:
  33407. friend class Synthesiser;
  33408. double currentSampleRate;
  33409. int currentlyPlayingNote;
  33410. uint32 noteOnTime;
  33411. SynthesiserSound::Ptr currentlyPlayingSound;
  33412. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  33413. };
  33414. /**
  33415. Base class for a musical device that can play sounds.
  33416. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  33417. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  33418. which can play back one of these sounds.
  33419. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  33420. set of sounds, and a set of voices it can use to play them. If you only give it
  33421. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  33422. have available.
  33423. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  33424. events that go in will be scanned for note on/off messages, and these are used to
  33425. start and stop the voices playing the appropriate sounds.
  33426. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  33427. noteOff() and other controller methods.
  33428. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  33429. what the target playback rate is. This value is passed on to the voices so that
  33430. they can pitch their output correctly.
  33431. */
  33432. class JUCE_API Synthesiser
  33433. {
  33434. public:
  33435. /** Creates a new synthesiser.
  33436. You'll need to add some sounds and voices before it'll make any sound..
  33437. */
  33438. Synthesiser();
  33439. /** Destructor. */
  33440. virtual ~Synthesiser();
  33441. /** Deletes all voices. */
  33442. void clearVoices();
  33443. /** Returns the number of voices that have been added. */
  33444. int getNumVoices() const { return voices.size(); }
  33445. /** Returns one of the voices that have been added. */
  33446. SynthesiserVoice* getVoice (int index) const;
  33447. /** Adds a new voice to the synth.
  33448. All the voices should be the same class of object and are treated equally.
  33449. The object passed in will be managed by the synthesiser, which will delete
  33450. it later on when no longer needed. The caller should not retain a pointer to the
  33451. voice.
  33452. */
  33453. void addVoice (SynthesiserVoice* newVoice);
  33454. /** Deletes one of the voices. */
  33455. void removeVoice (int index);
  33456. /** Deletes all sounds. */
  33457. void clearSounds();
  33458. /** Returns the number of sounds that have been added to the synth. */
  33459. int getNumSounds() const { return sounds.size(); }
  33460. /** Returns one of the sounds. */
  33461. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  33462. /** Adds a new sound to the synthesiser.
  33463. The object passed in is reference counted, so will be deleted when it is removed
  33464. from the synthesiser, and when no voices are still using it.
  33465. */
  33466. void addSound (const SynthesiserSound::Ptr& newSound);
  33467. /** Removes and deletes one of the sounds. */
  33468. void removeSound (int index);
  33469. /** If set to true, then the synth will try to take over an existing voice if
  33470. it runs out and needs to play another note.
  33471. The value of this boolean is passed into findFreeVoice(), so the result will
  33472. depend on the implementation of this method.
  33473. */
  33474. void setNoteStealingEnabled (bool shouldStealNotes);
  33475. /** Returns true if note-stealing is enabled.
  33476. @see setNoteStealingEnabled
  33477. */
  33478. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  33479. /** Triggers a note-on event.
  33480. The default method here will find all the sounds that want to be triggered by
  33481. this note/channel. For each sound, it'll try to find a free voice, and use the
  33482. voice to start playing the sound.
  33483. Subclasses might want to override this if they need a more complex algorithm.
  33484. This method will be called automatically according to the midi data passed into
  33485. renderNextBlock(), but may be called explicitly too.
  33486. */
  33487. virtual void noteOn (int midiChannel,
  33488. int midiNoteNumber,
  33489. float velocity);
  33490. /** Triggers a note-off event.
  33491. This will turn off any voices that are playing a sound for the given note/channel.
  33492. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  33493. (if they can do). If this is false, the notes will all be cut off immediately.
  33494. This method will be called automatically according to the midi data passed into
  33495. renderNextBlock(), but may be called explicitly too.
  33496. */
  33497. virtual void noteOff (int midiChannel,
  33498. int midiNoteNumber,
  33499. bool allowTailOff);
  33500. /** Turns off all notes.
  33501. This will turn off any voices that are playing a sound on the given midi channel.
  33502. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  33503. which channel they're playing.
  33504. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  33505. (if they can do). If this is false, the notes will all be cut off immediately.
  33506. This method will be called automatically according to the midi data passed into
  33507. renderNextBlock(), but may be called explicitly too.
  33508. */
  33509. virtual void allNotesOff (int midiChannel,
  33510. bool allowTailOff);
  33511. /** Sends a pitch-wheel message.
  33512. This will send a pitch-wheel message to any voices that are playing sounds on
  33513. the given midi channel.
  33514. This method will be called automatically according to the midi data passed into
  33515. renderNextBlock(), but may be called explicitly too.
  33516. @param midiChannel the midi channel for the event
  33517. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  33518. */
  33519. virtual void handlePitchWheel (int midiChannel,
  33520. int wheelValue);
  33521. /** Sends a midi controller message.
  33522. This will send a midi controller message to any voices that are playing sounds on
  33523. the given midi channel.
  33524. This method will be called automatically according to the midi data passed into
  33525. renderNextBlock(), but may be called explicitly too.
  33526. @param midiChannel the midi channel for the event
  33527. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  33528. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  33529. */
  33530. virtual void handleController (int midiChannel,
  33531. int controllerNumber,
  33532. int controllerValue);
  33533. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  33534. render.
  33535. This value is propagated to the voices so that they can use it to render the correct
  33536. pitches.
  33537. */
  33538. void setCurrentPlaybackSampleRate (double sampleRate);
  33539. /** Creates the next block of audio output.
  33540. This will process the next numSamples of data from all the voices, and add that output
  33541. to the audio block supplied, starting from the offset specified. Note that the
  33542. data will be added to the current contents of the buffer, so you should clear it
  33543. before calling this method if necessary.
  33544. The midi events in the inputMidi buffer are parsed for note and controller events,
  33545. and these are used to trigger the voices. Note that the startSample offset applies
  33546. both to the audio output buffer and the midi input buffer, so any midi events
  33547. with timestamps outside the specified region will be ignored.
  33548. */
  33549. void renderNextBlock (AudioSampleBuffer& outputAudio,
  33550. const MidiBuffer& inputMidi,
  33551. int startSample,
  33552. int numSamples);
  33553. protected:
  33554. /** This is used to control access to the rendering callback and the note trigger methods. */
  33555. CriticalSection lock;
  33556. OwnedArray <SynthesiserVoice> voices;
  33557. ReferenceCountedArray <SynthesiserSound> sounds;
  33558. /** The last pitch-wheel values for each midi channel. */
  33559. int lastPitchWheelValues [16];
  33560. /** Searches through the voices to find one that's not currently playing, and which
  33561. can play the given sound.
  33562. Returns 0 if all voices are busy and stealing isn't enabled.
  33563. This can be overridden to implement custom voice-stealing algorithms.
  33564. */
  33565. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  33566. const bool stealIfNoneAvailable) const;
  33567. /** Starts a specified voice playing a particular sound.
  33568. You'll probably never need to call this, it's used internally by noteOn(), but
  33569. may be needed by subclasses for custom behaviours.
  33570. */
  33571. void startVoice (SynthesiserVoice* voice,
  33572. SynthesiserSound* sound,
  33573. int midiChannel,
  33574. int midiNoteNumber,
  33575. float velocity);
  33576. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  33577. // Temporary method here to cause a compiler error - note the new parameters for this method.
  33578. int findFreeVoice (const bool) const { return 0; }
  33579. #endif
  33580. private:
  33581. double sampleRate;
  33582. uint32 lastNoteOnCounter;
  33583. bool shouldStealNotes;
  33584. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  33585. };
  33586. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  33587. /*** End of inlined file: juce_Synthesiser.h ***/
  33588. /**
  33589. A subclass of SynthesiserSound that represents a sampled audio clip.
  33590. This is a pretty basic sampler, and just attempts to load the whole audio stream
  33591. into memory.
  33592. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  33593. give it some SampledSound objects to play.
  33594. @see SamplerVoice, Synthesiser, SynthesiserSound
  33595. */
  33596. class JUCE_API SamplerSound : public SynthesiserSound
  33597. {
  33598. public:
  33599. /** Creates a sampled sound from an audio reader.
  33600. This will attempt to load the audio from the source into memory and store
  33601. it in this object.
  33602. @param name a name for the sample
  33603. @param source the audio to load. This object can be safely deleted by the
  33604. caller after this constructor returns
  33605. @param midiNotes the set of midi keys that this sound should be played on. This
  33606. is used by the SynthesiserSound::appliesToNote() method
  33607. @param midiNoteForNormalPitch the midi note at which the sample should be played
  33608. with its natural rate. All other notes will be pitched
  33609. up or down relative to this one
  33610. @param attackTimeSecs the attack (fade-in) time, in seconds
  33611. @param releaseTimeSecs the decay (fade-out) time, in seconds
  33612. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  33613. source, in seconds
  33614. */
  33615. SamplerSound (const String& name,
  33616. AudioFormatReader& source,
  33617. const BigInteger& midiNotes,
  33618. int midiNoteForNormalPitch,
  33619. double attackTimeSecs,
  33620. double releaseTimeSecs,
  33621. double maxSampleLengthSeconds);
  33622. /** Destructor. */
  33623. ~SamplerSound();
  33624. /** Returns the sample's name */
  33625. const String& getName() const { return name; }
  33626. /** Returns the audio sample data.
  33627. This could be 0 if there was a problem loading it.
  33628. */
  33629. AudioSampleBuffer* getAudioData() const { return data; }
  33630. bool appliesToNote (const int midiNoteNumber);
  33631. bool appliesToChannel (const int midiChannel);
  33632. private:
  33633. friend class SamplerVoice;
  33634. String name;
  33635. ScopedPointer <AudioSampleBuffer> data;
  33636. double sourceSampleRate;
  33637. BigInteger midiNotes;
  33638. int length, attackSamples, releaseSamples;
  33639. int midiRootNote;
  33640. JUCE_LEAK_DETECTOR (SamplerSound);
  33641. };
  33642. /**
  33643. A subclass of SynthesiserVoice that can play a SamplerSound.
  33644. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  33645. give it some SampledSound objects to play.
  33646. @see SamplerSound, Synthesiser, SynthesiserVoice
  33647. */
  33648. class JUCE_API SamplerVoice : public SynthesiserVoice
  33649. {
  33650. public:
  33651. /** Creates a SamplerVoice.
  33652. */
  33653. SamplerVoice();
  33654. /** Destructor. */
  33655. ~SamplerVoice();
  33656. bool canPlaySound (SynthesiserSound* sound);
  33657. void startNote (const int midiNoteNumber,
  33658. const float velocity,
  33659. SynthesiserSound* sound,
  33660. const int currentPitchWheelPosition);
  33661. void stopNote (const bool allowTailOff);
  33662. void pitchWheelMoved (const int newValue);
  33663. void controllerMoved (const int controllerNumber,
  33664. const int newValue);
  33665. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  33666. private:
  33667. double pitchRatio;
  33668. double sourceSamplePosition;
  33669. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  33670. bool isInAttack, isInRelease;
  33671. JUCE_LEAK_DETECTOR (SamplerVoice);
  33672. };
  33673. #endif // __JUCE_SAMPLER_JUCEHEADER__
  33674. /*** End of inlined file: juce_Sampler.h ***/
  33675. #endif
  33676. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  33677. #endif
  33678. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  33679. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  33680. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  33681. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  33682. /** Manages a list of ActionListeners, and can send them messages.
  33683. To quickly add methods to your class that can add/remove action
  33684. listeners and broadcast to them, you can derive from this.
  33685. @see ActionListener, ChangeListener
  33686. */
  33687. class JUCE_API ActionBroadcaster
  33688. {
  33689. public:
  33690. /** Creates an ActionBroadcaster. */
  33691. ActionBroadcaster();
  33692. /** Destructor. */
  33693. virtual ~ActionBroadcaster();
  33694. /** Adds a listener to the list.
  33695. Trying to add a listener that's already on the list will have no effect.
  33696. */
  33697. void addActionListener (ActionListener* listener);
  33698. /** Removes a listener from the list.
  33699. If the listener isn't on the list, this won't have any effect.
  33700. */
  33701. void removeActionListener (ActionListener* listener);
  33702. /** Removes all listeners from the list. */
  33703. void removeAllActionListeners();
  33704. /** Broadcasts a message to all the registered listeners.
  33705. @see ActionListener::actionListenerCallback
  33706. */
  33707. void sendActionMessage (const String& message) const;
  33708. private:
  33709. class CallbackReceiver : public MessageListener
  33710. {
  33711. public:
  33712. CallbackReceiver();
  33713. void handleMessage (const Message&);
  33714. ActionBroadcaster* owner;
  33715. };
  33716. friend class CallbackReceiver;
  33717. CallbackReceiver callback;
  33718. SortedSet <ActionListener*> actionListeners;
  33719. CriticalSection actionListenerLock;
  33720. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  33721. };
  33722. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  33723. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  33724. #endif
  33725. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  33726. #endif
  33727. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  33728. #endif
  33729. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  33730. #endif
  33731. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  33732. #endif
  33733. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  33734. #endif
  33735. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  33736. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  33737. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  33738. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  33739. class InterprocessConnectionServer;
  33740. /**
  33741. Manages a simple two-way messaging connection to another process, using either
  33742. a socket or a named pipe as the transport medium.
  33743. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  33744. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  33745. and incoming messages will result in a callback via the messageReceived()
  33746. method.
  33747. To open a pipe and wait for another client to connect to it, use the createPipe()
  33748. method.
  33749. To act as a socket server and create connections for one or more client, see the
  33750. InterprocessConnectionServer class.
  33751. @see InterprocessConnectionServer, Socket, NamedPipe
  33752. */
  33753. class JUCE_API InterprocessConnection : public Thread,
  33754. private MessageListener
  33755. {
  33756. public:
  33757. /** Creates a connection.
  33758. Connections are created manually, connecting them with the connectToSocket()
  33759. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  33760. when a client wants to connect.
  33761. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  33762. connectionLost() and messageReceived() methods will
  33763. always be made using the message thread; if false,
  33764. these will be called immediately on the connection's
  33765. own thread.
  33766. @param magicMessageHeaderNumber a magic number to use in the header to check the
  33767. validity of the data blocks being sent and received. This
  33768. can be any number, but the sender and receiver must obviously
  33769. use matching values or they won't recognise each other.
  33770. */
  33771. InterprocessConnection (bool callbacksOnMessageThread = true,
  33772. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  33773. /** Destructor. */
  33774. ~InterprocessConnection();
  33775. /** Tries to connect this object to a socket.
  33776. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  33777. object waiting to receive client connections on this port number.
  33778. @param hostName the host computer, either a network address or name
  33779. @param portNumber the socket port number to try to connect to
  33780. @param timeOutMillisecs how long to keep trying before giving up
  33781. @returns true if the connection is established successfully
  33782. @see Socket
  33783. */
  33784. bool connectToSocket (const String& hostName,
  33785. int portNumber,
  33786. int timeOutMillisecs);
  33787. /** Tries to connect the object to an existing named pipe.
  33788. For this to work, another process on the same computer must already have opened
  33789. an InterprocessConnection object and used createPipe() to create a pipe for this
  33790. to connect to.
  33791. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  33792. @returns true if it connects successfully.
  33793. @see createPipe, NamedPipe
  33794. */
  33795. bool connectToPipe (const String& pipeName,
  33796. int pipeReceiveMessageTimeoutMs = -1);
  33797. /** Tries to create a new pipe for other processes to connect to.
  33798. This creates a pipe with the given name, so that other processes can use
  33799. connectToPipe() to connect to the other end.
  33800. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  33801. If another process is already using this pipe, this will fail and return false.
  33802. */
  33803. bool createPipe (const String& pipeName,
  33804. int pipeReceiveMessageTimeoutMs = -1);
  33805. /** Disconnects and closes any currently-open sockets or pipes. */
  33806. void disconnect();
  33807. /** True if a socket or pipe is currently active. */
  33808. bool isConnected() const;
  33809. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  33810. StreamingSocket* getSocket() const throw() { return socket; }
  33811. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  33812. NamedPipe* getPipe() const throw() { return pipe; }
  33813. /** Returns the name of the machine at the other end of this connection.
  33814. This will return an empty string if the other machine isn't known for
  33815. some reason.
  33816. */
  33817. const String getConnectedHostName() const;
  33818. /** Tries to send a message to the other end of this connection.
  33819. This will fail if it's not connected, or if there's some kind of write error. If
  33820. it succeeds, the connection object at the other end will receive the message by
  33821. a callback to its messageReceived() method.
  33822. @see messageReceived
  33823. */
  33824. bool sendMessage (const MemoryBlock& message);
  33825. /** Called when the connection is first connected.
  33826. If the connection was created with the callbacksOnMessageThread flag set, then
  33827. this will be called on the message thread; otherwise it will be called on a server
  33828. thread.
  33829. */
  33830. virtual void connectionMade() = 0;
  33831. /** Called when the connection is broken.
  33832. If the connection was created with the callbacksOnMessageThread flag set, then
  33833. this will be called on the message thread; otherwise it will be called on a server
  33834. thread.
  33835. */
  33836. virtual void connectionLost() = 0;
  33837. /** Called when a message arrives.
  33838. When the object at the other end of this connection sends us a message with sendMessage(),
  33839. this callback is used to deliver it to us.
  33840. If the connection was created with the callbacksOnMessageThread flag set, then
  33841. this will be called on the message thread; otherwise it will be called on a server
  33842. thread.
  33843. @see sendMessage
  33844. */
  33845. virtual void messageReceived (const MemoryBlock& message) = 0;
  33846. private:
  33847. CriticalSection pipeAndSocketLock;
  33848. ScopedPointer <StreamingSocket> socket;
  33849. ScopedPointer <NamedPipe> pipe;
  33850. bool callbackConnectionState;
  33851. const bool useMessageThread;
  33852. const uint32 magicMessageHeader;
  33853. int pipeReceiveMessageTimeout;
  33854. friend class InterprocessConnectionServer;
  33855. void initialiseWithSocket (StreamingSocket* socket_);
  33856. void initialiseWithPipe (NamedPipe* pipe_);
  33857. void handleMessage (const Message& message);
  33858. void connectionMadeInt();
  33859. void connectionLostInt();
  33860. void deliverDataInt (const MemoryBlock& data);
  33861. bool readNextMessageInt();
  33862. void run();
  33863. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  33864. };
  33865. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  33866. /*** End of inlined file: juce_InterprocessConnection.h ***/
  33867. #endif
  33868. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  33869. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  33870. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  33871. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  33872. /**
  33873. An object that waits for client sockets to connect to a port on this host, and
  33874. creates InterprocessConnection objects for each one.
  33875. To use this, create a class derived from it which implements the createConnectionObject()
  33876. method, so that it creates suitable connection objects for each client that tries
  33877. to connect.
  33878. @see InterprocessConnection
  33879. */
  33880. class JUCE_API InterprocessConnectionServer : private Thread
  33881. {
  33882. public:
  33883. /** Creates an uninitialised server object.
  33884. */
  33885. InterprocessConnectionServer();
  33886. /** Destructor. */
  33887. ~InterprocessConnectionServer();
  33888. /** Starts an internal thread which listens on the given port number.
  33889. While this is running, in another process tries to connect with the
  33890. InterprocessConnection::connectToSocket() method, this object will call
  33891. createConnectionObject() to create a connection to that client.
  33892. Use stop() to stop the thread running.
  33893. @see createConnectionObject, stop
  33894. */
  33895. bool beginWaitingForSocket (int portNumber);
  33896. /** Terminates the listener thread, if it's active.
  33897. @see beginWaitingForSocket
  33898. */
  33899. void stop();
  33900. protected:
  33901. /** Creates a suitable connection object for a client process that wants to
  33902. connect to this one.
  33903. This will be called by the listener thread when a client process tries
  33904. to connect, and must return a new InterprocessConnection object that will
  33905. then run as this end of the connection.
  33906. @see InterprocessConnection
  33907. */
  33908. virtual InterprocessConnection* createConnectionObject() = 0;
  33909. private:
  33910. ScopedPointer <StreamingSocket> socket;
  33911. void run();
  33912. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  33913. };
  33914. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  33915. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  33916. #endif
  33917. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  33918. #endif
  33919. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  33920. #endif
  33921. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  33922. #endif
  33923. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  33924. /*** Start of inlined file: juce_MessageManager.h ***/
  33925. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  33926. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  33927. class Component;
  33928. class MessageManagerLock;
  33929. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  33930. */
  33931. typedef void* (MessageCallbackFunction) (void* userData);
  33932. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  33933. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  33934. */
  33935. class JUCE_API MessageManager
  33936. {
  33937. public:
  33938. /** Returns the global instance of the MessageManager. */
  33939. static MessageManager* getInstance() throw();
  33940. /** Runs the event dispatch loop until a stop message is posted.
  33941. This method is only intended to be run by the application's startup routine,
  33942. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  33943. @see stopDispatchLoop
  33944. */
  33945. void runDispatchLoop();
  33946. /** Sends a signal that the dispatch loop should terminate.
  33947. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  33948. will be interrupted and will return.
  33949. @see runDispatchLoop
  33950. */
  33951. void stopDispatchLoop();
  33952. /** Returns true if the stopDispatchLoop() method has been called.
  33953. */
  33954. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  33955. /** Synchronously dispatches messages until a given time has elapsed.
  33956. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  33957. otherwise returns true.
  33958. */
  33959. bool runDispatchLoopUntil (int millisecondsToRunFor);
  33960. /** Calls a function using the message-thread.
  33961. This can be used by any thread to cause this function to be called-back
  33962. by the message thread. If it's the message-thread that's calling this method,
  33963. then the function will just be called; if another thread is calling, a message
  33964. will be posted to the queue, and this method will block until that message
  33965. is delivered, the function is called, and the result is returned.
  33966. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  33967. thread has a critical section locked, which an unrelated message callback then tries to lock
  33968. before the message thread gets round to processing this callback.
  33969. @param callback the function to call - its signature must be @code
  33970. void* myCallbackFunction (void*) @endcode
  33971. @param userData a user-defined pointer that will be passed to the function that gets called
  33972. @returns the value that the callback function returns.
  33973. @see MessageManagerLock
  33974. */
  33975. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  33976. void* userData);
  33977. /** Returns true if the caller-thread is the message thread. */
  33978. bool isThisTheMessageThread() const throw();
  33979. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  33980. (Best to ignore this method unless you really know what you're doing..)
  33981. @see getCurrentMessageThread
  33982. */
  33983. void setCurrentThreadAsMessageThread();
  33984. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  33985. (Best to ignore this method unless you really know what you're doing..)
  33986. @see setCurrentMessageThread
  33987. */
  33988. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  33989. /** Returns true if the caller thread has currenltly got the message manager locked.
  33990. see the MessageManagerLock class for more info about this.
  33991. This will be true if the caller is the message thread, because that automatically
  33992. gains a lock while a message is being dispatched.
  33993. */
  33994. bool currentThreadHasLockedMessageManager() const throw();
  33995. /** Sends a message to all other JUCE applications that are running.
  33996. @param messageText the string that will be passed to the actionListenerCallback()
  33997. method of the broadcast listeners in the other app.
  33998. @see registerBroadcastListener, ActionListener
  33999. */
  34000. static void broadcastMessage (const String& messageText);
  34001. /** Registers a listener to get told about broadcast messages.
  34002. The actionListenerCallback() callback's string parameter
  34003. is the message passed into broadcastMessage().
  34004. @see broadcastMessage
  34005. */
  34006. void registerBroadcastListener (ActionListener* listener);
  34007. /** Deregisters a broadcast listener. */
  34008. void deregisterBroadcastListener (ActionListener* listener);
  34009. /** @internal */
  34010. void deliverMessage (Message*);
  34011. /** @internal */
  34012. void deliverBroadcastMessage (const String&);
  34013. /** @internal */
  34014. ~MessageManager() throw();
  34015. private:
  34016. MessageManager() throw();
  34017. friend class MessageListener;
  34018. friend class ChangeBroadcaster;
  34019. friend class ActionBroadcaster;
  34020. friend class CallbackMessage;
  34021. static MessageManager* instance;
  34022. SortedSet <const MessageListener*> messageListeners;
  34023. ScopedPointer <ActionBroadcaster> broadcaster;
  34024. friend class JUCEApplication;
  34025. bool quitMessagePosted, quitMessageReceived;
  34026. Thread::ThreadID messageThreadId;
  34027. static void* exitModalLoopCallback (void*);
  34028. void postMessageToQueue (Message* message);
  34029. static void doPlatformSpecificInitialisation();
  34030. static void doPlatformSpecificShutdown();
  34031. friend class MessageManagerLock;
  34032. Thread::ThreadID volatile threadWithLock;
  34033. CriticalSection lockingLock;
  34034. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  34035. };
  34036. /** Used to make sure that the calling thread has exclusive access to the message loop.
  34037. Because it's not thread-safe to call any of the Component or other UI classes
  34038. from threads other than the message thread, one of these objects can be used to
  34039. lock the message loop and allow this to be done. The message thread will be
  34040. suspended for the lifetime of the MessageManagerLock object, so create one on
  34041. the stack like this: @code
  34042. void MyThread::run()
  34043. {
  34044. someData = 1234;
  34045. const MessageManagerLock mmLock;
  34046. // the event loop will now be locked so it's safe to make a few calls..
  34047. myComponent->setBounds (newBounds);
  34048. myComponent->repaint();
  34049. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  34050. }
  34051. @endcode
  34052. Obviously be careful not to create one of these and leave it lying around, or
  34053. your app will grind to a halt!
  34054. Another caveat is that using this in conjunction with other CriticalSections
  34055. can create lots of interesting ways of producing a deadlock! In particular, if
  34056. your message thread calls stopThread() for a thread that uses these locks,
  34057. you'll get an (occasional) deadlock..
  34058. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  34059. */
  34060. class JUCE_API MessageManagerLock
  34061. {
  34062. public:
  34063. /** Tries to acquire a lock on the message manager.
  34064. The constructor attempts to gain a lock on the message loop, and the lock will be
  34065. kept for the lifetime of this object.
  34066. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  34067. this method will keep checking whether the thread has been given the
  34068. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  34069. without gaining the lock. If you pass a thread, you must check whether the lock was
  34070. successful by calling lockWasGained(). If this is false, your thread is being told to
  34071. die, so you should take evasive action.
  34072. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  34073. careful when doing this, because it's very easy to deadlock if your message thread
  34074. attempts to call stopThread() on a thread just as that thread attempts to get the
  34075. message lock.
  34076. If the calling thread already has the lock, nothing will be done, so it's safe and
  34077. quick to use these locks recursively.
  34078. E.g.
  34079. @code
  34080. void run()
  34081. {
  34082. ...
  34083. while (! threadShouldExit())
  34084. {
  34085. MessageManagerLock mml (Thread::getCurrentThread());
  34086. if (! mml.lockWasGained())
  34087. return; // another thread is trying to kill us!
  34088. ..do some locked stuff here..
  34089. }
  34090. ..and now the MM is now unlocked..
  34091. }
  34092. @endcode
  34093. */
  34094. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  34095. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  34096. instead of a thread.
  34097. See the MessageManagerLock (Thread*) constructor for details on how this works.
  34098. */
  34099. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  34100. /** Releases the current thread's lock on the message manager.
  34101. Make sure this object is created and deleted by the same thread,
  34102. otherwise there are no guarantees what will happen!
  34103. */
  34104. ~MessageManagerLock() throw();
  34105. /** Returns true if the lock was successfully acquired.
  34106. (See the constructor that takes a Thread for more info).
  34107. */
  34108. bool lockWasGained() const throw() { return locked; }
  34109. private:
  34110. class BlockingMessage;
  34111. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  34112. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  34113. bool locked;
  34114. void init (Thread* thread, ThreadPoolJob* job);
  34115. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  34116. };
  34117. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  34118. /*** End of inlined file: juce_MessageManager.h ***/
  34119. #endif
  34120. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  34121. /*** Start of inlined file: juce_MultiTimer.h ***/
  34122. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  34123. #define __JUCE_MULTITIMER_JUCEHEADER__
  34124. /**
  34125. A type of timer class that can run multiple timers with different frequencies,
  34126. all of which share a single callback.
  34127. This class is very similar to the Timer class, but allows you run multiple
  34128. separate timers, where each one has a unique ID number. The methods in this
  34129. class are exactly equivalent to those in Timer, but with the addition of
  34130. this ID number.
  34131. To use it, you need to create a subclass of MultiTimer, implementing the
  34132. timerCallback() method. Then you can start timers with startTimer(), and
  34133. each time the callback is triggered, it passes in the ID of the timer that
  34134. caused it.
  34135. @see Timer
  34136. */
  34137. class JUCE_API MultiTimer
  34138. {
  34139. protected:
  34140. /** Creates a MultiTimer.
  34141. When created, no timers are running, so use startTimer() to start things off.
  34142. */
  34143. MultiTimer() throw();
  34144. /** Creates a copy of another timer.
  34145. Note that this timer will not contain any running timers, even if the one you're
  34146. copying from was running.
  34147. */
  34148. MultiTimer (const MultiTimer& other) throw();
  34149. public:
  34150. /** Destructor. */
  34151. virtual ~MultiTimer();
  34152. /** The user-defined callback routine that actually gets called by each of the
  34153. timers that are running.
  34154. It's perfectly ok to call startTimer() or stopTimer() from within this
  34155. callback to change the subsequent intervals.
  34156. */
  34157. virtual void timerCallback (int timerId) = 0;
  34158. /** Starts a timer and sets the length of interval required.
  34159. If the timer is already started, this will reset it, so the
  34160. time between calling this method and the next timer callback
  34161. will not be less than the interval length passed in.
  34162. @param timerId a unique Id number that identifies the timer to
  34163. start. This is the id that will be passed back
  34164. to the timerCallback() method when this timer is
  34165. triggered
  34166. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  34167. rounded up to 1)
  34168. */
  34169. void startTimer (int timerId, int intervalInMilliseconds) throw();
  34170. /** Stops a timer.
  34171. If a timer has been started with the given ID number, it will be cancelled.
  34172. No more callbacks will be made for the specified timer after this method returns.
  34173. If this is called from a different thread, any callbacks that may
  34174. be currently executing may be allowed to finish before the method
  34175. returns.
  34176. */
  34177. void stopTimer (int timerId) throw();
  34178. /** Checks whether a timer has been started for a specified ID.
  34179. @returns true if a timer with the given ID is running.
  34180. */
  34181. bool isTimerRunning (int timerId) const throw();
  34182. /** Returns the interval for a specified timer ID.
  34183. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  34184. is running for the ID number specified.
  34185. */
  34186. int getTimerInterval (int timerId) const throw();
  34187. private:
  34188. class MultiTimerCallback;
  34189. CriticalSection timerListLock;
  34190. OwnedArray <MultiTimerCallback> timers;
  34191. MultiTimer& operator= (const MultiTimer&);
  34192. };
  34193. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  34194. /*** End of inlined file: juce_MultiTimer.h ***/
  34195. #endif
  34196. #ifndef __JUCE_TIMER_JUCEHEADER__
  34197. #endif
  34198. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  34199. /*** Start of inlined file: juce_ArrowButton.h ***/
  34200. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  34201. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  34202. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  34203. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  34204. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  34205. /**
  34206. An effect filter that adds a drop-shadow behind the image's content.
  34207. (This will only work on images/components that aren't opaque, of course).
  34208. When added to a component, this effect will draw a soft-edged
  34209. shadow based on what gets drawn inside it. The shadow will also
  34210. be applied to the component's children.
  34211. For speed, this doesn't use a proper gaussian blur, but cheats by
  34212. using a simple bilinear filter. If you need a really high-quality
  34213. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  34214. @see Component::setComponentEffect
  34215. */
  34216. class JUCE_API DropShadowEffect : public ImageEffectFilter
  34217. {
  34218. public:
  34219. /** Creates a default drop-shadow effect.
  34220. To customise the shadow's appearance, use the setShadowProperties()
  34221. method.
  34222. */
  34223. DropShadowEffect();
  34224. /** Destructor. */
  34225. ~DropShadowEffect();
  34226. /** Sets up parameters affecting the shadow's appearance.
  34227. @param newRadius the (approximate) radius of the blur used
  34228. @param newOpacity the opacity with which the shadow is rendered
  34229. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  34230. component's contents
  34231. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  34232. component's contents
  34233. */
  34234. void setShadowProperties (float newRadius,
  34235. float newOpacity,
  34236. int newShadowOffsetX,
  34237. int newShadowOffsetY);
  34238. /** @internal */
  34239. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  34240. private:
  34241. int offsetX, offsetY;
  34242. float radius, opacity;
  34243. JUCE_LEAK_DETECTOR (DropShadowEffect);
  34244. };
  34245. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  34246. /*** End of inlined file: juce_DropShadowEffect.h ***/
  34247. /**
  34248. A button with an arrow in it.
  34249. @see Button
  34250. */
  34251. class JUCE_API ArrowButton : public Button
  34252. {
  34253. public:
  34254. /** Creates an ArrowButton.
  34255. @param buttonName the name to give the button
  34256. @param arrowDirection the direction the arrow should point in, where 0.0 is
  34257. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  34258. @param arrowColour the colour to use for the arrow
  34259. */
  34260. ArrowButton (const String& buttonName,
  34261. float arrowDirection,
  34262. const Colour& arrowColour);
  34263. /** Destructor. */
  34264. ~ArrowButton();
  34265. protected:
  34266. /** @internal */
  34267. void paintButton (Graphics& g,
  34268. bool isMouseOverButton,
  34269. bool isButtonDown);
  34270. /** @internal */
  34271. void buttonStateChanged();
  34272. private:
  34273. Colour colour;
  34274. DropShadowEffect shadow;
  34275. Path path;
  34276. int offset;
  34277. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  34278. };
  34279. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  34280. /*** End of inlined file: juce_ArrowButton.h ***/
  34281. #endif
  34282. #ifndef __JUCE_BUTTON_JUCEHEADER__
  34283. #endif
  34284. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  34285. /*** Start of inlined file: juce_DrawableButton.h ***/
  34286. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  34287. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  34288. /*** Start of inlined file: juce_Drawable.h ***/
  34289. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  34290. #define __JUCE_DRAWABLE_JUCEHEADER__
  34291. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  34292. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  34293. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  34294. /**
  34295. Expresses a coordinate as a dynamically evaluated expression.
  34296. @see RelativePoint, RelativeRectangle
  34297. */
  34298. class JUCE_API RelativeCoordinate
  34299. {
  34300. public:
  34301. /** Creates a zero coordinate. */
  34302. RelativeCoordinate();
  34303. RelativeCoordinate (const Expression& expression);
  34304. RelativeCoordinate (const RelativeCoordinate& other);
  34305. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  34306. /** Creates an absolute position from the parent origin on either the X or Y axis.
  34307. @param absoluteDistanceFromOrigin the distance from the origin
  34308. */
  34309. RelativeCoordinate (double absoluteDistanceFromOrigin);
  34310. /** Recreates a coordinate from a string description.
  34311. The string will be parsed by ExpressionParser::parse().
  34312. @param stringVersion the expression to use
  34313. @see toString
  34314. */
  34315. RelativeCoordinate (const String& stringVersion);
  34316. /** Destructor. */
  34317. ~RelativeCoordinate();
  34318. bool operator== (const RelativeCoordinate& other) const throw();
  34319. bool operator!= (const RelativeCoordinate& other) const throw();
  34320. /** Calculates the absolute position of this coordinate.
  34321. You'll need to provide a suitable Expression::EvaluationContext for looking up any coordinates that may
  34322. be needed to calculate the result.
  34323. */
  34324. double resolve (const Expression::EvaluationContext* evaluationContext) const;
  34325. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  34326. This will recursively check any coordinates upon which this one depends.
  34327. */
  34328. bool references (const String& coordName, const Expression::EvaluationContext* evaluationContext) const;
  34329. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  34330. bool isRecursive (const Expression::EvaluationContext* evaluationContext) const;
  34331. /** Returns true if this coordinate depends on any other coordinates for its position. */
  34332. bool isDynamic() const;
  34333. /** Changes the value of this coord to make it resolve to the specified position.
  34334. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  34335. or relative position to whatever value is necessary to make its resultant position
  34336. match the position that is provided.
  34337. */
  34338. void moveToAbsolute (double absoluteTargetPosition, const Expression::EvaluationContext* evaluationContext);
  34339. /** Changes the name of a symbol if it is used as part of the coordinate's expression. */
  34340. void renameSymbolIfUsed (const String& oldName, const String& newName);
  34341. /** Returns the expression that defines this coordinate. */
  34342. const Expression& getExpression() const { return term; }
  34343. /** Returns a string which represents this coordinate.
  34344. For details of the string syntax, see the constructor notes.
  34345. */
  34346. const String toString() const;
  34347. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  34348. As well as avoiding using string literals in your code, using these preset values
  34349. has the advantage that all instances of the same string will share the same, reference-counted
  34350. String object, so if you have thousands of points which all refer to the same
  34351. anchor points, this can save a significant amount of memory allocation.
  34352. */
  34353. struct Strings
  34354. {
  34355. static const String parent; /**< "parent" */
  34356. static const String this_; /**< "this" */
  34357. static const String left; /**< "left" */
  34358. static const String right; /**< "right" */
  34359. static const String top; /**< "top" */
  34360. static const String bottom; /**< "bottom" */
  34361. static const String parentLeft; /**< "parent.left" */
  34362. static const String parentTop; /**< "parent.top" */
  34363. static const String parentRight; /**< "parent.right" */
  34364. static const String parentBottom; /**< "parent.bottom" */
  34365. };
  34366. private:
  34367. Expression term;
  34368. };
  34369. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  34370. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  34371. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  34372. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  34373. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  34374. /*** Start of inlined file: juce_RelativePoint.h ***/
  34375. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  34376. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  34377. /**
  34378. An X-Y position stored as a pair of RelativeCoordinate values.
  34379. @see RelativeCoordinate, RelativeRectangle
  34380. */
  34381. class JUCE_API RelativePoint
  34382. {
  34383. public:
  34384. /** Creates a point at the origin. */
  34385. RelativePoint();
  34386. /** Creates an absolute point, relative to the origin. */
  34387. RelativePoint (const Point<float>& absolutePoint);
  34388. /** Creates an absolute point, relative to the origin. */
  34389. RelativePoint (float absoluteX, float absoluteY);
  34390. /** Creates an absolute point from two coordinates. */
  34391. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  34392. /** Creates a point from a stringified representation.
  34393. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  34394. strings is explained in the RelativeCoordinate class.
  34395. @see toString
  34396. */
  34397. RelativePoint (const String& stringVersion);
  34398. bool operator== (const RelativePoint& other) const throw();
  34399. bool operator!= (const RelativePoint& other) const throw();
  34400. /** Calculates the absolute position of this point.
  34401. You'll need to provide a suitable Expression::EvaluationContext for looking up any coordinates that may
  34402. be needed to calculate the result.
  34403. */
  34404. const Point<float> resolve (const Expression::EvaluationContext* evaluationContext) const;
  34405. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  34406. Calling this will leave any anchor points unchanged, but will set any absolute
  34407. or relative positions to whatever values are necessary to make the resultant position
  34408. match the position that is provided.
  34409. */
  34410. void moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* evaluationContext);
  34411. /** Returns a string which represents this point.
  34412. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  34413. coordinates, see the RelativeCoordinate constructor notes.
  34414. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  34415. */
  34416. const String toString() const;
  34417. /** Renames a symbol if it is used by any of the coordinates.
  34418. This calls RelativeCoordinate::renameAnchorIfUsed() on its X and Y coordinates.
  34419. */
  34420. void renameSymbolIfUsed (const String& oldName, const String& newName);
  34421. /** Returns true if this point depends on any other coordinates for its position. */
  34422. bool isDynamic() const;
  34423. // The actual X and Y coords...
  34424. RelativeCoordinate x, y;
  34425. };
  34426. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  34427. /*** End of inlined file: juce_RelativePoint.h ***/
  34428. /*** Start of inlined file: juce_MarkerList.h ***/
  34429. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  34430. #define __JUCE_MARKERLIST_JUCEHEADER__
  34431. class Component;
  34432. /**
  34433. Holds a set of named marker points along a one-dimensional axis.
  34434. This class is used to store sets of X and Y marker points in components.
  34435. @see Component::getMarkers().
  34436. */
  34437. class JUCE_API MarkerList
  34438. {
  34439. public:
  34440. /** Creates an empty marker list. */
  34441. MarkerList();
  34442. /** Creates a copy of another marker list. */
  34443. MarkerList (const MarkerList& other);
  34444. /** Copies another marker list to this one. */
  34445. MarkerList& operator= (const MarkerList& other);
  34446. /** Destructor. */
  34447. ~MarkerList();
  34448. /** Represents a marker in a MarkerList. */
  34449. class JUCE_API Marker
  34450. {
  34451. public:
  34452. /** Creates a copy of another Marker. */
  34453. Marker (const Marker& other);
  34454. /** Creates a Marker with a given name and position. */
  34455. Marker (const String& name, const RelativeCoordinate& position);
  34456. /** The marker's name. */
  34457. String name;
  34458. /** The marker's position.
  34459. The expression used to define the coordinate may use the names of other
  34460. markers, so that markers can be linked in arbitrary ways, but be careful
  34461. not to create recursive loops of markers whose positions are based on each
  34462. other! It can also refer to "parent.right" and "parent.bottom" so that you
  34463. can set markers which are relative to the size of the component that contains
  34464. them.
  34465. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  34466. */
  34467. RelativeCoordinate position;
  34468. /** Returns true if both the names and positions of these two markers match. */
  34469. bool operator== (const Marker&) const throw();
  34470. /** Returns true if either the name or position of these two markers differ. */
  34471. bool operator!= (const Marker&) const throw();
  34472. };
  34473. /** Returns the number of markers in the list. */
  34474. int getNumMarkers() const throw();
  34475. /** Returns one of the markers in the list, by its index. */
  34476. const Marker* getMarker (int index) const throw();
  34477. /** Returns a named marker, or 0 if no such name is found.
  34478. Note that name comparisons are case-sensitive.
  34479. */
  34480. const Marker* getMarker (const String& name) const throw();
  34481. /** Evaluates the given marker and returns its absolute position.
  34482. The parent component must be supplied in case the marker's expression refers to
  34483. the size of its parent component.
  34484. */
  34485. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  34486. /** Sets the position of a marker.
  34487. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  34488. new marker is added.
  34489. */
  34490. void setMarker (const String& name, const RelativeCoordinate& position);
  34491. /** Deletes the marker at the given list index. */
  34492. void removeMarker (int index);
  34493. /** Deletes the marker with the given name. */
  34494. void removeMarker (const String& name);
  34495. /** Returns true if all the markers in these two lists match exactly. */
  34496. bool operator== (const MarkerList& other) const throw();
  34497. /** Returns true if not all the markers in these two lists match exactly. */
  34498. bool operator!= (const MarkerList& other) const throw();
  34499. /**
  34500. A class for receiving events when changes are made to a MarkerList.
  34501. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  34502. method, and it will be called when markers are moved, added, or deleted.
  34503. @see MarkerList::addListener, MarkerList::removeListener
  34504. */
  34505. class JUCE_API Listener
  34506. {
  34507. public:
  34508. /** Destructor. */
  34509. virtual ~Listener() {}
  34510. /** Called when something in the given marker list changes. */
  34511. virtual void markersChanged (MarkerList* markerList) = 0;
  34512. /** Called when the given marker list is being deleted. */
  34513. virtual void markerListBeingDeleted (MarkerList* markerList);
  34514. };
  34515. /** Registers a listener that will be called when the markers are changed. */
  34516. void addListener (Listener* listener);
  34517. /** Deregisters a previously-registered listener. */
  34518. void removeListener (Listener* listener);
  34519. /** Synchronously calls markersChanged() on all the registered listeners. */
  34520. void markersHaveChanged();
  34521. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  34522. class ValueTreeWrapper
  34523. {
  34524. public:
  34525. ValueTreeWrapper (const ValueTree& state);
  34526. ValueTree& getState() throw() { return state; }
  34527. int getNumMarkers() const;
  34528. const ValueTree getMarkerState (int index) const;
  34529. const ValueTree getMarkerState (const String& name) const;
  34530. bool containsMarker (const ValueTree& state) const;
  34531. const MarkerList::Marker getMarker (const ValueTree& state) const;
  34532. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  34533. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  34534. void applyTo (MarkerList& markerList);
  34535. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  34536. static const Identifier markerTag, nameProperty, posProperty;
  34537. private:
  34538. ValueTree state;
  34539. };
  34540. private:
  34541. OwnedArray<Marker> markers;
  34542. ListenerList<Listener> listeners;
  34543. JUCE_LEAK_DETECTOR (MarkerList);
  34544. };
  34545. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  34546. /*** End of inlined file: juce_MarkerList.h ***/
  34547. /**
  34548. Base class for Component::Positioners that are based upon relative coordinates.
  34549. */
  34550. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  34551. public ComponentListener,
  34552. public MarkerList::Listener,
  34553. public Expression::EvaluationContext
  34554. {
  34555. public:
  34556. RelativeCoordinatePositionerBase (Component& component_);
  34557. ~RelativeCoordinatePositionerBase();
  34558. const Expression getSymbolValue (const String& objectName, const String& member) const;
  34559. void componentMovedOrResized (Component&, bool, bool);
  34560. void componentParentHierarchyChanged (Component&);
  34561. void componentBeingDeleted (Component& component);
  34562. void markersChanged (MarkerList*);
  34563. void markerListBeingDeleted (MarkerList* markerList);
  34564. void apply();
  34565. bool addCoordinate (const RelativeCoordinate& coord);
  34566. bool addPoint (const RelativePoint& point);
  34567. protected:
  34568. virtual bool registerCoordinates() = 0;
  34569. virtual void applyToComponentBounds() = 0;
  34570. private:
  34571. Array <Component*> sourceComponents;
  34572. Array <MarkerList*> sourceMarkerLists;
  34573. bool registeredOk;
  34574. bool registerListeners (const Expression& e);
  34575. bool registerComponent (const String& componentID);
  34576. bool registerMarker (const String markerName);
  34577. void registerComponentListener (Component* const comp);
  34578. void registerMarkerListListener (MarkerList* const list);
  34579. void unregisterListeners();
  34580. Component* findComponent (const String& componentID) const;
  34581. Component* getSourceComponent (const String& objectName) const;
  34582. const Expression xToExpression (const Component* const source, const int x) const;
  34583. const Expression yToExpression (const Component* const source, const int y) const;
  34584. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  34585. };
  34586. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  34587. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  34588. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  34589. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  34590. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  34591. /**
  34592. Loads and maintains a tree of Components from a ValueTree that represents them.
  34593. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  34594. this class lets you register a set of type-handlers for the different components that
  34595. are involved, and then uses these types to re-create a set of components from its
  34596. stored state.
  34597. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  34598. then use registerTypeHandler() to give it a set of type handlers that can cope with
  34599. all the items in your tree. Then you can call getComponent() to build the component.
  34600. Once you've got the component you can either take it and delete the ComponentBuilder
  34601. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  34602. ValueTree and automatically update the component to reflect these changes.
  34603. */
  34604. class JUCE_API ComponentBuilder : public ValueTree::Listener
  34605. {
  34606. public:
  34607. /** Creates a ComponentBuilder that will use the given state.
  34608. Once you've created your builder, you should use registerTypeHandler() to register some
  34609. type handlers for it, and then you can call createComponent() or getManagedComponent()
  34610. to get the actual component.
  34611. */
  34612. explicit ComponentBuilder (const ValueTree& state);
  34613. /** Destructor. */
  34614. ~ComponentBuilder();
  34615. /** Returns the ValueTree that this builder is working with. */
  34616. ValueTree& getState() throw() { return state; }
  34617. /** Returns the ValueTree that this builder is working with. */
  34618. const ValueTree& getState() const throw() { return state; }
  34619. /** Returns the builder's component (creating it if necessary).
  34620. The first time that this method is called, the builder will attempt to create a component
  34621. from the ValueTree, so you must have registered some suitable type handlers before calling
  34622. this. If there's a problem and the component can't be created, this method returns 0.
  34623. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  34624. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  34625. when the builder is destroyed. If you want to get a component that you can delete yourself,
  34626. call createComponent() instead.
  34627. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  34628. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  34629. as they may be changed or removed.
  34630. */
  34631. Component* getManagedComponent();
  34632. /** Creates and returns a new instance of the component that the ValueTree represents.
  34633. The caller is responsible for using and deleting the object that is returned. Unlike
  34634. getManagedComponent(), the component that is returned will not be updated by the builder.
  34635. */
  34636. Component* createComponent();
  34637. /**
  34638. The class is a base class for objects that manage the loading of a type of component
  34639. from a ValueTree.
  34640. To store and re-load a tree of components as a ValueTree, each component type must have
  34641. a TypeHandler to represent it.
  34642. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  34643. */
  34644. class JUCE_API TypeHandler
  34645. {
  34646. public:
  34647. /** Creates a TypeHandler.
  34648. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  34649. */
  34650. explicit TypeHandler (const Identifier& valueTreeType);
  34651. /** Destructor. */
  34652. virtual ~TypeHandler();
  34653. /** Returns the type of the ValueTrees that this handler can parse. */
  34654. const Identifier& getType() const throw() { return valueTreeType; }
  34655. /** Returns the builder that this type is registered with. */
  34656. ComponentBuilder* getBuilder() const throw();
  34657. /** This method must create a new component from the given state, add it to the specified
  34658. parent component (which may be null), and return it.
  34659. The ValueTree will have been pre-checked to make sure that its type matches the type
  34660. that this handler supports.
  34661. There's no need to set the new Component's ID to match that of the state - the builder
  34662. will take care of that itself.
  34663. */
  34664. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  34665. /** This method must update an existing component from a new ValueTree state.
  34666. A component that has been created with addNewComponentFromState() may need to be updated
  34667. if the ValueTree changes, so this method is used to do that. Your implementation must do
  34668. whatever's necessary to update the component from the new state provided.
  34669. The ValueTree will have been pre-checked to make sure that its type matches the type
  34670. that this handler supports, and the component will have been created by this type's
  34671. addNewComponentFromState() method.
  34672. */
  34673. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  34674. private:
  34675. friend class ComponentBuilder;
  34676. ComponentBuilder* builder;
  34677. const Identifier valueTreeType;
  34678. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  34679. };
  34680. /** Adds a type handler that the builder can use when trying to load components.
  34681. @see Drawable::registerDrawableTypeHandlers()
  34682. */
  34683. void registerTypeHandler (TypeHandler* type);
  34684. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  34685. TypeHandler* getHandlerForState (const ValueTree& state) const;
  34686. /** Returns the number of registered type handlers.
  34687. @see getHandler, registerTypeHandler
  34688. */
  34689. int getNumHandlers() const throw();
  34690. /** Returns one of the registered type handlers.
  34691. @see getNumHandlers, registerTypeHandler
  34692. */
  34693. TypeHandler* getHandler (int index) const throw();
  34694. /** This class is used when references to images need to be stored in ValueTrees.
  34695. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  34696. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  34697. your app.
  34698. When you're loading components from a ValueTree that may need a way of loading images, you
  34699. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  34700. trying to load the component.
  34701. @see ComponentBuilder::setImageProvider()
  34702. */
  34703. class JUCE_API ImageProvider
  34704. {
  34705. public:
  34706. ImageProvider() {}
  34707. virtual ~ImageProvider() {}
  34708. /** Retrieves the image associated with this identifier, which could be any
  34709. kind of string, number, filename, etc.
  34710. The image that is returned will be owned by the caller, but it may come
  34711. from the ImageCache.
  34712. */
  34713. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  34714. /** Returns an identifier to be used to refer to a given image.
  34715. This is used when a reference to an image is stored in a ValueTree.
  34716. */
  34717. virtual const var getIdentifierForImage (const Image& image) = 0;
  34718. };
  34719. /** Gives the builder an ImageProvider object that the type handlers can use when
  34720. loading images from stored references.
  34721. The object that is passed in is not owned by the builder, so the caller must delete
  34722. it when it is no longer needed, but not while the builder may still be using it. To
  34723. clear the image provider, just call setImageProvider (0).
  34724. */
  34725. void setImageProvider (ImageProvider* newImageProvider) throw();
  34726. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  34727. ImageProvider* getImageProvider() const throw();
  34728. /** Updates the children of a parent component by updating them from the children of
  34729. a given ValueTree.
  34730. */
  34731. void updateChildComponents (Component& parent, const ValueTree& children);
  34732. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  34733. for that component.
  34734. */
  34735. static const Identifier idProperty;
  34736. /** @internal */
  34737. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  34738. /** @internal */
  34739. void valueTreeChildrenChanged (ValueTree& treeWhoseChildHasChanged);
  34740. /** @internal */
  34741. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  34742. private:
  34743. ValueTree state;
  34744. OwnedArray <TypeHandler> types;
  34745. ScopedPointer<Component> component;
  34746. ImageProvider* imageProvider;
  34747. #if JUCE_DEBUG
  34748. WeakReference<Component> componentRef;
  34749. #endif
  34750. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  34751. };
  34752. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  34753. /*** End of inlined file: juce_ComponentBuilder.h ***/
  34754. class DrawableComposite;
  34755. /**
  34756. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  34757. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  34758. */
  34759. class JUCE_API Drawable : public Component
  34760. {
  34761. protected:
  34762. /** The base class can't be instantiated directly.
  34763. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  34764. */
  34765. Drawable();
  34766. public:
  34767. /** Destructor. */
  34768. virtual ~Drawable();
  34769. /** Creates a deep copy of this Drawable object.
  34770. Use this to create a new copy of this and any sub-objects in the tree.
  34771. */
  34772. virtual Drawable* createCopy() const = 0;
  34773. /** Renders this Drawable object.
  34774. Note that the preferred way to render a drawable in future is by using it
  34775. as a component and adding it to a parent, so you might want to consider that
  34776. before using this method.
  34777. @see drawWithin
  34778. */
  34779. void draw (Graphics& g, float opacity,
  34780. const AffineTransform& transform = AffineTransform::identity) const;
  34781. /** Renders the Drawable at a given offset within the Graphics context.
  34782. The co-ordinates passed-in are used to translate the object relative to its own
  34783. origin before drawing it - this is basically a quick way of saying:
  34784. @code
  34785. draw (g, AffineTransform::translation (x, y)).
  34786. @endcode
  34787. Note that the preferred way to render a drawable in future is by using it
  34788. as a component and adding it to a parent, so you might want to consider that
  34789. before using this method.
  34790. */
  34791. void drawAt (Graphics& g, float x, float y, float opacity) const;
  34792. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  34793. changing its aspect-ratio.
  34794. The object can placed arbitrarily within the rectangle based on a Justification type,
  34795. and can either be made as big as possible, or just reduced to fit.
  34796. Note that the preferred way to render a drawable in future is by using it
  34797. as a component and adding it to a parent, so you might want to consider that
  34798. before using this method.
  34799. @param g the graphics context to render onto
  34800. @param destArea the target rectangle to fit the drawable into
  34801. @param placement defines the alignment and rescaling to use to fit
  34802. this object within the target rectangle.
  34803. @param opacity the opacity to use, in the range 0 to 1.0
  34804. */
  34805. void drawWithin (Graphics& g,
  34806. const Rectangle<float>& destArea,
  34807. const RectanglePlacement& placement,
  34808. float opacity) const;
  34809. /** Resets any transformations on this drawable, and positions its origin within
  34810. its parent component.
  34811. */
  34812. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  34813. /** Sets a transform for this drawable that will position it within the specified
  34814. area of its parent component.
  34815. */
  34816. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  34817. /** Returns the DrawableComposite that contains this object, if there is one. */
  34818. DrawableComposite* getParent() const;
  34819. /** Tries to turn some kind of image file into a drawable.
  34820. The data could be an image that the ImageFileFormat class understands, or it
  34821. could be SVG.
  34822. */
  34823. static Drawable* createFromImageData (const void* data, size_t numBytes);
  34824. /** Tries to turn a stream containing some kind of image data into a drawable.
  34825. The data could be an image that the ImageFileFormat class understands, or it
  34826. could be SVG.
  34827. */
  34828. static Drawable* createFromImageDataStream (InputStream& dataSource);
  34829. /** Tries to turn a file containing some kind of image data into a drawable.
  34830. The data could be an image that the ImageFileFormat class understands, or it
  34831. could be SVG.
  34832. */
  34833. static Drawable* createFromImageFile (const File& file);
  34834. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  34835. into a Drawable tree.
  34836. The object returned must be deleted by the caller. If something goes wrong
  34837. while parsing, it may return 0.
  34838. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  34839. implementation, but it can return the basic vector objects.
  34840. */
  34841. static Drawable* createFromSVG (const XmlElement& svgDocument);
  34842. /** Tries to create a Drawable from a previously-saved ValueTree.
  34843. The ValueTree must have been created by the createValueTree() method.
  34844. If there are any images used within the drawable, you'll need to provide a valid
  34845. ImageProvider object that can be used to retrieve these images from whatever type
  34846. of identifier is used to represent them.
  34847. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  34848. */
  34849. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  34850. /** Creates a ValueTree to represent this Drawable.
  34851. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  34852. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  34853. object that can be used to create storable representations of them.
  34854. */
  34855. virtual const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  34856. /** Returns the area that this drawble covers.
  34857. The result is expressed in this drawable's own coordinate space, and does not take
  34858. into account any transforms that may be applied to the component.
  34859. */
  34860. virtual const Rectangle<float> getDrawableBounds() const = 0;
  34861. /** Internal class used to manage ValueTrees that represent Drawables. */
  34862. class ValueTreeWrapperBase
  34863. {
  34864. public:
  34865. ValueTreeWrapperBase (const ValueTree& state);
  34866. ValueTree& getState() throw() { return state; }
  34867. const String getID() const;
  34868. void setID (const String& newID);
  34869. ValueTree state;
  34870. };
  34871. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  34872. load all the different Drawable types from a saved state.
  34873. @see ComponentBuilder::registerTypeHandler()
  34874. */
  34875. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  34876. protected:
  34877. friend class DrawableComposite;
  34878. friend class DrawableShape;
  34879. /** @internal */
  34880. void transformContextToCorrectOrigin (Graphics& g);
  34881. /** @internal */
  34882. void parentHierarchyChanged();
  34883. /** @internal */
  34884. void setBoundsToEnclose (const Rectangle<float>& area);
  34885. Point<int> originRelativeToComponent;
  34886. #ifndef DOXYGEN
  34887. /** Internal utility class used by Drawables. */
  34888. template <class DrawableType>
  34889. class Positioner : public RelativeCoordinatePositionerBase
  34890. {
  34891. public:
  34892. Positioner (DrawableType& component_)
  34893. : RelativeCoordinatePositionerBase (component_),
  34894. owner (component_)
  34895. {}
  34896. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  34897. void applyToComponentBounds() { owner.recalculateCoordinates (this); }
  34898. private:
  34899. DrawableType& owner;
  34900. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  34901. };
  34902. #endif
  34903. private:
  34904. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  34905. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  34906. };
  34907. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  34908. /*** End of inlined file: juce_Drawable.h ***/
  34909. /**
  34910. A button that displays a Drawable.
  34911. Up to three Drawable objects can be given to this button, to represent the
  34912. 'normal', 'over' and 'down' states.
  34913. @see Button
  34914. */
  34915. class JUCE_API DrawableButton : public Button
  34916. {
  34917. public:
  34918. enum ButtonStyle
  34919. {
  34920. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  34921. ImageRaw, /**< The button will just display the images in their normal size and position.
  34922. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  34923. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  34924. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  34925. };
  34926. /** Creates a DrawableButton.
  34927. After creating one of these, use setImages() to specify the drawables to use.
  34928. @param buttonName the name to give the component
  34929. @param buttonStyle the layout to use
  34930. @see ButtonStyle, setButtonStyle, setImages
  34931. */
  34932. DrawableButton (const String& buttonName,
  34933. ButtonStyle buttonStyle);
  34934. /** Destructor. */
  34935. ~DrawableButton();
  34936. /** Sets up the images to draw for the various button states.
  34937. The button will keep its own internal copies of these drawables.
  34938. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  34939. will be made of the object passed-in if it is non-zero.
  34940. @param overImage the thing to draw for the button's 'over' state - if this is
  34941. zero, the button's normal image will be used when the mouse is
  34942. over it. An internal copy will be made of the object passed-in
  34943. if it is non-zero.
  34944. @param downImage the thing to draw for the button's 'down' state - if this is
  34945. zero, the 'over' image will be used instead (or the normal image
  34946. as a last resort). An internal copy will be made of the object
  34947. passed-in if it is non-zero.
  34948. @param disabledImage an image to draw when the button is disabled. If this is zero,
  34949. the normal image will be drawn with a reduced opacity instead.
  34950. An internal copy will be made of the object passed-in if it is
  34951. non-zero.
  34952. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  34953. state is 'on'. If this is 0, the normal image is used instead
  34954. @param overImageOn same as the overImage, but this is used when the button's toggle
  34955. state is 'on'. If this is 0, the normalImageOn is drawn instead
  34956. @param downImageOn same as the downImage, but this is used when the button's toggle
  34957. state is 'on'. If this is 0, the overImageOn is drawn instead
  34958. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  34959. state is 'on'. If this is 0, the normal image will be drawn instead
  34960. with a reduced opacity
  34961. */
  34962. void setImages (const Drawable* normalImage,
  34963. const Drawable* overImage = 0,
  34964. const Drawable* downImage = 0,
  34965. const Drawable* disabledImage = 0,
  34966. const Drawable* normalImageOn = 0,
  34967. const Drawable* overImageOn = 0,
  34968. const Drawable* downImageOn = 0,
  34969. const Drawable* disabledImageOn = 0);
  34970. /** Changes the button's style.
  34971. @see ButtonStyle
  34972. */
  34973. void setButtonStyle (ButtonStyle newStyle);
  34974. /** Changes the button's background colours.
  34975. The toggledOffColour is the colour to use when the button's toggle state
  34976. is off, and toggledOnColour when it's on.
  34977. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  34978. used to fill the background of the component.
  34979. For an ImageOnButtonBackground style, the colour is used to draw the
  34980. button's lozenge shape and exactly how the colour's used will depend
  34981. on the LookAndFeel.
  34982. */
  34983. void setBackgroundColours (const Colour& toggledOffColour,
  34984. const Colour& toggledOnColour);
  34985. /** Returns the current background colour being used.
  34986. @see setBackgroundColour
  34987. */
  34988. const Colour& getBackgroundColour() const throw();
  34989. /** Gives the button an optional amount of space around the edge of the drawable.
  34990. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  34991. ones on a button background. If the button is too small for the given gap, a
  34992. smaller gap will be used.
  34993. By default there's a gap of about 3 pixels.
  34994. */
  34995. void setEdgeIndent (int numPixelsIndent);
  34996. /** Returns the image that the button is currently displaying. */
  34997. Drawable* getCurrentImage() const throw();
  34998. Drawable* getNormalImage() const throw();
  34999. Drawable* getOverImage() const throw();
  35000. Drawable* getDownImage() const throw();
  35001. /** A set of colour IDs to use to change the colour of various aspects of the link.
  35002. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35003. methods.
  35004. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35005. */
  35006. enum ColourIds
  35007. {
  35008. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  35009. };
  35010. protected:
  35011. /** @internal */
  35012. void paintButton (Graphics& g,
  35013. bool isMouseOverButton,
  35014. bool isButtonDown);
  35015. /** @internal */
  35016. void buttonStateChanged();
  35017. /** @internal */
  35018. void resized();
  35019. private:
  35020. ButtonStyle style;
  35021. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  35022. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  35023. Drawable* currentImage;
  35024. Colour backgroundOff, backgroundOn;
  35025. int edgeIndent;
  35026. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  35027. };
  35028. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  35029. /*** End of inlined file: juce_DrawableButton.h ***/
  35030. #endif
  35031. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  35032. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  35033. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  35034. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  35035. /**
  35036. A button showing an underlined weblink, that will launch the link
  35037. when it's clicked.
  35038. @see Button
  35039. */
  35040. class JUCE_API HyperlinkButton : public Button
  35041. {
  35042. public:
  35043. /** Creates a HyperlinkButton.
  35044. @param linkText the text that will be displayed in the button - this is
  35045. also set as the Component's name, but the text can be
  35046. changed later with the Button::getButtonText() method
  35047. @param linkURL the URL to launch when the user clicks the button
  35048. */
  35049. HyperlinkButton (const String& linkText,
  35050. const URL& linkURL);
  35051. /** Destructor. */
  35052. ~HyperlinkButton();
  35053. /** Changes the font to use for the text.
  35054. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  35055. to match the size of the component.
  35056. */
  35057. void setFont (const Font& newFont,
  35058. bool resizeToMatchComponentHeight,
  35059. const Justification& justificationType = Justification::horizontallyCentred);
  35060. /** A set of colour IDs to use to change the colour of various aspects of the link.
  35061. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35062. methods.
  35063. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35064. */
  35065. enum ColourIds
  35066. {
  35067. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  35068. };
  35069. /** Changes the URL that the button will trigger. */
  35070. void setURL (const URL& newURL) throw();
  35071. /** Returns the URL that the button will trigger. */
  35072. const URL& getURL() const throw() { return url; }
  35073. /** Resizes the button horizontally to fit snugly around the text.
  35074. This won't affect the button's height.
  35075. */
  35076. void changeWidthToFitText();
  35077. protected:
  35078. /** @internal */
  35079. void clicked();
  35080. /** @internal */
  35081. void colourChanged();
  35082. /** @internal */
  35083. void paintButton (Graphics& g,
  35084. bool isMouseOverButton,
  35085. bool isButtonDown);
  35086. private:
  35087. URL url;
  35088. Font font;
  35089. bool resizeFont;
  35090. Justification justification;
  35091. const Font getFontToUse() const;
  35092. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  35093. };
  35094. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  35095. /*** End of inlined file: juce_HyperlinkButton.h ***/
  35096. #endif
  35097. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  35098. /*** Start of inlined file: juce_ImageButton.h ***/
  35099. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  35100. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  35101. /**
  35102. As the title suggests, this is a button containing an image.
  35103. The colour and transparency of the image can be set to vary when the
  35104. button state changes.
  35105. @see Button, ShapeButton, TextButton
  35106. */
  35107. class JUCE_API ImageButton : public Button
  35108. {
  35109. public:
  35110. /** Creates an ImageButton.
  35111. Use setImage() to specify the image to use. The colours and opacities that
  35112. are specified here can be changed later using setDrawingOptions().
  35113. @param name the name to give the component
  35114. */
  35115. explicit ImageButton (const String& name);
  35116. /** Destructor. */
  35117. ~ImageButton();
  35118. /** Sets up the images to draw in various states.
  35119. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  35120. resized to the same dimensions as the normal image
  35121. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  35122. button when the button's size changes
  35123. @param preserveImageProportions if true then any rescaling of the image to fit
  35124. the button will keep the image's x and y proportions
  35125. correct - i.e. it won't distort its shape, although
  35126. this might create gaps around the edges
  35127. @param normalImage the image to use when the button is in its normal state.
  35128. button no longer needs it.
  35129. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  35130. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  35131. normal image - if this colour is transparent, no overlay
  35132. will be drawn. The overlay will be drawn over the top of the
  35133. image, so you can basically add a solid or semi-transparent
  35134. colour to the image to brighten or darken it
  35135. @param overImage the image to use when the mouse is over the button. If
  35136. you want to use the same image as was set in the normalImage
  35137. parameter, this value can be a null image.
  35138. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  35139. is over the button
  35140. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  35141. image when the mouse is over - if this colour is transparent,
  35142. no overlay will be drawn
  35143. @param downImage an image to use when the button is pressed down. If set
  35144. to a null image, the 'over' image will be drawn instead (or the
  35145. normal image if there isn't an 'over' image either).
  35146. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  35147. is pressed
  35148. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  35149. image when the button is pressed down - if this colour is
  35150. transparent, no overlay will be drawn
  35151. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  35152. whenever it's inside the button's bounding rectangle. If
  35153. set to values higher than 0, the mouse will only be
  35154. considered to be over the image when the value of the
  35155. image's alpha channel at that position is greater than
  35156. this level.
  35157. */
  35158. void setImages (bool resizeButtonNowToFitThisImage,
  35159. bool rescaleImagesWhenButtonSizeChanges,
  35160. bool preserveImageProportions,
  35161. const Image& normalImage,
  35162. float imageOpacityWhenNormal,
  35163. const Colour& overlayColourWhenNormal,
  35164. const Image& overImage,
  35165. float imageOpacityWhenOver,
  35166. const Colour& overlayColourWhenOver,
  35167. const Image& downImage,
  35168. float imageOpacityWhenDown,
  35169. const Colour& overlayColourWhenDown,
  35170. float hitTestAlphaThreshold = 0.0f);
  35171. /** Returns the currently set 'normal' image. */
  35172. const Image getNormalImage() const;
  35173. /** Returns the image that's drawn when the mouse is over the button.
  35174. If a valid 'over' image has been set, this will return it; otherwise it'll
  35175. just return the normal image.
  35176. */
  35177. const Image getOverImage() const;
  35178. /** Returns the image that's drawn when the button is held down.
  35179. If a valid 'down' image has been set, this will return it; otherwise it'll
  35180. return the 'over' image or normal image, depending on what's available.
  35181. */
  35182. const Image getDownImage() const;
  35183. protected:
  35184. /** @internal */
  35185. bool hitTest (int x, int y);
  35186. /** @internal */
  35187. void paintButton (Graphics& g,
  35188. bool isMouseOverButton,
  35189. bool isButtonDown);
  35190. private:
  35191. bool scaleImageToFit, preserveProportions;
  35192. unsigned char alphaThreshold;
  35193. int imageX, imageY, imageW, imageH;
  35194. Image normalImage, overImage, downImage;
  35195. float normalOpacity, overOpacity, downOpacity;
  35196. Colour normalOverlay, overOverlay, downOverlay;
  35197. const Image getCurrentImage() const;
  35198. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  35199. };
  35200. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  35201. /*** End of inlined file: juce_ImageButton.h ***/
  35202. #endif
  35203. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  35204. /*** Start of inlined file: juce_ShapeButton.h ***/
  35205. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  35206. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  35207. /**
  35208. A button that contains a filled shape.
  35209. @see Button, ImageButton, TextButton, ArrowButton
  35210. */
  35211. class JUCE_API ShapeButton : public Button
  35212. {
  35213. public:
  35214. /** Creates a ShapeButton.
  35215. @param name a name to give the component - see Component::setName()
  35216. @param normalColour the colour to fill the shape with when the mouse isn't over
  35217. @param overColour the colour to use when the mouse is over the shape
  35218. @param downColour the colour to use when the button is in the pressed-down state
  35219. */
  35220. ShapeButton (const String& name,
  35221. const Colour& normalColour,
  35222. const Colour& overColour,
  35223. const Colour& downColour);
  35224. /** Destructor. */
  35225. ~ShapeButton();
  35226. /** Sets the shape to use.
  35227. @param newShape the shape to use
  35228. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  35229. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  35230. the button is resized
  35231. @param hasDropShadow if true, the button will be given a drop-shadow effect
  35232. */
  35233. void setShape (const Path& newShape,
  35234. bool resizeNowToFitThisShape,
  35235. bool maintainShapeProportions,
  35236. bool hasDropShadow);
  35237. /** Set the colours to use for drawing the shape.
  35238. @param normalColour the colour to fill the shape with when the mouse isn't over
  35239. @param overColour the colour to use when the mouse is over the shape
  35240. @param downColour the colour to use when the button is in the pressed-down state
  35241. */
  35242. void setColours (const Colour& normalColour,
  35243. const Colour& overColour,
  35244. const Colour& downColour);
  35245. /** Sets up an outline to draw around the shape.
  35246. @param outlineColour the colour to use
  35247. @param outlineStrokeWidth the thickness of line to draw
  35248. */
  35249. void setOutline (const Colour& outlineColour,
  35250. float outlineStrokeWidth);
  35251. protected:
  35252. /** @internal */
  35253. void paintButton (Graphics& g,
  35254. bool isMouseOverButton,
  35255. bool isButtonDown);
  35256. private:
  35257. Colour normalColour, overColour, downColour, outlineColour;
  35258. DropShadowEffect shadow;
  35259. Path shape;
  35260. bool maintainShapeProportions;
  35261. float outlineWidth;
  35262. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  35263. };
  35264. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  35265. /*** End of inlined file: juce_ShapeButton.h ***/
  35266. #endif
  35267. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35268. #endif
  35269. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  35270. /*** Start of inlined file: juce_ToggleButton.h ***/
  35271. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  35272. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  35273. /**
  35274. A button that can be toggled on/off.
  35275. All buttons can be toggle buttons, but this lets you create one of the
  35276. standard ones which has a tick-box and a text label next to it.
  35277. @see Button, DrawableButton, TextButton
  35278. */
  35279. class JUCE_API ToggleButton : public Button
  35280. {
  35281. public:
  35282. /** Creates a ToggleButton.
  35283. @param buttonText the text to put in the button (the component's name is also
  35284. initially set to this string, but these can be changed later
  35285. using the setName() and setButtonText() methods)
  35286. */
  35287. explicit ToggleButton (const String& buttonText = String::empty);
  35288. /** Destructor. */
  35289. ~ToggleButton();
  35290. /** Resizes the button to fit neatly around its current text.
  35291. The button's height won't be affected, only its width.
  35292. */
  35293. void changeWidthToFitText();
  35294. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35295. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35296. methods.
  35297. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35298. */
  35299. enum ColourIds
  35300. {
  35301. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  35302. };
  35303. protected:
  35304. /** @internal */
  35305. void paintButton (Graphics& g,
  35306. bool isMouseOverButton,
  35307. bool isButtonDown);
  35308. /** @internal */
  35309. void colourChanged();
  35310. private:
  35311. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  35312. };
  35313. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  35314. /*** End of inlined file: juce_ToggleButton.h ***/
  35315. #endif
  35316. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  35317. /*** Start of inlined file: juce_ToolbarButton.h ***/
  35318. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  35319. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  35320. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  35321. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35322. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35323. /*** Start of inlined file: juce_Toolbar.h ***/
  35324. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35325. #define __JUCE_TOOLBAR_JUCEHEADER__
  35326. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  35327. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  35328. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  35329. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  35330. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  35331. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  35332. /**
  35333. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  35334. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  35335. derive your component from this class, and make sure that it is somewhere inside a
  35336. DragAndDropContainer component.
  35337. Note: If all that you need to do is to respond to files being drag-and-dropped from
  35338. the operating system onto your component, you don't need any of these classes: instead
  35339. see the FileDragAndDropTarget class.
  35340. @see DragAndDropContainer, FileDragAndDropTarget
  35341. */
  35342. class JUCE_API DragAndDropTarget
  35343. {
  35344. public:
  35345. /** Destructor. */
  35346. virtual ~DragAndDropTarget() {}
  35347. /** Callback to check whether this target is interested in the type of object being
  35348. dragged.
  35349. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  35350. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  35351. @returns true if this component wants to receive the other callbacks regarging this
  35352. type of object; if it returns false, no other callbacks will be made.
  35353. */
  35354. virtual bool isInterestedInDragSource (const String& sourceDescription,
  35355. Component* sourceComponent) = 0;
  35356. /** Callback to indicate that something is being dragged over this component.
  35357. This gets called when the user moves the mouse into this component while dragging
  35358. something.
  35359. Use this callback as a trigger to make your component repaint itself to give the
  35360. user feedback about whether the item can be dropped here or not.
  35361. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  35362. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  35363. @param x the mouse x position, relative to this component
  35364. @param y the mouse y position, relative to this component
  35365. @see itemDragExit
  35366. */
  35367. virtual void itemDragEnter (const String& sourceDescription,
  35368. Component* sourceComponent,
  35369. int x, int y);
  35370. /** Callback to indicate that the user is dragging something over this component.
  35371. This gets called when the user moves the mouse over this component while dragging
  35372. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  35373. this lets you know what happens in-between.
  35374. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  35375. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  35376. @param x the mouse x position, relative to this component
  35377. @param y the mouse y position, relative to this component
  35378. */
  35379. virtual void itemDragMove (const String& sourceDescription,
  35380. Component* sourceComponent,
  35381. int x, int y);
  35382. /** Callback to indicate that something has been dragged off the edge of this component.
  35383. This gets called when the user moves the mouse out of this component while dragging
  35384. something.
  35385. If you've used itemDragEnter() to repaint your component and give feedback, use this
  35386. as a signal to repaint it in its normal state.
  35387. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  35388. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  35389. @see itemDragEnter
  35390. */
  35391. virtual void itemDragExit (const String& sourceDescription,
  35392. Component* sourceComponent);
  35393. /** Callback to indicate that the user has dropped something onto this component.
  35394. When the user drops an item this get called, and you can use the description to
  35395. work out whether your object wants to deal with it or not.
  35396. Note that after this is called, the itemDragExit method may not be called, so you should
  35397. clean up in here if there's anything you need to do when the drag finishes.
  35398. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  35399. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  35400. @param x the mouse x position, relative to this component
  35401. @param y the mouse y position, relative to this component
  35402. */
  35403. virtual void itemDropped (const String& sourceDescription,
  35404. Component* sourceComponent,
  35405. int x, int y) = 0;
  35406. /** Overriding this allows the target to tell the drag container whether to
  35407. draw the drag image while the cursor is over it.
  35408. By default it returns true, but if you return false, then the normal drag
  35409. image will not be shown when the cursor is over this target.
  35410. */
  35411. virtual bool shouldDrawDragImageWhenOver();
  35412. };
  35413. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  35414. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  35415. /**
  35416. Enables drag-and-drop behaviour for a component and all its sub-components.
  35417. For a component to be able to make or receive drag-and-drop events, one of its parent
  35418. components must derive from this class. It's probably best for the top-level
  35419. component to implement it.
  35420. Then to start a drag operation, any sub-component can just call the startDragging()
  35421. method, and this object will take over, tracking the mouse and sending appropriate
  35422. callbacks to any child components derived from DragAndDropTarget which the mouse
  35423. moves over.
  35424. Note: If all that you need to do is to respond to files being drag-and-dropped from
  35425. the operating system onto your component, you don't need any of these classes: you can do this
  35426. simply by overriding Component::filesDropped().
  35427. @see DragAndDropTarget
  35428. */
  35429. class JUCE_API DragAndDropContainer
  35430. {
  35431. public:
  35432. /** Creates a DragAndDropContainer.
  35433. The object that derives from this class must also be a Component.
  35434. */
  35435. DragAndDropContainer();
  35436. /** Destructor. */
  35437. virtual ~DragAndDropContainer();
  35438. /** Begins a drag-and-drop operation.
  35439. This starts a drag-and-drop operation - call it when the user drags the
  35440. mouse in your drag-source component, and this object will track mouse
  35441. movements until the user lets go of the mouse button, and will send
  35442. appropriate messages to DragAndDropTarget objects that the mouse moves
  35443. over.
  35444. findParentDragContainerFor() is a handy method to call to find the
  35445. drag container to use for a component.
  35446. @param sourceDescription a string to use as the description of the thing being
  35447. dragged - this will be passed to the objects that might be
  35448. dropped-onto so they can decide if they want to handle it or
  35449. not
  35450. @param sourceComponent the component that is being dragged
  35451. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  35452. a snapshot of the sourceComponent will be used instead.
  35453. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  35454. window, and can be dragged to DragAndDropTargets that are the
  35455. children of components other than this one.
  35456. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  35457. at which the image should be drawn from the mouse. If it isn't
  35458. specified, then the image will be centred around the mouse. If
  35459. an image hasn't been passed-in, this will be ignored.
  35460. */
  35461. void startDragging (const String& sourceDescription,
  35462. Component* sourceComponent,
  35463. const Image& dragImage = Image::null,
  35464. bool allowDraggingToOtherJuceWindows = false,
  35465. const Point<int>* imageOffsetFromMouse = 0);
  35466. /** Returns true if something is currently being dragged. */
  35467. bool isDragAndDropActive() const;
  35468. /** Returns the description of the thing that's currently being dragged.
  35469. If nothing's being dragged, this will return an empty string, otherwise it's the
  35470. string that was passed into startDragging().
  35471. @see startDragging
  35472. */
  35473. const String getCurrentDragDescription() const;
  35474. /** Utility to find the DragAndDropContainer for a given Component.
  35475. This will search up this component's parent hierarchy looking for the first
  35476. parent component which is a DragAndDropContainer.
  35477. It's useful when a component wants to call startDragging but doesn't know
  35478. the DragAndDropContainer it should to use.
  35479. Obviously this may return 0 if it doesn't find a suitable component.
  35480. */
  35481. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  35482. /** This performs a synchronous drag-and-drop of a set of files to some external
  35483. application.
  35484. You can call this function in response to a mouseDrag callback, and it will
  35485. block, running its own internal message loop and tracking the mouse, while it
  35486. uses a native operating system drag-and-drop operation to move or copy some
  35487. files to another application.
  35488. @param files a list of filenames to drag
  35489. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  35490. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  35491. @returns true if the files were successfully dropped somewhere, or false if it
  35492. was interrupted
  35493. @see performExternalDragDropOfText
  35494. */
  35495. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  35496. /** This performs a synchronous drag-and-drop of a block of text to some external
  35497. application.
  35498. You can call this function in response to a mouseDrag callback, and it will
  35499. block, running its own internal message loop and tracking the mouse, while it
  35500. uses a native operating system drag-and-drop operation to move or copy some
  35501. text to another application.
  35502. @param text the text to copy
  35503. @returns true if the text was successfully dropped somewhere, or false if it
  35504. was interrupted
  35505. @see performExternalDragDropOfFiles
  35506. */
  35507. static bool performExternalDragDropOfText (const String& text);
  35508. protected:
  35509. /** Override this if you want to be able to perform an external drag a set of files
  35510. when the user drags outside of this container component.
  35511. This method will be called when a drag operation moves outside the Juce-based window,
  35512. and if you want it to then perform a file drag-and-drop, add the filenames you want
  35513. to the array passed in, and return true.
  35514. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  35515. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  35516. @param files on return, the filenames you want to drag
  35517. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  35518. it must make a copy of them (see the performExternalDragDropOfFiles()
  35519. method)
  35520. @see performExternalDragDropOfFiles
  35521. */
  35522. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  35523. Component* dragSourceComponent,
  35524. StringArray& files,
  35525. bool& canMoveFiles);
  35526. private:
  35527. friend class DragImageComponent;
  35528. ScopedPointer <Component> dragImageComponent;
  35529. String currentDragDesc;
  35530. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  35531. };
  35532. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  35533. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  35534. class ToolbarItemComponent;
  35535. class ToolbarItemFactory;
  35536. /**
  35537. A toolbar component.
  35538. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  35539. and looks after their order and layout.
  35540. Items (icon buttons or other custom components) are added to a toolbar using a
  35541. ToolbarItemFactory - each type of item is given a unique ID number, and a
  35542. toolbar might contain more than one instance of a particular item type.
  35543. Toolbars can be interactively customised, allowing the user to drag the items
  35544. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  35545. component as a source of new items.
  35546. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  35547. */
  35548. class JUCE_API Toolbar : public Component,
  35549. public DragAndDropContainer,
  35550. public DragAndDropTarget,
  35551. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  35552. {
  35553. public:
  35554. /** Creates an empty toolbar component.
  35555. To add some icons or other components to your toolbar, you'll need to
  35556. create a ToolbarItemFactory class that can create a suitable set of
  35557. ToolbarItemComponents.
  35558. @see ToolbarItemFactory, ToolbarItemComponents
  35559. */
  35560. Toolbar();
  35561. /** Destructor.
  35562. Any items on the bar will be deleted when the toolbar is deleted.
  35563. */
  35564. ~Toolbar();
  35565. /** Changes the bar's orientation.
  35566. @see isVertical
  35567. */
  35568. void setVertical (bool shouldBeVertical);
  35569. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  35570. You can change the bar's orientation with setVertical().
  35571. */
  35572. bool isVertical() const throw() { return vertical; }
  35573. /** Returns the depth of the bar.
  35574. If the bar is horizontal, this will return its height; if it's vertical, it
  35575. will return its width.
  35576. @see getLength
  35577. */
  35578. int getThickness() const throw();
  35579. /** Returns the length of the bar.
  35580. If the bar is horizontal, this will return its width; if it's vertical, it
  35581. will return its height.
  35582. @see getThickness
  35583. */
  35584. int getLength() const throw();
  35585. /** Deletes all items from the bar.
  35586. */
  35587. void clear();
  35588. /** Adds an item to the toolbar.
  35589. The factory's ToolbarItemFactory::createItem() will be called by this method
  35590. to create the component that will actually be added to the bar.
  35591. The new item will be inserted at the specified index (if the index is -1, it
  35592. will be added to the right-hand or bottom end of the bar).
  35593. Once added, the component will be automatically deleted by this object when it
  35594. is no longer needed.
  35595. @see ToolbarItemFactory
  35596. */
  35597. void addItem (ToolbarItemFactory& factory,
  35598. int itemId,
  35599. int insertIndex = -1);
  35600. /** Deletes one of the items from the bar.
  35601. */
  35602. void removeToolbarItem (int itemIndex);
  35603. /** Returns the number of items currently on the toolbar.
  35604. @see getItemId, getItemComponent
  35605. */
  35606. int getNumItems() const throw();
  35607. /** Returns the ID of the item with the given index.
  35608. If the index is less than zero or greater than the number of items,
  35609. this will return 0.
  35610. @see getNumItems
  35611. */
  35612. int getItemId (int itemIndex) const throw();
  35613. /** Returns the component being used for the item with the given index.
  35614. If the index is less than zero or greater than the number of items,
  35615. this will return 0.
  35616. @see getNumItems
  35617. */
  35618. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  35619. /** Clears this toolbar and adds to it the default set of items that the specified
  35620. factory creates.
  35621. @see ToolbarItemFactory::getDefaultItemSet
  35622. */
  35623. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  35624. /** Options for the way items should be displayed.
  35625. @see setStyle, getStyle
  35626. */
  35627. enum ToolbarItemStyle
  35628. {
  35629. iconsOnly, /**< Means that the toolbar should just contain icons. */
  35630. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  35631. textOnly /**< Means that the toolbar only display text labels for each item. */
  35632. };
  35633. /** Returns the toolbar's current style.
  35634. @see ToolbarItemStyle, setStyle
  35635. */
  35636. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  35637. /** Changes the toolbar's current style.
  35638. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  35639. */
  35640. void setStyle (const ToolbarItemStyle& newStyle);
  35641. /** Flags used by the showCustomisationDialog() method. */
  35642. enum CustomisationFlags
  35643. {
  35644. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  35645. show the "icons only" option on its choice of toolbar styles. */
  35646. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  35647. show the "icons with text" option on its choice of toolbar styles. */
  35648. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  35649. show the "text only" option on its choice of toolbar styles. */
  35650. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  35651. show a button to reset the toolbar to its default set of items. */
  35652. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  35653. };
  35654. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  35655. The dialog contains a ToolbarItemPalette and various controls for editing other
  35656. aspects of the toolbar. This method will block and run the dialog box modally,
  35657. returning when the user closes it.
  35658. The factory is used to determine the set of items that will be shown on the
  35659. palette.
  35660. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  35661. enum.
  35662. @see ToolbarItemPalette
  35663. */
  35664. void showCustomisationDialog (ToolbarItemFactory& factory,
  35665. int optionFlags = allCustomisationOptionsEnabled);
  35666. /** Turns on or off the toolbar's editing mode, in which its items can be
  35667. rearranged by the user.
  35668. (In most cases it's easier just to use showCustomisationDialog() instead of
  35669. trying to enable editing directly).
  35670. @see ToolbarItemPalette
  35671. */
  35672. void setEditingActive (bool editingEnabled);
  35673. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  35674. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35675. methods.
  35676. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35677. */
  35678. enum ColourIds
  35679. {
  35680. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  35681. more control over this, override LookAndFeel::paintToolbarBackground(). */
  35682. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  35683. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  35684. over them. */
  35685. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  35686. held down on them. */
  35687. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  35688. when the style is set to iconsWithText or textOnly. */
  35689. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  35690. the customisation dialog is active and the mouse moves over them. */
  35691. };
  35692. /** Returns a string that represents the toolbar's current set of items.
  35693. This lets you later restore the same item layout using restoreFromString().
  35694. @see restoreFromString
  35695. */
  35696. const String toString() const;
  35697. /** Restores a set of items that was previously stored in a string by the toString()
  35698. method.
  35699. The factory object is used to create any item components that are needed.
  35700. @see toString
  35701. */
  35702. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  35703. const String& savedVersion);
  35704. /** @internal */
  35705. void paint (Graphics& g);
  35706. /** @internal */
  35707. void resized();
  35708. /** @internal */
  35709. void buttonClicked (Button*);
  35710. /** @internal */
  35711. void mouseDown (const MouseEvent&);
  35712. /** @internal */
  35713. bool isInterestedInDragSource (const String&, Component*);
  35714. /** @internal */
  35715. void itemDragMove (const String&, Component*, int, int);
  35716. /** @internal */
  35717. void itemDragExit (const String&, Component*);
  35718. /** @internal */
  35719. void itemDropped (const String&, Component*, int, int);
  35720. /** @internal */
  35721. void updateAllItemPositions (bool animate);
  35722. /** @internal */
  35723. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  35724. private:
  35725. ScopedPointer<Button> missingItemsButton;
  35726. bool vertical, isEditingActive;
  35727. ToolbarItemStyle toolbarStyle;
  35728. class MissingItemsComponent;
  35729. friend class MissingItemsComponent;
  35730. OwnedArray <ToolbarItemComponent> items;
  35731. friend class ItemDragAndDropOverlayComponent;
  35732. static const char* const toolbarDragDescriptor;
  35733. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  35734. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  35735. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  35736. };
  35737. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  35738. /*** End of inlined file: juce_Toolbar.h ***/
  35739. class ItemDragAndDropOverlayComponent;
  35740. /**
  35741. A component that can be used as one of the items in a Toolbar.
  35742. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  35743. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  35744. class for further info about creating them.
  35745. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  35746. components too. To do this, set the value of isBeingUsedAsAButton to false when
  35747. calling the constructor, and override contentAreaChanged(), in which you can position
  35748. any sub-components you need to add.
  35749. To add basic buttons without writing a special subclass, have a look at the
  35750. ToolbarButton class.
  35751. @see ToolbarButton, Toolbar, ToolbarItemFactory
  35752. */
  35753. class JUCE_API ToolbarItemComponent : public Button
  35754. {
  35755. public:
  35756. /** Constructor.
  35757. @param itemId the ID of the type of toolbar item which this represents
  35758. @param labelText the text to display if the toolbar's style is set to
  35759. Toolbar::iconsWithText or Toolbar::textOnly
  35760. @param isBeingUsedAsAButton set this to false if you don't want the button
  35761. to draw itself with button over/down states when the mouse
  35762. moves over it or clicks
  35763. */
  35764. ToolbarItemComponent (int itemId,
  35765. const String& labelText,
  35766. bool isBeingUsedAsAButton);
  35767. /** Destructor. */
  35768. ~ToolbarItemComponent();
  35769. /** Returns the item type ID that this component represents.
  35770. This value is in the constructor.
  35771. */
  35772. int getItemId() const throw() { return itemId; }
  35773. /** Returns the toolbar that contains this component, or 0 if it's not currently
  35774. inside one.
  35775. */
  35776. Toolbar* getToolbar() const;
  35777. /** Returns true if this component is currently inside a toolbar which is vertical.
  35778. @see Toolbar::isVertical
  35779. */
  35780. bool isToolbarVertical() const;
  35781. /** Returns the current style setting of this item.
  35782. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  35783. @see setStyle, Toolbar::getStyle
  35784. */
  35785. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  35786. /** Changes the current style setting of this item.
  35787. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  35788. by the toolbar that holds this item.
  35789. @see setStyle, Toolbar::setStyle
  35790. */
  35791. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  35792. /** Returns the area of the component that should be used to display the button image or
  35793. other contents of the item.
  35794. This content area may change when the item's style changes, and may leave a space around the
  35795. edge of the component where the text label can be shown.
  35796. @see contentAreaChanged
  35797. */
  35798. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  35799. /** This method must return the size criteria for this item, based on a given toolbar
  35800. size and orientation.
  35801. The preferredSize, minSize and maxSize values must all be set by your implementation
  35802. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  35803. toolbar, they refer to the item's height.
  35804. The preferredSize is the size that the component would like to be, and this must be
  35805. between the min and max sizes. For a fixed-size item, simply set all three variables to
  35806. the same value.
  35807. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  35808. Toolbar::getThickness().
  35809. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  35810. vertically.
  35811. */
  35812. virtual bool getToolbarItemSizes (int toolbarThickness,
  35813. bool isToolbarVertical,
  35814. int& preferredSize,
  35815. int& minSize,
  35816. int& maxSize) = 0;
  35817. /** Your subclass should use this method to draw its content area.
  35818. The graphics object that is passed-in will have been clipped and had its origin
  35819. moved to fit the content area as specified get getContentArea(). The width and height
  35820. parameters are the width and height of the content area.
  35821. If the component you're writing isn't a button, you can just do nothing in this method.
  35822. */
  35823. virtual void paintButtonArea (Graphics& g,
  35824. int width, int height,
  35825. bool isMouseOver, bool isMouseDown) = 0;
  35826. /** Callback to indicate that the content area of this item has changed.
  35827. This might be because the component was resized, or because the style changed and
  35828. the space needed for the text label is different.
  35829. See getContentArea() for a description of what the area is.
  35830. */
  35831. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  35832. /** Editing modes.
  35833. These are used by setEditingMode(), but will be rarely needed in user code.
  35834. */
  35835. enum ToolbarEditingMode
  35836. {
  35837. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  35838. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  35839. customisation mode, and the items can be dragged around. */
  35840. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  35841. dragged onto a toolbar to add it to that bar.*/
  35842. };
  35843. /** Changes the editing mode of this component.
  35844. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  35845. and is unlikely to be of much use in end-user-code.
  35846. */
  35847. void setEditingMode (const ToolbarEditingMode newMode);
  35848. /** Returns the current editing mode of this component.
  35849. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  35850. and is unlikely to be of much use in end-user-code.
  35851. */
  35852. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  35853. /** @internal */
  35854. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  35855. /** @internal */
  35856. void resized();
  35857. private:
  35858. friend class Toolbar;
  35859. friend class ItemDragAndDropOverlayComponent;
  35860. const int itemId;
  35861. ToolbarEditingMode mode;
  35862. Toolbar::ToolbarItemStyle toolbarStyle;
  35863. ScopedPointer <Component> overlayComp;
  35864. int dragOffsetX, dragOffsetY;
  35865. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  35866. Rectangle<int> contentArea;
  35867. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  35868. };
  35869. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35870. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  35871. /**
  35872. A type of button designed to go on a toolbar.
  35873. This simple button can have two Drawable objects specified - one for normal
  35874. use and another one (optionally) for the button's "on" state if it's a
  35875. toggle button.
  35876. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  35877. */
  35878. class JUCE_API ToolbarButton : public ToolbarItemComponent
  35879. {
  35880. public:
  35881. /** Creates a ToolbarButton.
  35882. @param itemId the ID for this toolbar item type. This is passed through to the
  35883. ToolbarItemComponent constructor
  35884. @param labelText the text to display on the button (if the toolbar is using a style
  35885. that shows text labels). This is passed through to the
  35886. ToolbarItemComponent constructor
  35887. @param normalImage a drawable object that the button should use as its icon. The object
  35888. that is passed-in here will be kept by this object and will be
  35889. deleted when no longer needed or when this button is deleted.
  35890. @param toggledOnImage a drawable object that the button can use as its icon if the button
  35891. is in a toggled-on state (see the Button::getToggleState() method). If
  35892. 0 is passed-in here, then the normal image will be used instead, regardless
  35893. of the toggle state. The object that is passed-in here will be kept by
  35894. this object and will be deleted when no longer needed or when this button
  35895. is deleted.
  35896. */
  35897. ToolbarButton (int itemId,
  35898. const String& labelText,
  35899. Drawable* normalImage,
  35900. Drawable* toggledOnImage);
  35901. /** Destructor. */
  35902. ~ToolbarButton();
  35903. /** @internal */
  35904. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  35905. int& minSize, int& maxSize);
  35906. /** @internal */
  35907. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  35908. /** @internal */
  35909. void contentAreaChanged (const Rectangle<int>& newBounds);
  35910. /** @internal */
  35911. void buttonStateChanged();
  35912. /** @internal */
  35913. void resized();
  35914. /** @internal */
  35915. void enablementChanged();
  35916. private:
  35917. ScopedPointer<Drawable> normalImage, toggledOnImage;
  35918. Drawable* currentImage;
  35919. void updateDrawable();
  35920. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  35921. };
  35922. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  35923. /*** End of inlined file: juce_ToolbarButton.h ***/
  35924. #endif
  35925. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  35926. /*** Start of inlined file: juce_CodeDocument.h ***/
  35927. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  35928. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  35929. class CodeDocumentLine;
  35930. /**
  35931. A class for storing and manipulating a source code file.
  35932. When using a CodeEditorComponent, it takes one of these as its source object.
  35933. The CodeDocument stores its content as an array of lines, which makes it
  35934. quick to insert and delete.
  35935. @see CodeEditorComponent
  35936. */
  35937. class JUCE_API CodeDocument
  35938. {
  35939. public:
  35940. /** Creates a new, empty document.
  35941. */
  35942. CodeDocument();
  35943. /** Destructor. */
  35944. ~CodeDocument();
  35945. /** A position in a code document.
  35946. Using this class you can find a position in a code document and quickly get its
  35947. character position, line, and index. By calling setPositionMaintained (true), the
  35948. position is automatically updated when text is inserted or deleted in the document,
  35949. so that it maintains its original place in the text.
  35950. */
  35951. class JUCE_API Position
  35952. {
  35953. public:
  35954. /** Creates an uninitialised postion.
  35955. Don't attempt to call any methods on this until you've given it an owner document
  35956. to refer to!
  35957. */
  35958. Position() throw();
  35959. /** Creates a position based on a line and index in a document.
  35960. Note that this index is NOT the column number, it's the number of characters from the
  35961. start of the line. The "column" number isn't quite the same, because if the line
  35962. contains any tab characters, the relationship of the index to its visual column depends on
  35963. the number of spaces per tab being used!
  35964. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  35965. they will be adjusted to keep them within its limits.
  35966. */
  35967. Position (const CodeDocument* ownerDocument,
  35968. int line, int indexInLine) throw();
  35969. /** Creates a position based on a character index in a document.
  35970. This position is placed at the specified number of characters from the start of the
  35971. document. The line and column are auto-calculated.
  35972. If the position is beyond the range of the document, it'll be adjusted to keep it
  35973. inside.
  35974. */
  35975. Position (const CodeDocument* ownerDocument,
  35976. int charactersFromStartOfDocument) throw();
  35977. /** Creates a copy of another position.
  35978. This will copy the position, but the new object will not be set to maintain its position,
  35979. even if the source object was set to do so.
  35980. */
  35981. Position (const Position& other) throw();
  35982. /** Destructor. */
  35983. ~Position();
  35984. Position& operator= (const Position& other);
  35985. bool operator== (const Position& other) const throw();
  35986. bool operator!= (const Position& other) const throw();
  35987. /** Points this object at a new position within the document.
  35988. If the position is beyond the range of the document, it'll be adjusted to keep it
  35989. inside.
  35990. @see getPosition, setLineAndIndex
  35991. */
  35992. void setPosition (int charactersFromStartOfDocument);
  35993. /** Returns the position as the number of characters from the start of the document.
  35994. @see setPosition, getLineNumber, getIndexInLine
  35995. */
  35996. int getPosition() const throw() { return characterPos; }
  35997. /** Moves the position to a new line and index within the line.
  35998. Note that the index is NOT the column at which the position appears in an editor.
  35999. If the line contains any tab characters, the relationship of the index to its
  36000. visual position depends on the number of spaces per tab being used!
  36001. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  36002. they will be adjusted to keep them within its limits.
  36003. */
  36004. void setLineAndIndex (int newLine, int newIndexInLine);
  36005. /** Returns the line number of this position.
  36006. The first line in the document is numbered zero, not one!
  36007. */
  36008. int getLineNumber() const throw() { return line; }
  36009. /** Returns the number of characters from the start of the line.
  36010. Note that this value is NOT the column at which the position appears in an editor.
  36011. If the line contains any tab characters, the relationship of the index to its
  36012. visual position depends on the number of spaces per tab being used!
  36013. */
  36014. int getIndexInLine() const throw() { return indexInLine; }
  36015. /** Allows the position to be automatically updated when the document changes.
  36016. If this is set to true, the positon will register with its document so that
  36017. when the document has text inserted or deleted, this position will be automatically
  36018. moved to keep it at the same position in the text.
  36019. */
  36020. void setPositionMaintained (bool isMaintained);
  36021. /** Moves the position forwards or backwards by the specified number of characters.
  36022. @see movedBy
  36023. */
  36024. void moveBy (int characterDelta);
  36025. /** Returns a position which is the same as this one, moved by the specified number of
  36026. characters.
  36027. @see moveBy
  36028. */
  36029. const Position movedBy (int characterDelta) const;
  36030. /** Returns a position which is the same as this one, moved up or down by the specified
  36031. number of lines.
  36032. @see movedBy
  36033. */
  36034. const Position movedByLines (int deltaLines) const;
  36035. /** Returns the character in the document at this position.
  36036. @see getLineText
  36037. */
  36038. const juce_wchar getCharacter() const;
  36039. /** Returns the line from the document that this position is within.
  36040. @see getCharacter, getLineNumber
  36041. */
  36042. const String getLineText() const;
  36043. private:
  36044. CodeDocument* owner;
  36045. int characterPos, line, indexInLine;
  36046. bool positionMaintained;
  36047. };
  36048. /** Returns the full text of the document. */
  36049. const String getAllContent() const;
  36050. /** Returns a section of the document's text. */
  36051. const String getTextBetween (const Position& start, const Position& end) const;
  36052. /** Returns a line from the document. */
  36053. const String getLine (int lineIndex) const throw();
  36054. /** Returns the number of characters in the document. */
  36055. int getNumCharacters() const throw();
  36056. /** Returns the number of lines in the document. */
  36057. int getNumLines() const throw() { return lines.size(); }
  36058. /** Returns the number of characters in the longest line of the document. */
  36059. int getMaximumLineLength() throw();
  36060. /** Deletes a section of the text.
  36061. This operation is undoable.
  36062. */
  36063. void deleteSection (const Position& startPosition, const Position& endPosition);
  36064. /** Inserts some text into the document at a given position.
  36065. This operation is undoable.
  36066. */
  36067. void insertText (const Position& position, const String& text);
  36068. /** Clears the document and replaces it with some new text.
  36069. This operation is undoable - if you're trying to completely reset the document, you
  36070. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  36071. */
  36072. void replaceAllContent (const String& newContent);
  36073. /** Replaces the editor's contents with the contents of a stream.
  36074. This will also reset the undo history and save point marker.
  36075. */
  36076. bool loadFromStream (InputStream& stream);
  36077. /** Writes the editor's current contents to a stream. */
  36078. bool writeToStream (OutputStream& stream);
  36079. /** Returns the preferred new-line characters for the document.
  36080. This will be either "\n", "\r\n", or (rarely) "\r".
  36081. @see setNewLineCharacters
  36082. */
  36083. const String getNewLineCharacters() const throw() { return newLineChars; }
  36084. /** Sets the new-line characters that the document should use.
  36085. The string must be either "\n", "\r\n", or (rarely) "\r".
  36086. @see getNewLineCharacters
  36087. */
  36088. void setNewLineCharacters (const String& newLine) throw();
  36089. /** Begins a new undo transaction.
  36090. The document itself will not call this internally, so relies on whatever is using the
  36091. document to periodically call this to break up the undo sequence into sensible chunks.
  36092. @see UndoManager::beginNewTransaction
  36093. */
  36094. void newTransaction();
  36095. /** Undo the last operation.
  36096. @see UndoManager::undo
  36097. */
  36098. void undo();
  36099. /** Redo the last operation.
  36100. @see UndoManager::redo
  36101. */
  36102. void redo();
  36103. /** Clears the undo history.
  36104. @see UndoManager::clearUndoHistory
  36105. */
  36106. void clearUndoHistory();
  36107. /** Returns the document's UndoManager */
  36108. UndoManager& getUndoManager() throw() { return undoManager; }
  36109. /** Makes a note that the document's current state matches the one that is saved.
  36110. After this has been called, hasChangedSinceSavePoint() will return false until
  36111. the document has been altered, and then it'll start returning true. If the document is
  36112. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  36113. will again return false.
  36114. @see hasChangedSinceSavePoint
  36115. */
  36116. void setSavePoint() throw();
  36117. /** Returns true if the state of the document differs from the state it was in when
  36118. setSavePoint() was last called.
  36119. @see setSavePoint
  36120. */
  36121. bool hasChangedSinceSavePoint() const throw();
  36122. /** Searches for a word-break. */
  36123. const Position findWordBreakAfter (const Position& position) const throw();
  36124. /** Searches for a word-break. */
  36125. const Position findWordBreakBefore (const Position& position) const throw();
  36126. /** An object that receives callbacks from the CodeDocument when its text changes.
  36127. @see CodeDocument::addListener, CodeDocument::removeListener
  36128. */
  36129. class JUCE_API Listener
  36130. {
  36131. public:
  36132. Listener() {}
  36133. virtual ~Listener() {}
  36134. /** Called by a CodeDocument when it is altered.
  36135. */
  36136. virtual void codeDocumentChanged (const Position& affectedTextStart,
  36137. const Position& affectedTextEnd) = 0;
  36138. };
  36139. /** Registers a listener object to receive callbacks when the document changes.
  36140. If the listener is already registered, this method has no effect.
  36141. @see removeListener
  36142. */
  36143. void addListener (Listener* listener) throw();
  36144. /** Deregisters a listener.
  36145. @see addListener
  36146. */
  36147. void removeListener (Listener* listener) throw();
  36148. /** Iterates the text in a CodeDocument.
  36149. This class lets you read characters from a CodeDocument. It's designed to be used
  36150. by a SyntaxAnalyser object.
  36151. @see CodeDocument, SyntaxAnalyser
  36152. */
  36153. class Iterator
  36154. {
  36155. public:
  36156. Iterator (CodeDocument* document);
  36157. Iterator (const Iterator& other);
  36158. Iterator& operator= (const Iterator& other) throw();
  36159. ~Iterator() throw();
  36160. /** Reads the next character and returns it.
  36161. @see peekNextChar
  36162. */
  36163. juce_wchar nextChar();
  36164. /** Reads the next character without advancing the current position. */
  36165. juce_wchar peekNextChar() const;
  36166. /** Advances the position by one character. */
  36167. void skip();
  36168. /** Returns the position of the next character as its position within the
  36169. whole document.
  36170. */
  36171. int getPosition() const throw() { return position; }
  36172. /** Skips over any whitespace characters until the next character is non-whitespace. */
  36173. void skipWhitespace();
  36174. /** Skips forward until the next character will be the first character on the next line */
  36175. void skipToEndOfLine();
  36176. /** Returns the line number of the next character. */
  36177. int getLine() const throw() { return line; }
  36178. /** Returns true if the iterator has reached the end of the document. */
  36179. bool isEOF() const throw();
  36180. private:
  36181. CodeDocument* document;
  36182. CodeDocumentLine* currentLine;
  36183. int line, position;
  36184. };
  36185. private:
  36186. friend class CodeDocumentInsertAction;
  36187. friend class CodeDocumentDeleteAction;
  36188. friend class Iterator;
  36189. friend class Position;
  36190. OwnedArray <CodeDocumentLine> lines;
  36191. Array <Position*> positionsToMaintain;
  36192. UndoManager undoManager;
  36193. int currentActionIndex, indexOfSavedState;
  36194. int maximumLineLength;
  36195. ListenerList <Listener> listeners;
  36196. String newLineChars;
  36197. void sendListenerChangeMessage (int startLine, int endLine);
  36198. void insert (const String& text, int insertPos, bool undoable);
  36199. void remove (int startPos, int endPos, bool undoable);
  36200. void checkLastLineStatus();
  36201. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  36202. };
  36203. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  36204. /*** End of inlined file: juce_CodeDocument.h ***/
  36205. #endif
  36206. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  36207. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  36208. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  36209. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  36210. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  36211. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  36212. #define __JUCE_CODETOKENISER_JUCEHEADER__
  36213. /**
  36214. A base class for tokenising code so that the syntax can be displayed in a
  36215. code editor.
  36216. @see CodeDocument, CodeEditorComponent
  36217. */
  36218. class JUCE_API CodeTokeniser
  36219. {
  36220. public:
  36221. CodeTokeniser() {}
  36222. virtual ~CodeTokeniser() {}
  36223. /** Reads the next token from the source and returns its token type.
  36224. This must leave the source pointing to the first character in the
  36225. next token.
  36226. */
  36227. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  36228. /** Returns a list of the names of the token types this analyser uses.
  36229. The index in this list must match the token type numbers that are
  36230. returned by readNextToken().
  36231. */
  36232. virtual const StringArray getTokenTypes() = 0;
  36233. /** Returns a suggested syntax highlighting colour for a specified
  36234. token type.
  36235. */
  36236. virtual const Colour getDefaultColour (int tokenType) = 0;
  36237. private:
  36238. JUCE_LEAK_DETECTOR (CodeTokeniser);
  36239. };
  36240. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  36241. /*** End of inlined file: juce_CodeTokeniser.h ***/
  36242. /**
  36243. A text editor component designed specifically for source code.
  36244. This is designed to handle syntax highlighting and fast editing of very large
  36245. files.
  36246. */
  36247. class JUCE_API CodeEditorComponent : public Component,
  36248. public TextInputTarget,
  36249. public Timer,
  36250. public ScrollBar::Listener,
  36251. public CodeDocument::Listener,
  36252. public AsyncUpdater
  36253. {
  36254. public:
  36255. /** Creates an editor for a document.
  36256. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  36257. The object that you pass in is not owned or deleted by the editor - you must
  36258. make sure that it doesn't get deleted while this component is still using it.
  36259. @see CodeDocument
  36260. */
  36261. CodeEditorComponent (CodeDocument& document,
  36262. CodeTokeniser* codeTokeniser);
  36263. /** Destructor. */
  36264. ~CodeEditorComponent();
  36265. /** Returns the code document that this component is editing. */
  36266. CodeDocument& getDocument() const throw() { return document; }
  36267. /** Loads the given content into the document.
  36268. This will completely reset the CodeDocument object, clear its undo history,
  36269. and fill it with this text.
  36270. */
  36271. void loadContent (const String& newContent);
  36272. /** Returns the standard character width. */
  36273. float getCharWidth() const throw() { return charWidth; }
  36274. /** Returns the height of a line of text, in pixels. */
  36275. int getLineHeight() const throw() { return lineHeight; }
  36276. /** Returns the number of whole lines visible on the screen,
  36277. This doesn't include a cut-off line that might be visible at the bottom if the
  36278. component's height isn't an exact multiple of the line-height.
  36279. */
  36280. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  36281. /** Returns the number of whole columns visible on the screen.
  36282. This doesn't include any cut-off columns at the right-hand edge.
  36283. */
  36284. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  36285. /** Returns the current caret position. */
  36286. const CodeDocument::Position getCaretPos() const { return caretPos; }
  36287. /** Moves the caret.
  36288. If selecting is true, the section of the document between the current
  36289. caret position and the new one will become selected. If false, any currently
  36290. selected region will be deselected.
  36291. */
  36292. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  36293. /** Returns the on-screen position of a character in the document.
  36294. The rectangle returned is relative to this component's top-left origin.
  36295. */
  36296. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  36297. /** Finds the character at a given on-screen position.
  36298. The co-ordinates are relative to this component's top-left origin.
  36299. */
  36300. const CodeDocument::Position getPositionAt (int x, int y);
  36301. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  36302. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  36303. void cursorDown (bool selecting);
  36304. void cursorUp (bool selecting);
  36305. void pageDown (bool selecting);
  36306. void pageUp (bool selecting);
  36307. void scrollDown();
  36308. void scrollUp();
  36309. void scrollToLine (int newFirstLineOnScreen);
  36310. void scrollBy (int deltaLines);
  36311. void scrollToColumn (int newFirstColumnOnScreen);
  36312. void scrollToKeepCaretOnScreen();
  36313. void goToStartOfDocument (bool selecting);
  36314. void goToStartOfLine (bool selecting);
  36315. void goToEndOfDocument (bool selecting);
  36316. void goToEndOfLine (bool selecting);
  36317. void deselectAll();
  36318. void selectAll();
  36319. void insertTextAtCaret (const String& textToInsert);
  36320. void insertTabAtCaret();
  36321. void cut();
  36322. void copy();
  36323. void copyThenCut();
  36324. void paste();
  36325. void backspace (bool moveInWholeWordSteps);
  36326. void deleteForward (bool moveInWholeWordSteps);
  36327. void undo();
  36328. void redo();
  36329. const Range<int> getHighlightedRegion() const;
  36330. void setHighlightedRegion (const Range<int>& newRange);
  36331. const String getTextInRange (const Range<int>& range) const;
  36332. /** Changes the current tab settings.
  36333. This lets you change the tab size and whether pressing the tab key inserts a
  36334. tab character, or its equivalent number of spaces.
  36335. */
  36336. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  36337. /** Returns the current number of spaces per tab.
  36338. @see setTabSize
  36339. */
  36340. int getTabSize() const throw() { return spacesPerTab; }
  36341. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  36342. @see setTabSize
  36343. */
  36344. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  36345. /** Changes the font.
  36346. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  36347. */
  36348. void setFont (const Font& newFont);
  36349. /** Returns the font that the editor is using. */
  36350. const Font& getFont() const throw() { return font; }
  36351. /** Resets the syntax highlighting colours to the default ones provided by the
  36352. code tokeniser.
  36353. @see CodeTokeniser::getDefaultColour
  36354. */
  36355. void resetToDefaultColours();
  36356. /** Changes one of the syntax highlighting colours.
  36357. The token type values are dependent on the tokeniser being used - use
  36358. CodeTokeniser::getTokenTypes() to get a list of the token types.
  36359. @see getColourForTokenType
  36360. */
  36361. void setColourForTokenType (int tokenType, const Colour& colour);
  36362. /** Returns one of the syntax highlighting colours.
  36363. The token type values are dependent on the tokeniser being used - use
  36364. CodeTokeniser::getTokenTypes() to get a list of the token types.
  36365. @see setColourForTokenType
  36366. */
  36367. const Colour getColourForTokenType (int tokenType) const;
  36368. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  36369. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36370. methods.
  36371. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36372. */
  36373. enum ColourIds
  36374. {
  36375. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  36376. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  36377. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  36378. selected text. */
  36379. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  36380. enabled. */
  36381. };
  36382. /** Changes the size of the scrollbars. */
  36383. void setScrollbarThickness (int thickness);
  36384. /** Returns the thickness of the scrollbars. */
  36385. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  36386. /** @internal */
  36387. void resized();
  36388. /** @internal */
  36389. void paint (Graphics& g);
  36390. /** @internal */
  36391. bool keyPressed (const KeyPress& key);
  36392. /** @internal */
  36393. void mouseDown (const MouseEvent& e);
  36394. /** @internal */
  36395. void mouseDrag (const MouseEvent& e);
  36396. /** @internal */
  36397. void mouseUp (const MouseEvent& e);
  36398. /** @internal */
  36399. void mouseDoubleClick (const MouseEvent& e);
  36400. /** @internal */
  36401. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  36402. /** @internal */
  36403. void focusGained (FocusChangeType cause);
  36404. /** @internal */
  36405. void focusLost (FocusChangeType cause);
  36406. /** @internal */
  36407. void timerCallback();
  36408. /** @internal */
  36409. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  36410. /** @internal */
  36411. void handleAsyncUpdate();
  36412. /** @internal */
  36413. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36414. const CodeDocument::Position& affectedTextEnd);
  36415. /** @internal */
  36416. bool isTextInputActive() const;
  36417. private:
  36418. CodeDocument& document;
  36419. Font font;
  36420. int firstLineOnScreen, gutter, spacesPerTab;
  36421. float charWidth;
  36422. int lineHeight, linesOnScreen, columnsOnScreen;
  36423. int scrollbarThickness, columnToTryToMaintain;
  36424. bool useSpacesForTabs;
  36425. double xOffset;
  36426. CodeDocument::Position caretPos;
  36427. CodeDocument::Position selectionStart, selectionEnd;
  36428. class CaretComponent;
  36429. friend class ScopedPointer <CaretComponent>;
  36430. ScopedPointer<CaretComponent> caret;
  36431. ScrollBar verticalScrollBar, horizontalScrollBar;
  36432. enum DragType
  36433. {
  36434. notDragging,
  36435. draggingSelectionStart,
  36436. draggingSelectionEnd
  36437. };
  36438. DragType dragType;
  36439. CodeTokeniser* codeTokeniser;
  36440. Array <Colour> coloursForTokenCategories;
  36441. class CodeEditorLine;
  36442. OwnedArray <CodeEditorLine> lines;
  36443. void rebuildLineTokens();
  36444. OwnedArray <CodeDocument::Iterator> cachedIterators;
  36445. void clearCachedIterators (int firstLineToBeInvalid);
  36446. void updateCachedIterators (int maxLineNum);
  36447. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  36448. void moveLineDelta (int delta, bool selecting);
  36449. void updateScrollBars();
  36450. void scrollToLineInternal (int line);
  36451. void scrollToColumnInternal (double column);
  36452. void newTransaction();
  36453. int indexToColumn (int line, int index) const throw();
  36454. int columnToIndex (int line, int column) const throw();
  36455. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  36456. };
  36457. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  36458. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  36459. #endif
  36460. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  36461. #endif
  36462. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  36463. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  36464. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  36465. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  36466. /**
  36467. A simple lexical analyser for syntax colouring of C++ code.
  36468. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  36469. */
  36470. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  36471. {
  36472. public:
  36473. CPlusPlusCodeTokeniser();
  36474. ~CPlusPlusCodeTokeniser();
  36475. enum TokenType
  36476. {
  36477. tokenType_error = 0,
  36478. tokenType_comment,
  36479. tokenType_builtInKeyword,
  36480. tokenType_identifier,
  36481. tokenType_integerLiteral,
  36482. tokenType_floatLiteral,
  36483. tokenType_stringLiteral,
  36484. tokenType_operator,
  36485. tokenType_bracket,
  36486. tokenType_punctuation,
  36487. tokenType_preprocessor
  36488. };
  36489. int readNextToken (CodeDocument::Iterator& source);
  36490. const StringArray getTokenTypes();
  36491. const Colour getDefaultColour (int tokenType);
  36492. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  36493. static bool isReservedKeyword (const String& token) throw();
  36494. private:
  36495. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  36496. };
  36497. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  36498. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  36499. #endif
  36500. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  36501. #endif
  36502. #ifndef __JUCE_LABEL_JUCEHEADER__
  36503. #endif
  36504. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  36505. #endif
  36506. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  36507. /*** Start of inlined file: juce_ProgressBar.h ***/
  36508. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  36509. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  36510. /**
  36511. A progress bar component.
  36512. To use this, just create one and make it visible. It'll run its own timer
  36513. to keep an eye on a variable that you give it, and will automatically
  36514. redraw itself when the variable changes.
  36515. For an easy way of running a background task with a dialog box showing its
  36516. progress, see the ThreadWithProgressWindow class.
  36517. @see ThreadWithProgressWindow
  36518. */
  36519. class JUCE_API ProgressBar : public Component,
  36520. public SettableTooltipClient,
  36521. private Timer
  36522. {
  36523. public:
  36524. /** Creates a ProgressBar.
  36525. @param progress pass in a reference to a double that you're going to
  36526. update with your task's progress. The ProgressBar will
  36527. monitor the value of this variable and will redraw itself
  36528. when the value changes. The range is from 0 to 1.0. Obviously
  36529. you'd better be careful not to delete this variable while the
  36530. ProgressBar still exists!
  36531. */
  36532. explicit ProgressBar (double& progress);
  36533. /** Destructor. */
  36534. ~ProgressBar();
  36535. /** Turns the percentage display on or off.
  36536. By default this is on, and the progress bar will display a text string showing
  36537. its current percentage.
  36538. */
  36539. void setPercentageDisplay (bool shouldDisplayPercentage);
  36540. /** Gives the progress bar a string to display inside it.
  36541. If you call this, it will turn off the percentage display.
  36542. @see setPercentageDisplay
  36543. */
  36544. void setTextToDisplay (const String& text);
  36545. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  36546. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36547. methods.
  36548. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36549. */
  36550. enum ColourIds
  36551. {
  36552. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  36553. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  36554. classes will probably use variations on this colour. */
  36555. };
  36556. protected:
  36557. /** @internal */
  36558. void paint (Graphics& g);
  36559. /** @internal */
  36560. void lookAndFeelChanged();
  36561. /** @internal */
  36562. void visibilityChanged();
  36563. /** @internal */
  36564. void colourChanged();
  36565. private:
  36566. double& progress;
  36567. double currentValue;
  36568. bool displayPercentage;
  36569. String displayedMessage, currentMessage;
  36570. uint32 lastCallbackTime;
  36571. void timerCallback();
  36572. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  36573. };
  36574. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  36575. /*** End of inlined file: juce_ProgressBar.h ***/
  36576. #endif
  36577. #ifndef __JUCE_SLIDER_JUCEHEADER__
  36578. /*** Start of inlined file: juce_Slider.h ***/
  36579. #ifndef __JUCE_SLIDER_JUCEHEADER__
  36580. #define __JUCE_SLIDER_JUCEHEADER__
  36581. #if JUCE_VC6
  36582. #define Listener LabelListener
  36583. #endif
  36584. /**
  36585. A slider control for changing a value.
  36586. The slider can be horizontal, vertical, or rotary, and can optionally have
  36587. a text-box inside it to show an editable display of the current value.
  36588. To use it, create a Slider object and use the setSliderStyle() method
  36589. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  36590. To define the values that it can be set to, see the setRange() and setValue() methods.
  36591. There are also lots of custom tweaks you can do by subclassing and overriding
  36592. some of the virtual methods, such as changing the scaling, changing the format of
  36593. the text display, custom ways of limiting the values, etc.
  36594. You can register Slider::Listener objects with a slider, and they'll be called when
  36595. the value changes.
  36596. @see Slider::Listener
  36597. */
  36598. class JUCE_API Slider : public Component,
  36599. public SettableTooltipClient,
  36600. public AsyncUpdater,
  36601. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  36602. public LabelListener,
  36603. public ValueListener
  36604. {
  36605. public:
  36606. /** Creates a slider.
  36607. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  36608. setRange(), etc.
  36609. */
  36610. explicit Slider (const String& componentName = String::empty);
  36611. /** Destructor. */
  36612. ~Slider();
  36613. /** The types of slider available.
  36614. @see setSliderStyle, setRotaryParameters
  36615. */
  36616. enum SliderStyle
  36617. {
  36618. LinearHorizontal, /**< A traditional horizontal slider. */
  36619. LinearVertical, /**< A traditional vertical slider. */
  36620. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  36621. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  36622. @see setRotaryParameters */
  36623. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  36624. @see setRotaryParameters */
  36625. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  36626. @see setRotaryParameters */
  36627. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  36628. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  36629. @see setMinValue, setMaxValue */
  36630. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  36631. @see setMinValue, setMaxValue */
  36632. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  36633. value, with the current value being somewhere between them.
  36634. @see setMinValue, setMaxValue */
  36635. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  36636. value, with the current value being somewhere between them.
  36637. @see setMinValue, setMaxValue */
  36638. };
  36639. /** Changes the type of slider interface being used.
  36640. @param newStyle the type of interface
  36641. @see setRotaryParameters, setVelocityBasedMode,
  36642. */
  36643. void setSliderStyle (SliderStyle newStyle);
  36644. /** Returns the slider's current style.
  36645. @see setSliderStyle
  36646. */
  36647. SliderStyle getSliderStyle() const throw() { return style; }
  36648. /** Changes the properties of a rotary slider.
  36649. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  36650. the slider's minimum value is represented
  36651. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  36652. the slider's maximum value is represented. This must be
  36653. greater than startAngleRadians
  36654. @param stopAtEnd if true, then when the slider is dragged around past the
  36655. minimum or maximum, it'll stop there; if false, it'll wrap
  36656. back to the opposite value
  36657. */
  36658. void setRotaryParameters (float startAngleRadians,
  36659. float endAngleRadians,
  36660. bool stopAtEnd);
  36661. /** Sets the distance the mouse has to move to drag the slider across
  36662. the full extent of its range.
  36663. This only applies when in modes like RotaryHorizontalDrag, where it's using
  36664. relative mouse movements to adjust the slider.
  36665. */
  36666. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  36667. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  36668. int getMouseDragSensitivity() const throw() { return pixelsForFullDragExtent; }
  36669. /** Changes the way the the mouse is used when dragging the slider.
  36670. If true, this will turn on velocity-sensitive dragging, so that
  36671. the faster the mouse moves, the bigger the movement to the slider. This
  36672. helps when making accurate adjustments if the slider's range is quite large.
  36673. If false, the slider will just try to snap to wherever the mouse is.
  36674. */
  36675. void setVelocityBasedMode (bool isVelocityBased);
  36676. /** Returns true if velocity-based mode is active.
  36677. @see setVelocityBasedMode
  36678. */
  36679. bool getVelocityBasedMode() const throw() { return isVelocityBased; }
  36680. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  36681. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  36682. or if you're holding down ctrl.
  36683. @param sensitivity higher values than 1.0 increase the range of acceleration used
  36684. @param threshold the minimum number of pixels that the mouse needs to move for it
  36685. to be treated as a movement
  36686. @param offset values greater than 0.0 increase the minimum speed that will be used when
  36687. the threshold is reached
  36688. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  36689. key to toggle velocity-sensitive mode
  36690. */
  36691. void setVelocityModeParameters (double sensitivity = 1.0,
  36692. int threshold = 1,
  36693. double offset = 0.0,
  36694. bool userCanPressKeyToSwapMode = true);
  36695. /** Returns the velocity sensitivity setting.
  36696. @see setVelocityModeParameters
  36697. */
  36698. double getVelocitySensitivity() const throw() { return velocityModeSensitivity; }
  36699. /** Returns the velocity threshold setting.
  36700. @see setVelocityModeParameters
  36701. */
  36702. int getVelocityThreshold() const throw() { return velocityModeThreshold; }
  36703. /** Returns the velocity offset setting.
  36704. @see setVelocityModeParameters
  36705. */
  36706. double getVelocityOffset() const throw() { return velocityModeOffset; }
  36707. /** Returns the velocity user key setting.
  36708. @see setVelocityModeParameters
  36709. */
  36710. bool getVelocityModeIsSwappable() const throw() { return userKeyOverridesVelocity; }
  36711. /** Sets up a skew factor to alter the way values are distributed.
  36712. You may want to use a range of values on the slider where more accuracy
  36713. is required towards one end of the range, so this will logarithmically
  36714. spread the values across the length of the slider.
  36715. If the factor is < 1.0, the lower end of the range will fill more of the
  36716. slider's length; if the factor is > 1.0, the upper end of the range
  36717. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  36718. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  36719. method instead.
  36720. @see getSkewFactor, setSkewFactorFromMidPoint
  36721. */
  36722. void setSkewFactor (double factor);
  36723. /** Sets up a skew factor to alter the way values are distributed.
  36724. This allows you to specify the slider value that should appear in the
  36725. centre of the slider's visible range.
  36726. @see setSkewFactor, getSkewFactor
  36727. */
  36728. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  36729. /** Returns the current skew factor.
  36730. See setSkewFactor for more info.
  36731. @see setSkewFactor, setSkewFactorFromMidPoint
  36732. */
  36733. double getSkewFactor() const throw() { return skewFactor; }
  36734. /** Used by setIncDecButtonsMode().
  36735. */
  36736. enum IncDecButtonMode
  36737. {
  36738. incDecButtonsNotDraggable,
  36739. incDecButtonsDraggable_AutoDirection,
  36740. incDecButtonsDraggable_Horizontal,
  36741. incDecButtonsDraggable_Vertical
  36742. };
  36743. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  36744. can be dragged on the buttons to drag the values.
  36745. By default this is turned off. When enabled, clicking on the buttons still works
  36746. them as normal, but by holding down the mouse on a button and dragging it a little
  36747. distance, it flips into a mode where the value can be dragged. The drag direction can
  36748. either be set explicitly to be vertical or horizontal, or can be set to
  36749. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  36750. are side-by-side or above each other.
  36751. */
  36752. void setIncDecButtonsMode (IncDecButtonMode mode);
  36753. /** The position of the slider's text-entry box.
  36754. @see setTextBoxStyle
  36755. */
  36756. enum TextEntryBoxPosition
  36757. {
  36758. NoTextBox, /**< Doesn't display a text box. */
  36759. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  36760. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  36761. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  36762. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  36763. };
  36764. /** Changes the location and properties of the text-entry box.
  36765. @param newPosition where it should go (or NoTextBox to not have one at all)
  36766. @param isReadOnly if true, it's a read-only display
  36767. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  36768. room for the slider as well!
  36769. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  36770. room for the slider as well!
  36771. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  36772. */
  36773. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  36774. bool isReadOnly,
  36775. int textEntryBoxWidth,
  36776. int textEntryBoxHeight);
  36777. /** Returns the status of the text-box.
  36778. @see setTextBoxStyle
  36779. */
  36780. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  36781. /** Returns the width used for the text-box.
  36782. @see setTextBoxStyle
  36783. */
  36784. int getTextBoxWidth() const throw() { return textBoxWidth; }
  36785. /** Returns the height used for the text-box.
  36786. @see setTextBoxStyle
  36787. */
  36788. int getTextBoxHeight() const throw() { return textBoxHeight; }
  36789. /** Makes the text-box editable.
  36790. By default this is true, and the user can enter values into the textbox,
  36791. but it can be turned off if that's not suitable.
  36792. @see setTextBoxStyle, getValueFromText, getTextFromValue
  36793. */
  36794. void setTextBoxIsEditable (bool shouldBeEditable);
  36795. /** Returns true if the text-box is read-only.
  36796. @see setTextBoxStyle
  36797. */
  36798. bool isTextBoxEditable() const { return editableText; }
  36799. /** If the text-box is editable, this will give it the focus so that the user can
  36800. type directly into it.
  36801. This is basically the effect as the user clicking on it.
  36802. */
  36803. void showTextBox();
  36804. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  36805. focus away from it.
  36806. @param discardCurrentEditorContents if true, the slider's value will be left
  36807. unchanged; if false, the current contents of the
  36808. text editor will be used to set the slider position
  36809. before it is hidden.
  36810. */
  36811. void hideTextBox (bool discardCurrentEditorContents);
  36812. /** Changes the slider's current value.
  36813. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  36814. that are registered, and will synchronously call the valueChanged() method in case subclasses
  36815. want to handle it.
  36816. @param newValue the new value to set - this will be restricted by the
  36817. minimum and maximum range, and will be snapped to the
  36818. nearest interval if one has been set
  36819. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  36820. any Slider::Listeners or the valueChanged() method
  36821. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  36822. synchronously; if false, it will be asynchronous
  36823. */
  36824. void setValue (double newValue,
  36825. bool sendUpdateMessage = true,
  36826. bool sendMessageSynchronously = false);
  36827. /** Returns the slider's current value. */
  36828. double getValue() const;
  36829. /** Returns the Value object that represents the slider's current position.
  36830. You can use this Value object to connect the slider's position to external values or setters,
  36831. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  36832. your own Value object.
  36833. @see Value, getMaxValue, getMinValueObject
  36834. */
  36835. Value& getValueObject() { return currentValue; }
  36836. /** Sets the limits that the slider's value can take.
  36837. @param newMinimum the lowest value allowed
  36838. @param newMaximum the highest value allowed
  36839. @param newInterval the steps in which the value is allowed to increase - if this
  36840. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  36841. */
  36842. void setRange (double newMinimum,
  36843. double newMaximum,
  36844. double newInterval = 0);
  36845. /** Returns the current maximum value.
  36846. @see setRange
  36847. */
  36848. double getMaximum() const { return maximum; }
  36849. /** Returns the current minimum value.
  36850. @see setRange
  36851. */
  36852. double getMinimum() const { return minimum; }
  36853. /** Returns the current step-size for values.
  36854. @see setRange
  36855. */
  36856. double getInterval() const { return interval; }
  36857. /** For a slider with two or three thumbs, this returns the lower of its values.
  36858. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  36859. A slider with three values also uses the normal getValue() and setValue() methods to
  36860. control the middle value.
  36861. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  36862. */
  36863. double getMinValue() const;
  36864. /** For a slider with two or three thumbs, this returns the lower of its values.
  36865. You can use this Value object to connect the slider's position to external values or setters,
  36866. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  36867. your own Value object.
  36868. @see Value, getMinValue, getMaxValueObject
  36869. */
  36870. Value& getMinValueObject() throw() { return valueMin; }
  36871. /** For a slider with two or three thumbs, this sets the lower of its values.
  36872. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  36873. that are registered, and will synchronously call the valueChanged() method in case subclasses
  36874. want to handle it.
  36875. @param newValue the new value to set - this will be restricted by the
  36876. minimum and maximum range, and will be snapped to the nearest
  36877. interval if one has been set.
  36878. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  36879. any Slider::Listeners or the valueChanged() method
  36880. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  36881. synchronously; if false, it will be asynchronous
  36882. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  36883. max value (in a two-value slider) or the mid value (in a three-value
  36884. slider). If false, then if this value goes beyond those values,
  36885. it will push them along with it.
  36886. @see getMinValue, setMaxValue, setValue
  36887. */
  36888. void setMinValue (double newValue,
  36889. bool sendUpdateMessage = true,
  36890. bool sendMessageSynchronously = false,
  36891. bool allowNudgingOfOtherValues = false);
  36892. /** For a slider with two or three thumbs, this returns the higher of its values.
  36893. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  36894. A slider with three values also uses the normal getValue() and setValue() methods to
  36895. control the middle value.
  36896. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  36897. */
  36898. double getMaxValue() const;
  36899. /** For a slider with two or three thumbs, this returns the higher of its values.
  36900. You can use this Value object to connect the slider's position to external values or setters,
  36901. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  36902. your own Value object.
  36903. @see Value, getMaxValue, getMinValueObject
  36904. */
  36905. Value& getMaxValueObject() throw() { return valueMax; }
  36906. /** For a slider with two or three thumbs, this sets the lower of its values.
  36907. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  36908. that are registered, and will synchronously call the valueChanged() method in case subclasses
  36909. want to handle it.
  36910. @param newValue the new value to set - this will be restricted by the
  36911. minimum and maximum range, and will be snapped to the nearest
  36912. interval if one has been set.
  36913. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  36914. any Slider::Listeners or the valueChanged() method
  36915. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  36916. synchronously; if false, it will be asynchronous
  36917. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  36918. min value (in a two-value slider) or the mid value (in a three-value
  36919. slider). If false, then if this value goes beyond those values,
  36920. it will push them along with it.
  36921. @see getMaxValue, setMinValue, setValue
  36922. */
  36923. void setMaxValue (double newValue,
  36924. bool sendUpdateMessage = true,
  36925. bool sendMessageSynchronously = false,
  36926. bool allowNudgingOfOtherValues = false);
  36927. /** A class for receiving callbacks from a Slider.
  36928. To be told when a slider's value changes, you can register a Slider::Listener
  36929. object using Slider::addListener().
  36930. @see Slider::addListener, Slider::removeListener
  36931. */
  36932. class JUCE_API Listener
  36933. {
  36934. public:
  36935. /** Destructor. */
  36936. virtual ~Listener() {}
  36937. /** Called when the slider's value is changed.
  36938. This may be caused by dragging it, or by typing in its text entry box,
  36939. or by a call to Slider::setValue().
  36940. You can find out the new value using Slider::getValue().
  36941. @see Slider::valueChanged
  36942. */
  36943. virtual void sliderValueChanged (Slider* slider) = 0;
  36944. /** Called when the slider is about to be dragged.
  36945. This is called when a drag begins, then it's followed by multiple calls
  36946. to sliderValueChanged(), and then sliderDragEnded() is called after the
  36947. user lets go.
  36948. @see sliderDragEnded, Slider::startedDragging
  36949. */
  36950. virtual void sliderDragStarted (Slider* slider);
  36951. /** Called after a drag operation has finished.
  36952. @see sliderDragStarted, Slider::stoppedDragging
  36953. */
  36954. virtual void sliderDragEnded (Slider* slider);
  36955. };
  36956. /** Adds a listener to be called when this slider's value changes. */
  36957. void addListener (Listener* listener);
  36958. /** Removes a previously-registered listener. */
  36959. void removeListener (Listener* listener);
  36960. /** This lets you choose whether double-clicking moves the slider to a given position.
  36961. By default this is turned off, but it's handy if you want a double-click to act
  36962. as a quick way of resetting a slider. Just pass in the value you want it to
  36963. go to when double-clicked.
  36964. @see getDoubleClickReturnValue
  36965. */
  36966. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  36967. double valueToSetOnDoubleClick);
  36968. /** Returns the values last set by setDoubleClickReturnValue() method.
  36969. Sets isEnabled to true if double-click is enabled, and returns the value
  36970. that was set.
  36971. @see setDoubleClickReturnValue
  36972. */
  36973. double getDoubleClickReturnValue (bool& isEnabled) const;
  36974. /** Tells the slider whether to keep sending change messages while the user
  36975. is dragging the slider.
  36976. If set to true, a change message will only be sent when the user has
  36977. dragged the slider and let go. If set to false (the default), then messages
  36978. will be continuously sent as they drag it while the mouse button is still
  36979. held down.
  36980. */
  36981. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  36982. /** This lets you change whether the slider thumb jumps to the mouse position
  36983. when you click.
  36984. By default, this is true. If it's false, then the slider moves with relative
  36985. motion when you drag it.
  36986. This only applies to linear bars, and won't affect two- or three- value
  36987. sliders.
  36988. */
  36989. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  36990. /** If enabled, this gives the slider a pop-up bubble which appears while the
  36991. slider is being dragged.
  36992. This can be handy if your slider doesn't have a text-box, so that users can
  36993. see the value just when they're changing it.
  36994. If you pass a component as the parentComponentToUse parameter, the pop-up
  36995. bubble will be added as a child of that component when it's needed. If you
  36996. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  36997. transparent window, so if you're using an OS that can't do transparent windows
  36998. you'll have to add it to a parent component instead).
  36999. */
  37000. void setPopupDisplayEnabled (bool isEnabled,
  37001. Component* parentComponentToUse);
  37002. /** If this is set to true, then right-clicking on the slider will pop-up
  37003. a menu to let the user change the way it works.
  37004. By default this is turned off, but when turned on, the menu will include
  37005. things like velocity sensitivity, and for rotary sliders, whether they
  37006. use a linear or rotary mouse-drag to move them.
  37007. */
  37008. void setPopupMenuEnabled (bool menuEnabled);
  37009. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  37010. By default it's enabled.
  37011. */
  37012. void setScrollWheelEnabled (bool enabled);
  37013. /** Returns a number to indicate which thumb is currently being dragged by the
  37014. mouse.
  37015. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  37016. the maximum-value thumb, or -1 if none is currently down.
  37017. */
  37018. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  37019. /** Callback to indicate that the user is about to start dragging the slider.
  37020. @see Slider::Listener::sliderDragStarted
  37021. */
  37022. virtual void startedDragging();
  37023. /** Callback to indicate that the user has just stopped dragging the slider.
  37024. @see Slider::Listener::sliderDragEnded
  37025. */
  37026. virtual void stoppedDragging();
  37027. /** Callback to indicate that the user has just moved the slider.
  37028. @see Slider::Listener::sliderValueChanged
  37029. */
  37030. virtual void valueChanged();
  37031. /** Subclasses can override this to convert a text string to a value.
  37032. When the user enters something into the text-entry box, this method is
  37033. called to convert it to a value.
  37034. The default routine just tries to convert it to a double.
  37035. @see getTextFromValue
  37036. */
  37037. virtual double getValueFromText (const String& text);
  37038. /** Turns the slider's current value into a text string.
  37039. Subclasses can override this to customise the formatting of the text-entry box.
  37040. The default implementation just turns the value into a string, using
  37041. a number of decimal places based on the range interval. If a suffix string
  37042. has been set using setTextValueSuffix(), this will be appended to the text.
  37043. @see getValueFromText
  37044. */
  37045. virtual const String getTextFromValue (double value);
  37046. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  37047. a string.
  37048. This is used by the default implementation of getTextFromValue(), and is just
  37049. appended to the numeric value. For more advanced formatting, you can override
  37050. getTextFromValue() and do something else.
  37051. */
  37052. void setTextValueSuffix (const String& suffix);
  37053. /** Returns the suffix that was set by setTextValueSuffix(). */
  37054. const String getTextValueSuffix() const;
  37055. /** Allows a user-defined mapping of distance along the slider to its value.
  37056. The default implementation for this performs the skewing operation that
  37057. can be set up in the setSkewFactor() method. Override it if you need
  37058. some kind of custom mapping instead, but make sure you also implement the
  37059. inverse function in valueToProportionOfLength().
  37060. @param proportion a value 0 to 1.0, indicating a distance along the slider
  37061. @returns the slider value that is represented by this position
  37062. @see valueToProportionOfLength
  37063. */
  37064. virtual double proportionOfLengthToValue (double proportion);
  37065. /** Allows a user-defined mapping of value to the position of the slider along its length.
  37066. The default implementation for this performs the skewing operation that
  37067. can be set up in the setSkewFactor() method. Override it if you need
  37068. some kind of custom mapping instead, but make sure you also implement the
  37069. inverse function in proportionOfLengthToValue().
  37070. @param value a valid slider value, between the range of values specified in
  37071. setRange()
  37072. @returns a value 0 to 1.0 indicating the distance along the slider that
  37073. represents this value
  37074. @see proportionOfLengthToValue
  37075. */
  37076. virtual double valueToProportionOfLength (double value);
  37077. /** Returns the X or Y coordinate of a value along the slider's length.
  37078. If the slider is horizontal, this will be the X coordinate of the given
  37079. value, relative to the left of the slider. If it's vertical, then this will
  37080. be the Y coordinate, relative to the top of the slider.
  37081. If the slider is rotary, this will throw an assertion and return 0. If the
  37082. value is out-of-range, it will be constrained to the length of the slider.
  37083. */
  37084. float getPositionOfValue (double value);
  37085. /** This can be overridden to allow the slider to snap to user-definable values.
  37086. If overridden, it will be called when the user tries to move the slider to
  37087. a given position, and allows a subclass to sanity-check this value, possibly
  37088. returning a different value to use instead.
  37089. @param attemptedValue the value the user is trying to enter
  37090. @param userIsDragging true if the user is dragging with the mouse; false if
  37091. they are entering the value using the text box
  37092. @returns the value to use instead
  37093. */
  37094. virtual double snapValue (double attemptedValue, bool userIsDragging);
  37095. /** This can be called to force the text box to update its contents.
  37096. (Not normally needed, as this is done automatically).
  37097. */
  37098. void updateText();
  37099. /** True if the slider moves horizontally. */
  37100. bool isHorizontal() const;
  37101. /** True if the slider moves vertically. */
  37102. bool isVertical() const;
  37103. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  37104. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37105. methods.
  37106. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37107. */
  37108. enum ColourIds
  37109. {
  37110. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  37111. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  37112. and feel class how this is used. */
  37113. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  37114. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  37115. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  37116. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  37117. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  37118. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  37119. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  37120. };
  37121. protected:
  37122. /** @internal */
  37123. void labelTextChanged (Label*);
  37124. /** @internal */
  37125. void paint (Graphics& g);
  37126. /** @internal */
  37127. void resized();
  37128. /** @internal */
  37129. void mouseDown (const MouseEvent& e);
  37130. /** @internal */
  37131. void mouseUp (const MouseEvent& e);
  37132. /** @internal */
  37133. void mouseDrag (const MouseEvent& e);
  37134. /** @internal */
  37135. void mouseDoubleClick (const MouseEvent& e);
  37136. /** @internal */
  37137. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  37138. /** @internal */
  37139. void modifierKeysChanged (const ModifierKeys& modifiers);
  37140. /** @internal */
  37141. void buttonClicked (Button* button);
  37142. /** @internal */
  37143. void lookAndFeelChanged();
  37144. /** @internal */
  37145. void enablementChanged();
  37146. /** @internal */
  37147. void focusOfChildComponentChanged (FocusChangeType cause);
  37148. /** @internal */
  37149. void handleAsyncUpdate();
  37150. /** @internal */
  37151. void colourChanged();
  37152. /** @internal */
  37153. void valueChanged (Value& value);
  37154. /** Returns the best number of decimal places to use when displaying numbers.
  37155. This is calculated from the slider's interval setting.
  37156. */
  37157. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  37158. private:
  37159. ListenerList <Listener> listeners;
  37160. Value currentValue, valueMin, valueMax;
  37161. double lastCurrentValue, lastValueMin, lastValueMax;
  37162. double minimum, maximum, interval, doubleClickReturnValue;
  37163. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  37164. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  37165. int velocityModeThreshold;
  37166. float rotaryStart, rotaryEnd;
  37167. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  37168. int mouseDragStartX, mouseDragStartY;
  37169. int sliderRegionStart, sliderRegionSize;
  37170. int sliderBeingDragged;
  37171. int pixelsForFullDragExtent;
  37172. Rectangle<int> sliderRect;
  37173. String textSuffix;
  37174. SliderStyle style;
  37175. TextEntryBoxPosition textBoxPos;
  37176. int textBoxWidth, textBoxHeight;
  37177. IncDecButtonMode incDecButtonMode;
  37178. bool editableText : 1, doubleClickToValue : 1;
  37179. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  37180. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  37181. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  37182. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  37183. ScopedPointer<Label> valueBox;
  37184. ScopedPointer<Button> incButton, decButton;
  37185. ScopedPointer <Component> popupDisplay;
  37186. Component* parentForPopupDisplay;
  37187. float getLinearSliderPos (double value);
  37188. void restoreMouseIfHidden();
  37189. void sendDragStart();
  37190. void sendDragEnd();
  37191. double constrainedValue (double value) const;
  37192. void triggerChangeMessage (bool synchronous);
  37193. bool incDecDragDirectionIsHorizontal() const;
  37194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  37195. };
  37196. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  37197. typedef Slider::Listener SliderListener;
  37198. #if JUCE_VC6
  37199. #undef Listener
  37200. #endif
  37201. #endif // __JUCE_SLIDER_JUCEHEADER__
  37202. /*** End of inlined file: juce_Slider.h ***/
  37203. #endif
  37204. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  37205. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  37206. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  37207. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  37208. /**
  37209. A component that displays a strip of column headings for a table, and allows these
  37210. to be resized, dragged around, etc.
  37211. This is just the component that goes at the top of a table. You can use it
  37212. directly for custom components, or to create a simple table, use the
  37213. TableListBox class.
  37214. To use one of these, create it and use addColumn() to add all the columns that you need.
  37215. Each column must be given a unique ID number that's used to refer to it.
  37216. @see TableListBox, TableHeaderComponent::Listener
  37217. */
  37218. class JUCE_API TableHeaderComponent : public Component,
  37219. private AsyncUpdater
  37220. {
  37221. public:
  37222. /** Creates an empty table header.
  37223. */
  37224. TableHeaderComponent();
  37225. /** Destructor. */
  37226. ~TableHeaderComponent();
  37227. /** A combination of these flags are passed into the addColumn() method to specify
  37228. the properties of a column.
  37229. */
  37230. enum ColumnPropertyFlags
  37231. {
  37232. 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. */
  37233. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  37234. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  37235. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  37236. 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. */
  37237. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  37238. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  37239. /** This set of default flags is used as the default parameter value in addColumn(). */
  37240. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  37241. /** A quick way of combining flags for a column that's not resizable. */
  37242. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  37243. /** A quick way of combining flags for a column that's not resizable or sortable. */
  37244. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  37245. /** A quick way of combining flags for a column that's not sortable. */
  37246. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  37247. };
  37248. /** Adds a column to the table.
  37249. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  37250. registered listeners.
  37251. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  37252. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  37253. a unique ID. This is used to identify the column later on, after the user may have
  37254. changed the order that they appear in
  37255. @param width the initial width of the column, in pixels
  37256. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  37257. if the 'resizable' flag is specified for this column
  37258. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  37259. if the 'resizable' flag is specified for this column
  37260. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  37261. properties of this column
  37262. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  37263. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  37264. all columns, not just the index amongst those that are currently visible
  37265. */
  37266. void addColumn (const String& columnName,
  37267. int columnId,
  37268. int width,
  37269. int minimumWidth = 30,
  37270. int maximumWidth = -1,
  37271. int propertyFlags = defaultFlags,
  37272. int insertIndex = -1);
  37273. /** Removes a column with the given ID.
  37274. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  37275. registered listeners.
  37276. */
  37277. void removeColumn (int columnIdToRemove);
  37278. /** Deletes all columns from the table.
  37279. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  37280. registered listeners.
  37281. */
  37282. void removeAllColumns();
  37283. /** Returns the number of columns in the table.
  37284. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  37285. return the total number of columns, including hidden ones.
  37286. @see isColumnVisible
  37287. */
  37288. int getNumColumns (bool onlyCountVisibleColumns) const;
  37289. /** Returns the name for a column.
  37290. @see setColumnName
  37291. */
  37292. const String getColumnName (int columnId) const;
  37293. /** Changes the name of a column. */
  37294. void setColumnName (int columnId, const String& newName);
  37295. /** Moves a column to a different index in the table.
  37296. @param columnId the column to move
  37297. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  37298. */
  37299. void moveColumn (int columnId, int newVisibleIndex);
  37300. /** Returns the width of one of the columns.
  37301. */
  37302. int getColumnWidth (int columnId) const;
  37303. /** Changes the width of a column.
  37304. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  37305. */
  37306. void setColumnWidth (int columnId, int newWidth);
  37307. /** Shows or hides a column.
  37308. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  37309. @see isColumnVisible
  37310. */
  37311. void setColumnVisible (int columnId, bool shouldBeVisible);
  37312. /** Returns true if this column is currently visible.
  37313. @see setColumnVisible
  37314. */
  37315. bool isColumnVisible (int columnId) const;
  37316. /** Changes the column which is the sort column.
  37317. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  37318. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  37319. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  37320. @see getSortColumnId, isSortedForwards, reSortTable
  37321. */
  37322. void setSortColumnId (int columnId, bool sortForwards);
  37323. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  37324. @see setSortColumnId, isSortedForwards
  37325. */
  37326. int getSortColumnId() const;
  37327. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  37328. @see setSortColumnId
  37329. */
  37330. bool isSortedForwards() const;
  37331. /** Triggers a re-sort of the table according to the current sort-column.
  37332. If you modifiy the table's contents, you can call this to signal that the table needs
  37333. to be re-sorted.
  37334. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  37335. tableSortOrderChanged() method of any listeners).
  37336. */
  37337. void reSortTable();
  37338. /** Returns the total width of all the visible columns in the table.
  37339. */
  37340. int getTotalWidth() const;
  37341. /** Returns the index of a given column.
  37342. If there's no such column ID, this will return -1.
  37343. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  37344. otherwise it'll return the index amongst all the columns, including any hidden ones.
  37345. */
  37346. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  37347. /** Returns the ID of the column at a given index.
  37348. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  37349. otherwise it'll count it amongst all the columns, including any hidden ones.
  37350. If the index is out-of-range, it'll return 0.
  37351. */
  37352. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  37353. /** Returns the rectangle containing of one of the columns.
  37354. The index is an index from 0 to the number of columns that are currently visible (hidden
  37355. ones are not counted). It returns a rectangle showing the position of the column relative
  37356. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  37357. */
  37358. const Rectangle<int> getColumnPosition (int index) const;
  37359. /** Finds the column ID at a given x-position in the component.
  37360. If there is a column at this point this returns its ID, or if not, it will return 0.
  37361. */
  37362. int getColumnIdAtX (int xToFind) const;
  37363. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  37364. entire width of the component.
  37365. By default this is disabled. Turning it on also means that when resizing a column, those
  37366. on the right will be squashed to fit.
  37367. */
  37368. void setStretchToFitActive (bool shouldStretchToFit);
  37369. /** Returns true if stretch-to-fit has been enabled.
  37370. @see setStretchToFitActive
  37371. */
  37372. bool isStretchToFitActive() const;
  37373. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  37374. specified width, keeping their relative proportions the same.
  37375. If the minimum widths of the columns are too wide to fit into this space, it may
  37376. actually end up wider.
  37377. */
  37378. void resizeAllColumnsToFit (int targetTotalWidth);
  37379. /** Enables or disables the pop-up menu.
  37380. The default menu allows the user to show or hide columns. You can add custom
  37381. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  37382. By default the menu is enabled.
  37383. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  37384. */
  37385. void setPopupMenuActive (bool hasMenu);
  37386. /** Returns true if the pop-up menu is enabled.
  37387. @see setPopupMenuActive
  37388. */
  37389. bool isPopupMenuActive() const;
  37390. /** Returns a string that encapsulates the table's current layout.
  37391. This can be restored later using restoreFromString(). It saves the order of
  37392. the columns, the currently-sorted column, and the widths.
  37393. @see restoreFromString
  37394. */
  37395. const String toString() const;
  37396. /** Restores the state of the table, based on a string previously created with
  37397. toString().
  37398. @see toString
  37399. */
  37400. void restoreFromString (const String& storedVersion);
  37401. /**
  37402. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  37403. You can register one of these objects for table events using TableHeaderComponent::addListener()
  37404. and TableHeaderComponent::removeListener().
  37405. @see TableHeaderComponent
  37406. */
  37407. class JUCE_API Listener
  37408. {
  37409. public:
  37410. Listener() {}
  37411. /** Destructor. */
  37412. virtual ~Listener() {}
  37413. /** This is called when some of the table's columns are added, removed, hidden,
  37414. or rearranged.
  37415. */
  37416. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  37417. /** This is called when one or more of the table's columns are resized.
  37418. */
  37419. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  37420. /** This is called when the column by which the table should be sorted is changed.
  37421. */
  37422. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  37423. /** This is called when the user begins or ends dragging one of the columns around.
  37424. When the user starts dragging a column, this is called with the ID of that
  37425. column. When they finish dragging, it is called again with 0 as the ID.
  37426. */
  37427. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  37428. int columnIdNowBeingDragged);
  37429. };
  37430. /** Adds a listener to be informed about things that happen to the header. */
  37431. void addListener (Listener* newListener);
  37432. /** Removes a previously-registered listener. */
  37433. void removeListener (Listener* listenerToRemove);
  37434. /** This can be overridden to handle a mouse-click on one of the column headers.
  37435. The default implementation will use this click to call getSortColumnId() and
  37436. change the sort order.
  37437. */
  37438. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  37439. /** This can be overridden to add custom items to the pop-up menu.
  37440. If you override this, you should call the superclass's method to add its
  37441. column show/hide items, if you want them on the menu as well.
  37442. Then to handle the result, override reactToMenuItem().
  37443. @see reactToMenuItem
  37444. */
  37445. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  37446. /** Override this to handle any custom items that you have added to the
  37447. pop-up menu with an addMenuItems() override.
  37448. If the menuReturnId isn't one of your own custom menu items, you'll need to
  37449. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  37450. handle the items that it had added.
  37451. @see addMenuItems
  37452. */
  37453. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  37454. /** @internal */
  37455. void paint (Graphics& g);
  37456. /** @internal */
  37457. void resized();
  37458. /** @internal */
  37459. void mouseMove (const MouseEvent&);
  37460. /** @internal */
  37461. void mouseEnter (const MouseEvent&);
  37462. /** @internal */
  37463. void mouseExit (const MouseEvent&);
  37464. /** @internal */
  37465. void mouseDown (const MouseEvent&);
  37466. /** @internal */
  37467. void mouseDrag (const MouseEvent&);
  37468. /** @internal */
  37469. void mouseUp (const MouseEvent&);
  37470. /** @internal */
  37471. const MouseCursor getMouseCursor();
  37472. /** Can be overridden for more control over the pop-up menu behaviour. */
  37473. virtual void showColumnChooserMenu (int columnIdClicked);
  37474. private:
  37475. struct ColumnInfo
  37476. {
  37477. String name;
  37478. int id, propertyFlags, width, minimumWidth, maximumWidth;
  37479. double lastDeliberateWidth;
  37480. bool isVisible() const;
  37481. };
  37482. OwnedArray <ColumnInfo> columns;
  37483. Array <Listener*> listeners;
  37484. ScopedPointer <Component> dragOverlayComp;
  37485. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  37486. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  37487. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  37488. ColumnInfo* getInfoForId (int columnId) const;
  37489. int visibleIndexToTotalIndex (int visibleIndex) const;
  37490. void sendColumnsChanged();
  37491. void handleAsyncUpdate();
  37492. void beginDrag (const MouseEvent&);
  37493. void endDrag (int finalIndex);
  37494. int getResizeDraggerAt (int mouseX) const;
  37495. void updateColumnUnderMouse (int x, int y);
  37496. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  37497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  37498. };
  37499. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  37500. typedef TableHeaderComponent::Listener TableHeaderListener;
  37501. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  37502. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  37503. #endif
  37504. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  37505. /*** Start of inlined file: juce_TableListBox.h ***/
  37506. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  37507. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  37508. /**
  37509. One of these is used by a TableListBox as the data model for the table's contents.
  37510. The virtual methods that you override in this class take care of drawing the
  37511. table cells, and reacting to events.
  37512. @see TableListBox
  37513. */
  37514. class JUCE_API TableListBoxModel
  37515. {
  37516. public:
  37517. TableListBoxModel() {}
  37518. /** Destructor. */
  37519. virtual ~TableListBoxModel() {}
  37520. /** This must return the number of rows currently in the table.
  37521. If the number of rows changes, you must call TableListBox::updateContent() to
  37522. cause it to refresh the list.
  37523. */
  37524. virtual int getNumRows() = 0;
  37525. /** This must draw the background behind one of the rows in the table.
  37526. The graphics context has its origin at the row's top-left, and your method
  37527. should fill the area specified by the width and height parameters.
  37528. */
  37529. virtual void paintRowBackground (Graphics& g,
  37530. int rowNumber,
  37531. int width, int height,
  37532. bool rowIsSelected) = 0;
  37533. /** This must draw one of the cells.
  37534. The graphics context's origin will already be set to the top-left of the cell,
  37535. whose size is specified by (width, height).
  37536. */
  37537. virtual void paintCell (Graphics& g,
  37538. int rowNumber,
  37539. int columnId,
  37540. int width, int height,
  37541. bool rowIsSelected) = 0;
  37542. /** This is used to create or update a custom component to go in a cell.
  37543. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  37544. and handle mouse clicks with cellClicked().
  37545. This method will be called whenever a custom component might need to be updated - e.g.
  37546. when the table is changed, or TableListBox::updateContent() is called.
  37547. If you don't need a custom component for the specified cell, then return 0.
  37548. If you do want a custom component, and the existingComponentToUpdate is null, then
  37549. this method must create a new component suitable for the cell, and return it.
  37550. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  37551. by this method. In this case, the method must either update it to make sure it's correctly representing
  37552. the given cell (which may be different from the one that the component was created for), or it can
  37553. delete this component and return a new one.
  37554. */
  37555. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  37556. Component* existingComponentToUpdate);
  37557. /** This callback is made when the user clicks on one of the cells in the table.
  37558. The mouse event's coordinates will be relative to the entire table row.
  37559. @see cellDoubleClicked, backgroundClicked
  37560. */
  37561. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  37562. /** This callback is made when the user clicks on one of the cells in the table.
  37563. The mouse event's coordinates will be relative to the entire table row.
  37564. @see cellClicked, backgroundClicked
  37565. */
  37566. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  37567. /** This can be overridden to react to the user double-clicking on a part of the list where
  37568. there are no rows.
  37569. @see cellClicked
  37570. */
  37571. virtual void backgroundClicked();
  37572. /** This callback is made when the table's sort order is changed.
  37573. This could be because the user has clicked a column header, or because the
  37574. TableHeaderComponent::setSortColumnId() method was called.
  37575. If you implement this, your method should re-sort the table using the given
  37576. column as the key.
  37577. */
  37578. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  37579. /** Returns the best width for one of the columns.
  37580. If you implement this method, you should measure the width of all the items
  37581. in this column, and return the best size.
  37582. Returning 0 means that the column shouldn't be changed.
  37583. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  37584. */
  37585. virtual int getColumnAutoSizeWidth (int columnId);
  37586. /** Returns a tooltip for a particular cell in the table.
  37587. */
  37588. virtual const String getCellTooltip (int rowNumber, int columnId);
  37589. /** Override this to be informed when rows are selected or deselected.
  37590. @see ListBox::selectedRowsChanged()
  37591. */
  37592. virtual void selectedRowsChanged (int lastRowSelected);
  37593. /** Override this to be informed when the delete key is pressed.
  37594. @see ListBox::deleteKeyPressed()
  37595. */
  37596. virtual void deleteKeyPressed (int lastRowSelected);
  37597. /** Override this to be informed when the return key is pressed.
  37598. @see ListBox::returnKeyPressed()
  37599. */
  37600. virtual void returnKeyPressed (int lastRowSelected);
  37601. /** Override this to be informed when the list is scrolled.
  37602. This might be caused by the user moving the scrollbar, or by programmatic changes
  37603. to the list position.
  37604. */
  37605. virtual void listWasScrolled();
  37606. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  37607. If this returns a non-empty name then when the user drags a row, the table will try to
  37608. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  37609. drag-and-drop operation, using this string as the source description, and the listbox
  37610. itself as the source component.
  37611. @see DragAndDropContainer::startDragging
  37612. */
  37613. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  37614. };
  37615. /**
  37616. A table of cells, using a TableHeaderComponent as its header.
  37617. This component makes it easy to create a table by providing a TableListBoxModel as
  37618. the data source.
  37619. @see TableListBoxModel, TableHeaderComponent
  37620. */
  37621. class JUCE_API TableListBox : public ListBox,
  37622. private ListBoxModel,
  37623. private TableHeaderComponent::Listener
  37624. {
  37625. public:
  37626. /** Creates a TableListBox.
  37627. The model pointer passed-in can be null, in which case you can set it later
  37628. with setModel().
  37629. */
  37630. TableListBox (const String& componentName = String::empty,
  37631. TableListBoxModel* model = 0);
  37632. /** Destructor. */
  37633. ~TableListBox();
  37634. /** Changes the TableListBoxModel that is being used for this table.
  37635. */
  37636. void setModel (TableListBoxModel* newModel);
  37637. /** Returns the model currently in use. */
  37638. TableListBoxModel* getModel() const { return model; }
  37639. /** Returns the header component being used in this table. */
  37640. TableHeaderComponent& getHeader() const { return *header; }
  37641. /** Changes the height of the table header component.
  37642. @see getHeaderHeight
  37643. */
  37644. void setHeaderHeight (int newHeight);
  37645. /** Returns the height of the table header.
  37646. @see setHeaderHeight
  37647. */
  37648. int getHeaderHeight() const;
  37649. /** Resizes a column to fit its contents.
  37650. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  37651. and applies that to the column.
  37652. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  37653. */
  37654. void autoSizeColumn (int columnId);
  37655. /** Calls autoSizeColumn() for all columns in the table. */
  37656. void autoSizeAllColumns();
  37657. /** Enables or disables the auto size options on the popup menu.
  37658. By default, these are enabled.
  37659. */
  37660. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  37661. /** True if the auto-size options should be shown on the menu.
  37662. @see setAutoSizeMenuOptionsShown
  37663. */
  37664. bool isAutoSizeMenuOptionShown() const;
  37665. /** Returns the position of one of the cells in the table.
  37666. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  37667. the table component's top-left. The row number isn't checked to see if it's
  37668. in-range, but the column ID must exist or this will return an empty rectangle.
  37669. If relativeToComponentTopLeft is false, the co-ords are relative to the
  37670. top-left of the table's top-left cell.
  37671. */
  37672. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  37673. bool relativeToComponentTopLeft) const;
  37674. /** Returns the component that currently represents a given cell.
  37675. If the component for this cell is off-screen or if the position is out-of-range,
  37676. this may return 0.
  37677. @see getCellPosition
  37678. */
  37679. Component* getCellComponent (int columnId, int rowNumber) const;
  37680. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  37681. @see ListBox::scrollToEnsureRowIsOnscreen
  37682. */
  37683. void scrollToEnsureColumnIsOnscreen (int columnId);
  37684. /** @internal */
  37685. int getNumRows();
  37686. /** @internal */
  37687. void paintListBoxItem (int, Graphics&, int, int, bool);
  37688. /** @internal */
  37689. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37690. /** @internal */
  37691. void selectedRowsChanged (int lastRowSelected);
  37692. /** @internal */
  37693. void deleteKeyPressed (int currentSelectedRow);
  37694. /** @internal */
  37695. void returnKeyPressed (int currentSelectedRow);
  37696. /** @internal */
  37697. void backgroundClicked();
  37698. /** @internal */
  37699. void listWasScrolled();
  37700. /** @internal */
  37701. void tableColumnsChanged (TableHeaderComponent*);
  37702. /** @internal */
  37703. void tableColumnsResized (TableHeaderComponent*);
  37704. /** @internal */
  37705. void tableSortOrderChanged (TableHeaderComponent*);
  37706. /** @internal */
  37707. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  37708. /** @internal */
  37709. void resized();
  37710. private:
  37711. TableHeaderComponent* header;
  37712. TableListBoxModel* model;
  37713. int columnIdNowBeingDragged;
  37714. bool autoSizeOptionsShown;
  37715. void updateColumnComponents() const;
  37716. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  37717. };
  37718. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  37719. /*** End of inlined file: juce_TableListBox.h ***/
  37720. #endif
  37721. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  37722. #endif
  37723. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  37724. #endif
  37725. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37726. #endif
  37727. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  37728. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  37729. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  37730. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  37731. /**
  37732. A factory object which can create ToolbarItemComponent objects.
  37733. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  37734. that it can create.
  37735. Each type of item is identified by a unique ID, and multiple instances of an
  37736. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  37737. bars).
  37738. @see Toolbar, ToolbarItemComponent, ToolbarButton
  37739. */
  37740. class JUCE_API ToolbarItemFactory
  37741. {
  37742. public:
  37743. ToolbarItemFactory();
  37744. /** Destructor. */
  37745. virtual ~ToolbarItemFactory();
  37746. /** A set of reserved item ID values, used for the built-in item types.
  37747. */
  37748. enum SpecialItemIds
  37749. {
  37750. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  37751. can be placed between sets of items to break them into groups. */
  37752. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  37753. items.*/
  37754. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  37755. either side of it, filling any available space. */
  37756. };
  37757. /** Must return a list of the IDs for all the item types that this factory can create.
  37758. The ids should be added to the array that is passed-in.
  37759. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  37760. and the predefined IDs in the SpecialItemIds enum.
  37761. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  37762. to this list if you want your toolbar to be able to contain those items.
  37763. The list returned here is used by the ToolbarItemPalette class to obtain its list
  37764. of available items, and their order on the palette will reflect the order in which
  37765. they appear on this list.
  37766. @see ToolbarItemPalette
  37767. */
  37768. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  37769. /** Must return the set of items that should be added to a toolbar as its default set.
  37770. This method is used by Toolbar::addDefaultItems() to determine which items to
  37771. create.
  37772. The items that your method adds to the array that is passed-in will be added to the
  37773. toolbar in the same order. Items can appear in the list more than once.
  37774. */
  37775. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  37776. /** Must create an instance of one of the items that the factory lists in its
  37777. getAllToolbarItemIds() method.
  37778. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  37779. method, except for the built-in item types from the SpecialItemIds enum, which
  37780. are created internally by the toolbar code.
  37781. Try not to keep a pointer to the object that is returned, as it will be deleted
  37782. automatically by the toolbar, and remember that multiple instances of the same
  37783. item type are likely to exist at the same time.
  37784. */
  37785. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  37786. };
  37787. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  37788. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  37789. #endif
  37790. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  37791. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  37792. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  37793. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  37794. /**
  37795. A component containing a list of toolbar items, which the user can drag onto
  37796. a toolbar to add them.
  37797. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  37798. which automatically shows one of these in a dialog box with lots of extra controls.
  37799. @see Toolbar
  37800. */
  37801. class JUCE_API ToolbarItemPalette : public Component,
  37802. public DragAndDropContainer
  37803. {
  37804. public:
  37805. /** Creates a palette of items for a given factory, with the aim of adding them
  37806. to the specified toolbar.
  37807. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  37808. set of items that are shown in this palette.
  37809. The toolbar and factory must not be deleted while this object exists.
  37810. */
  37811. ToolbarItemPalette (ToolbarItemFactory& factory,
  37812. Toolbar* toolbar);
  37813. /** Destructor. */
  37814. ~ToolbarItemPalette();
  37815. /** @internal */
  37816. void resized();
  37817. private:
  37818. ToolbarItemFactory& factory;
  37819. Toolbar* toolbar;
  37820. Viewport viewport;
  37821. OwnedArray <ToolbarItemComponent> items;
  37822. friend class Toolbar;
  37823. void replaceComponent (ToolbarItemComponent* comp);
  37824. void addComponent (int itemId, int index);
  37825. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  37826. };
  37827. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  37828. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  37829. #endif
  37830. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  37831. /*** Start of inlined file: juce_TreeView.h ***/
  37832. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  37833. #define __JUCE_TREEVIEW_JUCEHEADER__
  37834. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  37835. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  37836. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  37837. /**
  37838. Components derived from this class can have files dropped onto them by an external application.
  37839. @see DragAndDropContainer
  37840. */
  37841. class JUCE_API FileDragAndDropTarget
  37842. {
  37843. public:
  37844. /** Destructor. */
  37845. virtual ~FileDragAndDropTarget() {}
  37846. /** Callback to check whether this target is interested in the set of files being offered.
  37847. Note that this will be called repeatedly when the user is dragging the mouse around over your
  37848. component, so don't do anything time-consuming in here, like opening the files to have a look
  37849. inside them!
  37850. @param files the set of (absolute) pathnames of the files that the user is dragging
  37851. @returns true if this component wants to receive the other callbacks regarging this
  37852. type of object; if it returns false, no other callbacks will be made.
  37853. */
  37854. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  37855. /** Callback to indicate that some files are being dragged over this component.
  37856. This gets called when the user moves the mouse into this component while dragging.
  37857. Use this callback as a trigger to make your component repaint itself to give the
  37858. user feedback about whether the files can be dropped here or not.
  37859. @param files the set of (absolute) pathnames of the files that the user is dragging
  37860. @param x the mouse x position, relative to this component
  37861. @param y the mouse y position, relative to this component
  37862. */
  37863. virtual void fileDragEnter (const StringArray& files, int x, int y);
  37864. /** Callback to indicate that the user is dragging some files over this component.
  37865. This gets called when the user moves the mouse over this component while dragging.
  37866. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  37867. this lets you know what happens in-between.
  37868. @param files the set of (absolute) pathnames of the files that the user is dragging
  37869. @param x the mouse x position, relative to this component
  37870. @param y the mouse y position, relative to this component
  37871. */
  37872. virtual void fileDragMove (const StringArray& files, int x, int y);
  37873. /** Callback to indicate that the mouse has moved away from this component.
  37874. This gets called when the user moves the mouse out of this component while dragging
  37875. the files.
  37876. If you've used fileDragEnter() to repaint your component and give feedback, use this
  37877. as a signal to repaint it in its normal state.
  37878. @param files the set of (absolute) pathnames of the files that the user is dragging
  37879. */
  37880. virtual void fileDragExit (const StringArray& files);
  37881. /** Callback to indicate that the user has dropped the files onto this component.
  37882. When the user drops the files, this get called, and you can use the files in whatever
  37883. way is appropriate.
  37884. Note that after this is called, the fileDragExit method may not be called, so you should
  37885. clean up in here if there's anything you need to do when the drag finishes.
  37886. @param files the set of (absolute) pathnames of the files that the user is dragging
  37887. @param x the mouse x position, relative to this component
  37888. @param y the mouse y position, relative to this component
  37889. */
  37890. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  37891. };
  37892. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  37893. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  37894. class TreeView;
  37895. /**
  37896. An item in a treeview.
  37897. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  37898. own sub-items.
  37899. To implement an item that contains sub-items, override the itemOpennessChanged()
  37900. method so that when it is opened, it adds the new sub-items to itself using the
  37901. addSubItem method. Depending on the nature of the item it might choose to only
  37902. do this the first time it's opened, or it might want to refresh itself each time.
  37903. It also has the option of deleting its sub-items when it is closed, or leaving them
  37904. in place.
  37905. */
  37906. class JUCE_API TreeViewItem
  37907. {
  37908. public:
  37909. /** Constructor. */
  37910. TreeViewItem();
  37911. /** Destructor. */
  37912. virtual ~TreeViewItem();
  37913. /** Returns the number of sub-items that have been added to this item.
  37914. Note that this doesn't mean much if the node isn't open.
  37915. @see getSubItem, mightContainSubItems, addSubItem
  37916. */
  37917. int getNumSubItems() const throw();
  37918. /** Returns one of the item's sub-items.
  37919. Remember that the object returned might get deleted at any time when its parent
  37920. item is closed or refreshed, depending on the nature of the items you're using.
  37921. @see getNumSubItems
  37922. */
  37923. TreeViewItem* getSubItem (int index) const throw();
  37924. /** Removes any sub-items. */
  37925. void clearSubItems();
  37926. /** Adds a sub-item.
  37927. @param newItem the object to add to the item's sub-item list. Once added, these can be
  37928. found using getSubItem(). When the items are later removed with
  37929. removeSubItem() (or when this item is deleted), they will be deleted.
  37930. @param insertPosition the index which the new item should have when it's added. If this
  37931. value is less than 0, the item will be added to the end of the list.
  37932. */
  37933. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  37934. /** Removes one of the sub-items.
  37935. @param index the item to remove
  37936. @param deleteItem if true, the item that is removed will also be deleted.
  37937. */
  37938. void removeSubItem (int index, bool deleteItem = true);
  37939. /** Returns the TreeView to which this item belongs. */
  37940. TreeView* getOwnerView() const throw() { return ownerView; }
  37941. /** Returns the item within which this item is contained. */
  37942. TreeViewItem* getParentItem() const throw() { return parentItem; }
  37943. /** True if this item is currently open in the treeview. */
  37944. bool isOpen() const throw();
  37945. /** Opens or closes the item.
  37946. When opened or closed, the item's itemOpennessChanged() method will be called,
  37947. and a subclass should use this callback to create and add any sub-items that
  37948. it needs to.
  37949. @see itemOpennessChanged, mightContainSubItems
  37950. */
  37951. void setOpen (bool shouldBeOpen);
  37952. /** True if this item is currently selected.
  37953. Use this when painting the node, to decide whether to draw it as selected or not.
  37954. */
  37955. bool isSelected() const throw();
  37956. /** Selects or deselects the item.
  37957. This will cause a callback to itemSelectionChanged()
  37958. */
  37959. void setSelected (bool shouldBeSelected,
  37960. bool deselectOtherItemsFirst);
  37961. /** Returns the rectangle that this item occupies.
  37962. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  37963. top-left of the TreeView comp, so this will depend on the scroll-position of
  37964. the tree. If false, it is relative to the top-left of the topmost item in the
  37965. tree (so this would be unaffected by scrolling the view).
  37966. */
  37967. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  37968. /** Sends a signal to the treeview to make it refresh itself.
  37969. Call this if your items have changed and you want the tree to update to reflect
  37970. this.
  37971. */
  37972. void treeHasChanged() const throw();
  37973. /** Sends a repaint message to redraw just this item.
  37974. Note that you should only call this if you want to repaint a superficial change. If
  37975. you're altering the tree's nodes, you should instead call treeHasChanged().
  37976. */
  37977. void repaintItem() const;
  37978. /** Returns the row number of this item in the tree.
  37979. The row number of an item will change according to which items are open.
  37980. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  37981. */
  37982. int getRowNumberInTree() const throw();
  37983. /** Returns true if all the item's parent nodes are open.
  37984. This is useful to check whether the item might actually be visible or not.
  37985. */
  37986. bool areAllParentsOpen() const throw();
  37987. /** Changes whether lines are drawn to connect any sub-items to this item.
  37988. By default, line-drawing is turned on.
  37989. */
  37990. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  37991. /** Tells the tree whether this item can potentially be opened.
  37992. If your item could contain sub-items, this should return true; if it returns
  37993. false then the tree will not try to open the item. This determines whether or
  37994. not the item will be drawn with a 'plus' button next to it.
  37995. */
  37996. virtual bool mightContainSubItems() = 0;
  37997. /** Returns a string to uniquely identify this item.
  37998. If you're planning on using the TreeView::getOpennessState() method, then
  37999. these strings will be used to identify which nodes are open. The string
  38000. should be unique amongst the item's sibling items, but it's ok for there
  38001. to be duplicates at other levels of the tree.
  38002. If you're not going to store the state, then it's ok not to bother implementing
  38003. this method.
  38004. */
  38005. virtual const String getUniqueName() const;
  38006. /** Called when an item is opened or closed.
  38007. When setOpen() is called and the item has specified that it might
  38008. have sub-items with the mightContainSubItems() method, this method
  38009. is called to let the item create or manage its sub-items.
  38010. So when this is called with isNowOpen set to true (i.e. when the item is being
  38011. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  38012. refresh its sub-item list.
  38013. When this is called with isNowOpen set to false, the subclass might want
  38014. to use clearSubItems() to save on space, or it might choose to leave them,
  38015. depending on the nature of the tree.
  38016. You could also use this callback as a trigger to start a background process
  38017. which asynchronously creates sub-items and adds them, if that's more
  38018. appropriate for the task in hand.
  38019. @see mightContainSubItems
  38020. */
  38021. virtual void itemOpennessChanged (bool isNowOpen);
  38022. /** Must return the width required by this item.
  38023. If your item needs to have a particular width in pixels, return that value; if
  38024. you'd rather have it just fill whatever space is available in the treeview,
  38025. return -1.
  38026. If all your items return -1, no horizontal scrollbar will be shown, but if any
  38027. items have fixed widths and extend beyond the width of the treeview, a
  38028. scrollbar will appear.
  38029. Each item can be a different width, but if they change width, you should call
  38030. treeHasChanged() to update the tree.
  38031. */
  38032. virtual int getItemWidth() const { return -1; }
  38033. /** Must return the height required by this item.
  38034. This is the height in pixels that the item will take up. Items in the tree
  38035. can be different heights, but if they change height, you should call
  38036. treeHasChanged() to update the tree.
  38037. */
  38038. virtual int getItemHeight() const { return 20; }
  38039. /** You can override this method to return false if you don't want to allow the
  38040. user to select this item.
  38041. */
  38042. virtual bool canBeSelected() const { return true; }
  38043. /** Creates a component that will be used to represent this item.
  38044. You don't have to implement this method - if it returns 0 then no component
  38045. will be used for the item, and you can just draw it using the paintItem()
  38046. callback. But if you do return a component, it will be positioned in the
  38047. treeview so that it can be used to represent this item.
  38048. The component returned will be managed by the treeview, so always return
  38049. a new component, and don't keep a reference to it, as the treeview will
  38050. delete it later when it goes off the screen or is no longer needed. Also
  38051. bear in mind that if the component keeps a reference to the item that
  38052. created it, that item could be deleted before the component. Its position
  38053. and size will be completely managed by the tree, so don't attempt to move it
  38054. around.
  38055. Something you may want to do with your component is to give it a pointer to
  38056. the TreeView that created it. This is perfectly safe, and there's no danger
  38057. of it becoming a dangling pointer because the TreeView will always delete
  38058. the component before it is itself deleted.
  38059. As long as you stick to these rules you can return whatever kind of
  38060. component you like. It's most useful if you're doing things like drag-and-drop
  38061. of items, or want to use a Label component to edit item names, etc.
  38062. */
  38063. virtual Component* createItemComponent() { return 0; }
  38064. /** Draws the item's contents.
  38065. You can choose to either implement this method and draw each item, or you
  38066. can use createItemComponent() to create a component that will represent the
  38067. item.
  38068. If all you need in your tree is to be able to draw the items and detect when
  38069. the user selects or double-clicks one of them, it's probably enough to
  38070. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  38071. complicated interactions, you may need to use createItemComponent() instead.
  38072. @param g the graphics context to draw into
  38073. @param width the width of the area available for drawing
  38074. @param height the height of the area available for drawing
  38075. */
  38076. virtual void paintItem (Graphics& g, int width, int height);
  38077. /** Draws the item's open/close button.
  38078. If you don't implement this method, the default behaviour is to
  38079. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  38080. it for custom effects.
  38081. */
  38082. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  38083. /** Called when the user clicks on this item.
  38084. If you're using createItemComponent() to create a custom component for the
  38085. item, the mouse-clicks might not make it through to the treeview, but this
  38086. is how you find out about clicks when just drawing each item individually.
  38087. The associated mouse-event details are passed in, so you can find out about
  38088. which button, where it was, etc.
  38089. @see itemDoubleClicked
  38090. */
  38091. virtual void itemClicked (const MouseEvent& e);
  38092. /** Called when the user double-clicks on this item.
  38093. If you're using createItemComponent() to create a custom component for the
  38094. item, the mouse-clicks might not make it through to the treeview, but this
  38095. is how you find out about clicks when just drawing each item individually.
  38096. The associated mouse-event details are passed in, so you can find out about
  38097. which button, where it was, etc.
  38098. If not overridden, the base class method here will open or close the item as
  38099. if the 'plus' button had been clicked.
  38100. @see itemClicked
  38101. */
  38102. virtual void itemDoubleClicked (const MouseEvent& e);
  38103. /** Called when the item is selected or deselected.
  38104. Use this if you want to do something special when the item's selectedness
  38105. changes. By default it'll get repainted when this happens.
  38106. */
  38107. virtual void itemSelectionChanged (bool isNowSelected);
  38108. /** The item can return a tool tip string here if it wants to.
  38109. @see TooltipClient
  38110. */
  38111. virtual const String getTooltip();
  38112. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  38113. If this returns a non-empty name then when the user drags an item, the treeview will
  38114. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  38115. a drag-and-drop operation, using this string as the source description, with the treeview
  38116. itself as the source component.
  38117. If you need more complex drag-and-drop behaviour, you can use custom components for
  38118. the items, and use those to trigger the drag.
  38119. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  38120. isInterestedInFileDrag(), etc.
  38121. @see DragAndDropContainer::startDragging
  38122. */
  38123. virtual const String getDragSourceDescription();
  38124. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  38125. method and return true.
  38126. If you return true and allow some files to be dropped, you'll also need to implement the
  38127. filesDropped() method to do something with them.
  38128. Note that this will be called often, so make your implementation very quick! There's
  38129. certainly no time to try opening the files and having a think about what's inside them!
  38130. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  38131. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  38132. */
  38133. virtual bool isInterestedInFileDrag (const StringArray& files);
  38134. /** When files are dropped into this item, this callback is invoked.
  38135. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  38136. The insertIndex value indicates where in the list of sub-items the files were dropped.
  38137. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  38138. */
  38139. virtual void filesDropped (const StringArray& files, int insertIndex);
  38140. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  38141. If you implement this method, you'll also need to implement itemDropped() in order to handle
  38142. the items when they are dropped.
  38143. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  38144. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  38145. */
  38146. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  38147. /** When a things are dropped into this item, this callback is invoked.
  38148. For this to work, you need to have also implemented isInterestedInDragSource().
  38149. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  38150. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  38151. */
  38152. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  38153. /** Sets a flag to indicate that the item wants to be allowed
  38154. to draw all the way across to the left edge of the treeview.
  38155. By default this is false, which means that when the paintItem()
  38156. method is called, its graphics context is clipped to only allow
  38157. drawing within the item's rectangle. If this flag is set to true,
  38158. then the graphics context isn't clipped on its left side, so it
  38159. can draw all the way across to the left margin. Note that the
  38160. context will still have its origin in the same place though, so
  38161. the coordinates of anything to its left will be negative. It's
  38162. mostly useful if you want to draw a wider bar behind the
  38163. highlighted item.
  38164. */
  38165. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  38166. /** Saves the current state of open/closed nodes so it can be restored later.
  38167. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  38168. and records it as XML. To identify node objects it uses the
  38169. TreeViewItem::getUniqueName() method to create named paths. This
  38170. means that the same state of open/closed nodes can be restored to a
  38171. completely different instance of the tree, as long as it contains nodes
  38172. whose unique names are the same.
  38173. You'd normally want to use TreeView::getOpennessState() rather than call it
  38174. for a specific item, but this can be handy if you need to briefly save the state
  38175. for a section of the tree.
  38176. The caller is responsible for deleting the object that is returned.
  38177. @see TreeView::getOpennessState, restoreOpennessState
  38178. */
  38179. XmlElement* getOpennessState() const throw();
  38180. /** Restores the openness of this item and all its sub-items from a saved state.
  38181. See TreeView::restoreOpennessState for more details.
  38182. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  38183. for a specific item, but this can be handy if you need to briefly save the state
  38184. for a section of the tree.
  38185. @see TreeView::restoreOpennessState, getOpennessState
  38186. */
  38187. void restoreOpennessState (const XmlElement& xml) throw();
  38188. /** Returns the index of this item in its parent's sub-items. */
  38189. int getIndexInParent() const throw();
  38190. /** Returns true if this item is the last of its parent's sub-itens. */
  38191. bool isLastOfSiblings() const throw();
  38192. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  38193. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  38194. The string takes the form of a path, constructed from the getUniqueName() of this
  38195. item and all its parents, so these must all be correctly implemented for it to work.
  38196. @see TreeView::findItemFromIdentifierString, getUniqueName
  38197. */
  38198. const String getItemIdentifierString() const;
  38199. private:
  38200. TreeView* ownerView;
  38201. TreeViewItem* parentItem;
  38202. OwnedArray <TreeViewItem> subItems;
  38203. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  38204. int uid;
  38205. bool selected : 1;
  38206. bool redrawNeeded : 1;
  38207. bool drawLinesInside : 1;
  38208. bool drawsInLeftMargin : 1;
  38209. unsigned int openness : 2;
  38210. friend class TreeView;
  38211. friend class TreeViewContentComponent;
  38212. void updatePositions (int newY);
  38213. int getIndentX() const throw();
  38214. void setOwnerView (TreeView* newOwner) throw();
  38215. void paintRecursively (Graphics& g, int width);
  38216. TreeViewItem* getTopLevelItem() throw();
  38217. TreeViewItem* findItemRecursively (int y) throw();
  38218. TreeViewItem* getDeepestOpenParentItem() throw();
  38219. int getNumRows() const throw();
  38220. TreeViewItem* getItemOnRow (int index) throw();
  38221. void deselectAllRecursively();
  38222. int countSelectedItemsRecursively (int depth) const throw();
  38223. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  38224. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  38225. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  38226. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  38227. };
  38228. /**
  38229. A tree-view component.
  38230. Use one of these to hold and display a structure of TreeViewItem objects.
  38231. */
  38232. class JUCE_API TreeView : public Component,
  38233. public SettableTooltipClient,
  38234. public FileDragAndDropTarget,
  38235. public DragAndDropTarget,
  38236. private AsyncUpdater
  38237. {
  38238. public:
  38239. /** Creates an empty treeview.
  38240. Once you've got a treeview component, you'll need to give it something to
  38241. display, using the setRootItem() method.
  38242. */
  38243. TreeView (const String& componentName = String::empty);
  38244. /** Destructor. */
  38245. ~TreeView();
  38246. /** Sets the item that is displayed in the treeview.
  38247. A tree has a single root item which contains as many sub-items as it needs. If
  38248. you want the tree to contain a number of root items, you should still use a single
  38249. root item above these, but hide it using setRootItemVisible().
  38250. You can pass in 0 to this method to clear the tree and remove its current root item.
  38251. The object passed in will not be deleted by the treeview, it's up to the caller
  38252. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  38253. this item until you've removed it from the tree, either by calling setRootItem (0),
  38254. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  38255. to delete it.
  38256. */
  38257. void setRootItem (TreeViewItem* newRootItem);
  38258. /** Returns the tree's root item.
  38259. This will be the last object passed to setRootItem(), or 0 if none has been set.
  38260. */
  38261. TreeViewItem* getRootItem() const throw() { return rootItem; }
  38262. /** This will remove and delete the current root item.
  38263. It's a convenient way of deleting the item and calling setRootItem (0).
  38264. */
  38265. void deleteRootItem();
  38266. /** Changes whether the tree's root item is shown or not.
  38267. If the root item is hidden, only its sub-items will be shown in the treeview - this
  38268. lets you make the tree look as if it's got many root items. If it's hidden, this call
  38269. will also make sure the root item is open (otherwise the treeview would look empty).
  38270. */
  38271. void setRootItemVisible (bool shouldBeVisible);
  38272. /** Returns true if the root item is visible.
  38273. @see setRootItemVisible
  38274. */
  38275. bool isRootItemVisible() const throw() { return rootItemVisible; }
  38276. /** Sets whether items are open or closed by default.
  38277. Normally, items are closed until the user opens them, but you can use this
  38278. to make them default to being open until explicitly closed.
  38279. @see areItemsOpenByDefault
  38280. */
  38281. void setDefaultOpenness (bool isOpenByDefault);
  38282. /** Returns true if the tree's items default to being open.
  38283. @see setDefaultOpenness
  38284. */
  38285. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  38286. /** This sets a flag to indicate that the tree can be used for multi-selection.
  38287. You can always select multiple items internally by calling the
  38288. TreeViewItem::setSelected() method, but this flag indicates whether the user
  38289. is allowed to multi-select by clicking on the tree.
  38290. By default it is disabled.
  38291. @see isMultiSelectEnabled
  38292. */
  38293. void setMultiSelectEnabled (bool canMultiSelect);
  38294. /** Returns whether multi-select has been enabled for the tree.
  38295. @see setMultiSelectEnabled
  38296. */
  38297. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  38298. /** Sets a flag to indicate whether to hide the open/close buttons.
  38299. @see areOpenCloseButtonsVisible
  38300. */
  38301. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  38302. /** Returns whether open/close buttons are shown.
  38303. @see setOpenCloseButtonsVisible
  38304. */
  38305. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  38306. /** Deselects any items that are currently selected. */
  38307. void clearSelectedItems();
  38308. /** Returns the number of items that are currently selected.
  38309. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  38310. tree will be recursed.
  38311. @see getSelectedItem, clearSelectedItems
  38312. */
  38313. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const throw();
  38314. /** Returns one of the selected items in the tree.
  38315. @param index the index, 0 to (getNumSelectedItems() - 1)
  38316. */
  38317. TreeViewItem* getSelectedItem (int index) const throw();
  38318. /** Returns the number of rows the tree is using.
  38319. This will depend on which items are open.
  38320. @see TreeViewItem::getRowNumberInTree()
  38321. */
  38322. int getNumRowsInTree() const;
  38323. /** Returns the item on a particular row of the tree.
  38324. If the index is out of range, this will return 0.
  38325. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  38326. */
  38327. TreeViewItem* getItemOnRow (int index) const;
  38328. /** Returns the item that contains a given y position.
  38329. The y is relative to the top of the TreeView component.
  38330. */
  38331. TreeViewItem* getItemAt (int yPosition) const throw();
  38332. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  38333. void scrollToKeepItemVisible (TreeViewItem* item);
  38334. /** Returns the treeview's Viewport object. */
  38335. Viewport* getViewport() const throw();
  38336. /** Returns the number of pixels by which each nested level of the tree is indented.
  38337. @see setIndentSize
  38338. */
  38339. int getIndentSize() const throw() { return indentSize; }
  38340. /** Changes the distance by which each nested level of the tree is indented.
  38341. @see getIndentSize
  38342. */
  38343. void setIndentSize (int newIndentSize);
  38344. /** Searches the tree for an item with the specified identifier.
  38345. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  38346. If no such item exists, this will return false. If the item is found, all of its items
  38347. will be automatically opened.
  38348. */
  38349. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  38350. /** Saves the current state of open/closed nodes so it can be restored later.
  38351. This takes a snapshot of which nodes have been explicitly opened or closed,
  38352. and records it as XML. To identify node objects it uses the
  38353. TreeViewItem::getUniqueName() method to create named paths. This
  38354. means that the same state of open/closed nodes can be restored to a
  38355. completely different instance of the tree, as long as it contains nodes
  38356. whose unique names are the same.
  38357. The caller is responsible for deleting the object that is returned.
  38358. @param alsoIncludeScrollPosition if this is true, the state will also
  38359. include information about where the
  38360. tree has been scrolled to vertically,
  38361. so this can also be restored
  38362. @see restoreOpennessState
  38363. */
  38364. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  38365. /** Restores a previously saved arrangement of open/closed nodes.
  38366. This will try to restore a snapshot of the tree's state that was created by
  38367. the getOpennessState() method. If any of the nodes named in the original
  38368. XML aren't present in this tree, they will be ignored.
  38369. @see getOpennessState
  38370. */
  38371. void restoreOpennessState (const XmlElement& newState);
  38372. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  38373. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38374. methods.
  38375. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38376. */
  38377. enum ColourIds
  38378. {
  38379. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  38380. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  38381. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  38382. };
  38383. /** @internal */
  38384. void paint (Graphics& g);
  38385. /** @internal */
  38386. void resized();
  38387. /** @internal */
  38388. bool keyPressed (const KeyPress& key);
  38389. /** @internal */
  38390. void colourChanged();
  38391. /** @internal */
  38392. void enablementChanged();
  38393. /** @internal */
  38394. bool isInterestedInFileDrag (const StringArray& files);
  38395. /** @internal */
  38396. void fileDragEnter (const StringArray& files, int x, int y);
  38397. /** @internal */
  38398. void fileDragMove (const StringArray& files, int x, int y);
  38399. /** @internal */
  38400. void fileDragExit (const StringArray& files);
  38401. /** @internal */
  38402. void filesDropped (const StringArray& files, int x, int y);
  38403. /** @internal */
  38404. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  38405. /** @internal */
  38406. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  38407. /** @internal */
  38408. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  38409. /** @internal */
  38410. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  38411. /** @internal */
  38412. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  38413. private:
  38414. friend class TreeViewItem;
  38415. friend class TreeViewContentComponent;
  38416. class TreeViewport;
  38417. class InsertPointHighlight;
  38418. class TargetGroupHighlight;
  38419. friend class ScopedPointer<TreeViewport>;
  38420. friend class ScopedPointer<InsertPointHighlight>;
  38421. friend class ScopedPointer<TargetGroupHighlight>;
  38422. ScopedPointer<TreeViewport> viewport;
  38423. CriticalSection nodeAlterationLock;
  38424. TreeViewItem* rootItem;
  38425. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  38426. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  38427. int indentSize;
  38428. bool defaultOpenness : 1;
  38429. bool needsRecalculating : 1;
  38430. bool rootItemVisible : 1;
  38431. bool multiSelectEnabled : 1;
  38432. bool openCloseButtonsVisible : 1;
  38433. void itemsChanged() throw();
  38434. void handleAsyncUpdate();
  38435. void moveSelectedRow (int delta);
  38436. void updateButtonUnderMouse (const MouseEvent& e);
  38437. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  38438. void hideDragHighlight() throw();
  38439. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  38440. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  38441. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  38442. const StringArray& files, const String& sourceDescription,
  38443. Component* sourceComponent) const throw();
  38444. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  38445. };
  38446. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  38447. /*** End of inlined file: juce_TreeView.h ***/
  38448. #endif
  38449. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38450. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  38451. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38452. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38453. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  38454. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38455. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38456. /*** Start of inlined file: juce_FileFilter.h ***/
  38457. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  38458. #define __JUCE_FILEFILTER_JUCEHEADER__
  38459. /**
  38460. Interface for deciding which files are suitable for something.
  38461. For example, this is used by DirectoryContentsList to select which files
  38462. go into the list.
  38463. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38464. */
  38465. class JUCE_API FileFilter
  38466. {
  38467. public:
  38468. /** Creates a filter with the given description.
  38469. The description can be returned later with the getDescription() method.
  38470. */
  38471. FileFilter (const String& filterDescription);
  38472. /** Destructor. */
  38473. virtual ~FileFilter();
  38474. /** Returns the description that the filter was created with. */
  38475. const String& getDescription() const throw();
  38476. /** Should return true if this file is suitable for inclusion in whatever context
  38477. the object is being used.
  38478. */
  38479. virtual bool isFileSuitable (const File& file) const = 0;
  38480. /** Should return true if this directory is suitable for inclusion in whatever context
  38481. the object is being used.
  38482. */
  38483. virtual bool isDirectorySuitable (const File& file) const = 0;
  38484. protected:
  38485. String description;
  38486. };
  38487. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  38488. /*** End of inlined file: juce_FileFilter.h ***/
  38489. /**
  38490. A class to asynchronously scan for details about the files in a directory.
  38491. This keeps a list of files and some information about them, using a background
  38492. thread to scan for more files. As files are found, it broadcasts change messages
  38493. to tell any listeners.
  38494. @see FileListComponent, FileBrowserComponent
  38495. */
  38496. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  38497. public TimeSliceClient
  38498. {
  38499. public:
  38500. /** Creates a directory list.
  38501. To set the directory it should point to, use setDirectory(), which will
  38502. also start it scanning for files on the background thread.
  38503. When the background thread finds and adds new files to this list, the
  38504. ChangeBroadcaster class will send a change message, so you can register
  38505. listeners and update them when the list changes.
  38506. @param fileFilter an optional filter to select which files are
  38507. included in the list. If this is 0, then all files
  38508. and directories are included. Make sure that the
  38509. filter doesn't get deleted during the lifetime of this
  38510. object
  38511. @param threadToUse a thread object that this list can use
  38512. to scan for files as a background task. Make sure
  38513. that the thread you give it has been started, or you
  38514. won't get any files!
  38515. */
  38516. DirectoryContentsList (const FileFilter* fileFilter,
  38517. TimeSliceThread& threadToUse);
  38518. /** Destructor. */
  38519. ~DirectoryContentsList();
  38520. /** Sets the directory to look in for files.
  38521. If the directory that's passed in is different to the current one, this will
  38522. also start the background thread scanning it for files.
  38523. */
  38524. void setDirectory (const File& directory,
  38525. bool includeDirectories,
  38526. bool includeFiles);
  38527. /** Returns the directory that's currently being used. */
  38528. const File& getDirectory() const;
  38529. /** Clears the list, and stops the thread scanning for files. */
  38530. void clear();
  38531. /** Clears the list and restarts scanning the directory for files. */
  38532. void refresh();
  38533. /** True if the background thread hasn't yet finished scanning for files. */
  38534. bool isStillLoading() const;
  38535. /** Tells the list whether or not to ignore hidden files.
  38536. By default these are ignored.
  38537. */
  38538. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  38539. /** Returns true if hidden files are ignored.
  38540. @see setIgnoresHiddenFiles
  38541. */
  38542. bool ignoresHiddenFiles() const;
  38543. /** Contains cached information about one of the files in a DirectoryContentsList.
  38544. */
  38545. struct FileInfo
  38546. {
  38547. /** The filename.
  38548. This isn't a full pathname, it's just the last part of the path, same as you'd
  38549. get from File::getFileName().
  38550. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  38551. */
  38552. String filename;
  38553. /** File size in bytes. */
  38554. int64 fileSize;
  38555. /** File modification time.
  38556. As supplied by File::getLastModificationTime().
  38557. */
  38558. Time modificationTime;
  38559. /** File creation time.
  38560. As supplied by File::getCreationTime().
  38561. */
  38562. Time creationTime;
  38563. /** True if the file is a directory. */
  38564. bool isDirectory;
  38565. /** True if the file is read-only. */
  38566. bool isReadOnly;
  38567. };
  38568. /** Returns the number of files currently available in the list.
  38569. The info about one of these files can be retrieved with getFileInfo() or
  38570. getFile().
  38571. Obviously as the background thread runs and scans the directory for files, this
  38572. number will change.
  38573. @see getFileInfo, getFile
  38574. */
  38575. int getNumFiles() const;
  38576. /** Returns the cached information about one of the files in the list.
  38577. If the index is in-range, this will return true and will copy the file's details
  38578. to the structure that is passed-in.
  38579. If it returns false, then the index wasn't in range, and the structure won't
  38580. be affected.
  38581. @see getNumFiles, getFile
  38582. */
  38583. bool getFileInfo (int index, FileInfo& resultInfo) const;
  38584. /** Returns one of the files in the list.
  38585. @param index should be less than getNumFiles(). If this is out-of-range, the
  38586. return value will be File::nonexistent
  38587. @see getNumFiles, getFileInfo
  38588. */
  38589. const File getFile (int index) const;
  38590. /** Returns the file filter being used.
  38591. The filter is specified in the constructor.
  38592. */
  38593. const FileFilter* getFilter() const { return fileFilter; }
  38594. /** @internal */
  38595. bool useTimeSlice();
  38596. /** @internal */
  38597. TimeSliceThread& getTimeSliceThread() { return thread; }
  38598. /** @internal */
  38599. static int compareElements (const DirectoryContentsList::FileInfo* first,
  38600. const DirectoryContentsList::FileInfo* second);
  38601. private:
  38602. File root;
  38603. const FileFilter* fileFilter;
  38604. TimeSliceThread& thread;
  38605. int fileTypeFlags;
  38606. CriticalSection fileListLock;
  38607. OwnedArray <FileInfo> files;
  38608. ScopedPointer <DirectoryIterator> fileFindHandle;
  38609. bool volatile shouldStop;
  38610. void changed();
  38611. bool checkNextFile (bool& hasChanged);
  38612. bool addFile (const File& file, bool isDir,
  38613. const int64 fileSize, const Time& modTime,
  38614. const Time& creationTime, bool isReadOnly);
  38615. void setTypeFlags (int newFlags);
  38616. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  38617. };
  38618. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38619. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  38620. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  38621. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38622. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38623. /**
  38624. A listener for user selection events in a file browser.
  38625. This is used by a FileBrowserComponent or FileListComponent.
  38626. */
  38627. class JUCE_API FileBrowserListener
  38628. {
  38629. public:
  38630. /** Destructor. */
  38631. virtual ~FileBrowserListener();
  38632. /** Callback when the user selects a different file in the browser. */
  38633. virtual void selectionChanged() = 0;
  38634. /** Callback when the user clicks on a file in the browser. */
  38635. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  38636. /** Callback when the user double-clicks on a file in the browser. */
  38637. virtual void fileDoubleClicked (const File& file) = 0;
  38638. };
  38639. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38640. /*** End of inlined file: juce_FileBrowserListener.h ***/
  38641. /**
  38642. A base class for components that display a list of the files in a directory.
  38643. @see DirectoryContentsList
  38644. */
  38645. class JUCE_API DirectoryContentsDisplayComponent
  38646. {
  38647. public:
  38648. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  38649. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  38650. /** Destructor. */
  38651. virtual ~DirectoryContentsDisplayComponent();
  38652. /** Returns the number of files the user has got selected.
  38653. @see getSelectedFile
  38654. */
  38655. virtual int getNumSelectedFiles() const = 0;
  38656. /** Returns one of the files that the user has currently selected.
  38657. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  38658. @see getNumSelectedFiles
  38659. */
  38660. virtual const File getSelectedFile (int index) const = 0;
  38661. /** Deselects any selected files. */
  38662. virtual void deselectAllFiles() = 0;
  38663. /** Scrolls this view to the top. */
  38664. virtual void scrollToTop() = 0;
  38665. /** Adds a listener to be told when files are selected or clicked.
  38666. @see removeListener
  38667. */
  38668. void addListener (FileBrowserListener* listener);
  38669. /** Removes a listener.
  38670. @see addListener
  38671. */
  38672. void removeListener (FileBrowserListener* listener);
  38673. /** A set of colour IDs to use to change the colour of various aspects of the list.
  38674. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38675. methods.
  38676. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38677. */
  38678. enum ColourIds
  38679. {
  38680. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  38681. textColourId = 0x1000541, /**< The colour for the text. */
  38682. };
  38683. /** @internal */
  38684. void sendSelectionChangeMessage();
  38685. /** @internal */
  38686. void sendDoubleClickMessage (const File& file);
  38687. /** @internal */
  38688. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  38689. protected:
  38690. DirectoryContentsList& fileList;
  38691. ListenerList <FileBrowserListener> listeners;
  38692. private:
  38693. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  38694. };
  38695. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  38696. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  38697. #endif
  38698. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  38699. #endif
  38700. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38701. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  38702. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38703. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38704. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  38705. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38706. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38707. /**
  38708. Base class for components that live inside a file chooser dialog box and
  38709. show previews of the files that get selected.
  38710. One of these allows special extra information to be displayed for files
  38711. in a dialog box as the user selects them. Each time the current file or
  38712. directory is changed, the selectedFileChanged() method will be called
  38713. to allow it to update itself appropriately.
  38714. @see FileChooser, ImagePreviewComponent
  38715. */
  38716. class JUCE_API FilePreviewComponent : public Component
  38717. {
  38718. public:
  38719. /** Creates a FilePreviewComponent. */
  38720. FilePreviewComponent();
  38721. /** Destructor. */
  38722. ~FilePreviewComponent();
  38723. /** Called to indicate that the user's currently selected file has changed.
  38724. @param newSelectedFile the newly selected file or directory, which may be
  38725. File::nonexistent if none is selected.
  38726. */
  38727. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  38728. private:
  38729. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  38730. };
  38731. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38732. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  38733. /**
  38734. A component for browsing and selecting a file or directory to open or save.
  38735. This contains a FileListComponent and adds various boxes and controls for
  38736. navigating and selecting a file. It can work in different modes so that it can
  38737. be used for loading or saving a file, or for choosing a directory.
  38738. @see FileChooserDialogBox, FileChooser, FileListComponent
  38739. */
  38740. class JUCE_API FileBrowserComponent : public Component,
  38741. public ChangeBroadcaster,
  38742. private FileBrowserListener,
  38743. private TextEditorListener,
  38744. private ButtonListener,
  38745. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38746. private FileFilter
  38747. {
  38748. public:
  38749. /** Various options for the browser.
  38750. A combination of these is passed into the FileBrowserComponent constructor.
  38751. */
  38752. enum FileChooserFlags
  38753. {
  38754. openMode = 1, /**< specifies that the component should allow the user to
  38755. choose an existing file with the intention of opening it. */
  38756. saveMode = 2, /**< specifies that the component should allow the user to specify
  38757. the name of a file that will be used to save something. */
  38758. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  38759. conjunction with canSelectDirectories). */
  38760. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  38761. conjuction with canSelectFiles). */
  38762. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  38763. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  38764. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  38765. };
  38766. /** Creates a FileBrowserComponent.
  38767. @param flags A combination of flags from the FileChooserFlags enumeration,
  38768. used to specify the component's behaviour. The flags must contain
  38769. either openMode or saveMode, and canSelectFiles and/or
  38770. canSelectDirectories.
  38771. @param initialFileOrDirectory The file or directory that should be selected when
  38772. the component begins. If this is File::nonexistent,
  38773. a default directory will be chosen.
  38774. @param fileFilter an optional filter to use to determine which files
  38775. are shown. If this is 0 then all files are displayed. Note
  38776. that a pointer is kept internally to this object, so
  38777. make sure that it is not deleted before the browser object
  38778. is deleted.
  38779. @param previewComp an optional preview component that will be used to
  38780. show previews of files that the user selects
  38781. */
  38782. FileBrowserComponent (int flags,
  38783. const File& initialFileOrDirectory,
  38784. const FileFilter* fileFilter,
  38785. FilePreviewComponent* previewComp);
  38786. /** Destructor. */
  38787. ~FileBrowserComponent();
  38788. /** Returns the number of files that the user has got selected.
  38789. If multiple select isn't active, this will only be 0 or 1. To get the complete
  38790. list of files they've chosen, pass an index to getCurrentFile().
  38791. */
  38792. int getNumSelectedFiles() const throw();
  38793. /** Returns one of the files that the user has chosen.
  38794. If the box has multi-select enabled, the index lets you specify which of the files
  38795. to get - see getNumSelectedFiles() to find out how many files were chosen.
  38796. @see getHighlightedFile
  38797. */
  38798. const File getSelectedFile (int index) const throw();
  38799. /** Deselects any files that are currently selected.
  38800. */
  38801. void deselectAllFiles();
  38802. /** Returns true if the currently selected file(s) are usable.
  38803. This can be used to decide whether the user can press "ok" for the
  38804. current file. What it does depends on the mode, so for example in an "open"
  38805. mode, this only returns true if a file has been selected and if it exists.
  38806. In a "save" mode, a non-existent file would also be valid.
  38807. */
  38808. bool currentFileIsValid() const;
  38809. /** This returns the last item in the view that the user has highlighted.
  38810. This may be different from getCurrentFile(), which returns the value
  38811. that is shown in the filename box, and if there are multiple selections,
  38812. this will only return one of them.
  38813. @see getSelectedFile
  38814. */
  38815. const File getHighlightedFile() const throw();
  38816. /** Returns the directory whose contents are currently being shown in the listbox. */
  38817. const File getRoot() const;
  38818. /** Changes the directory that's being shown in the listbox. */
  38819. void setRoot (const File& newRootDirectory);
  38820. /** Equivalent to pressing the "up" button to browse the parent directory. */
  38821. void goUp();
  38822. /** Refreshes the directory that's currently being listed. */
  38823. void refresh();
  38824. /** Changes the filter that's being used to sift the files. */
  38825. void setFileFilter (const FileFilter* newFileFilter);
  38826. /** Returns a verb to describe what should happen when the file is accepted.
  38827. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  38828. mode, it'll be "Save", etc.
  38829. */
  38830. virtual const String getActionVerb() const;
  38831. /** Returns true if the saveMode flag was set when this component was created.
  38832. */
  38833. bool isSaveMode() const throw();
  38834. /** Adds a listener to be told when the user selects and clicks on files.
  38835. @see removeListener
  38836. */
  38837. void addListener (FileBrowserListener* listener);
  38838. /** Removes a listener.
  38839. @see addListener
  38840. */
  38841. void removeListener (FileBrowserListener* listener);
  38842. /** @internal */
  38843. void resized();
  38844. /** @internal */
  38845. void buttonClicked (Button* b);
  38846. /** @internal */
  38847. void comboBoxChanged (ComboBox*);
  38848. /** @internal */
  38849. void textEditorTextChanged (TextEditor& editor);
  38850. /** @internal */
  38851. void textEditorReturnKeyPressed (TextEditor& editor);
  38852. /** @internal */
  38853. void textEditorEscapeKeyPressed (TextEditor& editor);
  38854. /** @internal */
  38855. void textEditorFocusLost (TextEditor& editor);
  38856. /** @internal */
  38857. bool keyPressed (const KeyPress& key);
  38858. /** @internal */
  38859. void selectionChanged();
  38860. /** @internal */
  38861. void fileClicked (const File& f, const MouseEvent& e);
  38862. /** @internal */
  38863. void fileDoubleClicked (const File& f);
  38864. /** @internal */
  38865. bool isFileSuitable (const File& file) const;
  38866. /** @internal */
  38867. bool isDirectorySuitable (const File&) const;
  38868. /** @internal */
  38869. FilePreviewComponent* getPreviewComponent() const throw();
  38870. protected:
  38871. /** Returns a list of names and paths for the default places the user might want to look.
  38872. Use an empty string to indicate a section break.
  38873. */
  38874. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  38875. private:
  38876. ScopedPointer <DirectoryContentsList> fileList;
  38877. const FileFilter* fileFilter;
  38878. int flags;
  38879. File currentRoot;
  38880. Array<File> chosenFiles;
  38881. ListenerList <FileBrowserListener> listeners;
  38882. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  38883. FilePreviewComponent* previewComp;
  38884. ComboBox currentPathBox;
  38885. TextEditor filenameBox;
  38886. Label fileLabel;
  38887. ScopedPointer<Button> goUpButton;
  38888. TimeSliceThread thread;
  38889. void sendListenerChangeMessage();
  38890. bool isFileOrDirSuitable (const File& f) const;
  38891. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  38892. };
  38893. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  38894. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  38895. #endif
  38896. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  38897. #endif
  38898. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  38899. /*** Start of inlined file: juce_FileChooser.h ***/
  38900. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  38901. #define __JUCE_FILECHOOSER_JUCEHEADER__
  38902. /**
  38903. Creates a dialog box to choose a file or directory to load or save.
  38904. To use a FileChooser:
  38905. - create one (as a local stack variable is the neatest way)
  38906. - call one of its browseFor.. methods
  38907. - if this returns true, the user has selected a file, so you can retrieve it
  38908. with the getResult() method.
  38909. e.g. @code
  38910. void loadMooseFile()
  38911. {
  38912. FileChooser myChooser ("Please select the moose you want to load...",
  38913. File::getSpecialLocation (File::userHomeDirectory),
  38914. "*.moose");
  38915. if (myChooser.browseForFileToOpen())
  38916. {
  38917. File mooseFile (myChooser.getResult());
  38918. loadMoose (mooseFile);
  38919. }
  38920. }
  38921. @endcode
  38922. */
  38923. class JUCE_API FileChooser
  38924. {
  38925. public:
  38926. /** Creates a FileChooser.
  38927. After creating one of these, use one of the browseFor... methods to display it.
  38928. @param dialogBoxTitle a text string to display in the dialog box to
  38929. tell the user what's going on
  38930. @param initialFileOrDirectory the file or directory that should be selected when
  38931. the dialog box opens. If this parameter is set to
  38932. File::nonexistent, a sensible default directory
  38933. will be used instead.
  38934. @param filePatternsAllowed a set of file patterns to specify which files can be
  38935. selected - each pattern should be separated by a
  38936. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  38937. empty string means that all files are allowed
  38938. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  38939. possible; if false, then a Juce-based browser dialog
  38940. box will always be used
  38941. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  38942. */
  38943. FileChooser (const String& dialogBoxTitle,
  38944. const File& initialFileOrDirectory = File::nonexistent,
  38945. const String& filePatternsAllowed = String::empty,
  38946. bool useOSNativeDialogBox = true);
  38947. /** Destructor. */
  38948. ~FileChooser();
  38949. /** Shows a dialog box to choose a file to open.
  38950. This will display the dialog box modally, using an "open file" mode, so that
  38951. it won't allow non-existent files or directories to be chosen.
  38952. @param previewComponent an optional component to display inside the dialog
  38953. box to show special info about the files that the user
  38954. is browsing. The component will not be deleted by this
  38955. object, so the caller must take care of it.
  38956. @returns true if the user selected a file, in which case, use the getResult()
  38957. method to find out what it was. Returns false if they cancelled instead.
  38958. @see browseForFileToSave, browseForDirectory
  38959. */
  38960. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  38961. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  38962. The files that are returned can be obtained by calling getResults(). See
  38963. browseForFileToOpen() for more info about the behaviour of this method.
  38964. */
  38965. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  38966. /** Shows a dialog box to choose a file to save.
  38967. This will display the dialog box modally, using an "save file" mode, so it
  38968. will allow non-existent files to be chosen, but not directories.
  38969. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  38970. the user if they're sure they want to overwrite a file that already
  38971. exists
  38972. @returns true if the user chose a file and pressed 'ok', in which case, use
  38973. the getResult() method to find out what the file was. Returns false
  38974. if they cancelled instead.
  38975. @see browseForFileToOpen, browseForDirectory
  38976. */
  38977. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  38978. /** Shows a dialog box to choose a directory.
  38979. This will display the dialog box modally, using an "open directory" mode, so it
  38980. will only allow directories to be returned, not files.
  38981. @returns true if the user chose a directory and pressed 'ok', in which case, use
  38982. the getResult() method to find out what they chose. Returns false
  38983. if they cancelled instead.
  38984. @see browseForFileToOpen, browseForFileToSave
  38985. */
  38986. bool browseForDirectory();
  38987. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  38988. The files that are returned can be obtained by calling getResults(). See
  38989. browseForFileToOpen() for more info about the behaviour of this method.
  38990. */
  38991. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  38992. /** Returns the last file that was chosen by one of the browseFor methods.
  38993. After calling the appropriate browseFor... method, this method lets you
  38994. find out what file or directory they chose.
  38995. Note that the file returned is only valid if the browse method returned true (i.e.
  38996. if the user pressed 'ok' rather than cancelling).
  38997. If you're using a multiple-file select, then use the getResults() method instead,
  38998. to obtain the list of all files chosen.
  38999. @see getResults
  39000. */
  39001. const File getResult() const;
  39002. /** Returns a list of all the files that were chosen during the last call to a
  39003. browse method.
  39004. This array may be empty if no files were chosen, or can contain multiple entries
  39005. if multiple files were chosen.
  39006. @see getResult
  39007. */
  39008. const Array<File>& getResults() const;
  39009. private:
  39010. String title, filters;
  39011. File startingFile;
  39012. Array<File> results;
  39013. bool useNativeDialogBox;
  39014. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  39015. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  39016. FilePreviewComponent* previewComponent);
  39017. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  39018. const String& filters, bool selectsDirectories, bool selectsFiles,
  39019. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  39020. FilePreviewComponent* previewComponent);
  39021. JUCE_LEAK_DETECTOR (FileChooser);
  39022. };
  39023. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  39024. /*** End of inlined file: juce_FileChooser.h ***/
  39025. #endif
  39026. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  39027. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  39028. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  39029. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  39030. /*** Start of inlined file: juce_ResizableWindow.h ***/
  39031. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  39032. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  39033. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  39034. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  39035. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  39036. /*** Start of inlined file: juce_DropShadower.h ***/
  39037. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  39038. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  39039. /**
  39040. Adds a drop-shadow to a component.
  39041. This object creates and manages a set of components which sit around a
  39042. component, creating a gaussian shadow around it. The components will track
  39043. the position of the component and if it's brought to the front they'll also
  39044. follow this.
  39045. For desktop windows you don't need to use this class directly - just
  39046. set the Component::windowHasDropShadow flag when calling
  39047. Component::addToDesktop(), and the system will create one of these if it's
  39048. needed (which it obviously isn't on the Mac, for example).
  39049. */
  39050. class JUCE_API DropShadower : public ComponentListener
  39051. {
  39052. public:
  39053. /** Creates a DropShadower.
  39054. @param alpha the opacity of the shadows, from 0 to 1.0
  39055. @param xOffset the horizontal displacement of the shadow, in pixels
  39056. @param yOffset the vertical displacement of the shadow, in pixels
  39057. @param blurRadius the radius of the blur to use for creating the shadow
  39058. */
  39059. DropShadower (float alpha = 0.5f,
  39060. int xOffset = 1,
  39061. int yOffset = 5,
  39062. float blurRadius = 10.0f);
  39063. /** Destructor. */
  39064. virtual ~DropShadower();
  39065. /** Attaches the DropShadower to the component you want to shadow. */
  39066. void setOwner (Component* componentToFollow);
  39067. /** @internal */
  39068. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  39069. /** @internal */
  39070. void componentBroughtToFront (Component& component);
  39071. /** @internal */
  39072. void componentParentHierarchyChanged (Component& component);
  39073. /** @internal */
  39074. void componentVisibilityChanged (Component& component);
  39075. private:
  39076. Component* owner;
  39077. OwnedArray<Component> shadowWindows;
  39078. Image shadowImageSections[12];
  39079. const int xOffset, yOffset;
  39080. const float alpha, blurRadius;
  39081. bool reentrant;
  39082. void updateShadows();
  39083. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  39084. void bringShadowWindowsToFront();
  39085. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  39086. };
  39087. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  39088. /*** End of inlined file: juce_DropShadower.h ***/
  39089. /**
  39090. A base class for top-level windows.
  39091. This class is used for components that are considered a major part of your
  39092. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  39093. etc. Things like menus that pop up briefly aren't derived from it.
  39094. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  39095. could itself be the child of another component.
  39096. The class manages a list of all instances of top-level windows that are in use,
  39097. and each one is also given the concept of being "active". The active window is
  39098. one that is actively being used by the user. This isn't quite the same as the
  39099. component with the keyboard focus, because there may be a popup menu or other
  39100. temporary window which gets keyboard focus while the active top level window is
  39101. unchanged.
  39102. A top-level window also has an optional drop-shadow.
  39103. @see ResizableWindow, DocumentWindow, DialogWindow
  39104. */
  39105. class JUCE_API TopLevelWindow : public Component
  39106. {
  39107. public:
  39108. /** Creates a TopLevelWindow.
  39109. @param name the name to give the component
  39110. @param addToDesktop if true, the window will be automatically added to the
  39111. desktop; if false, you can use it as a child component
  39112. */
  39113. TopLevelWindow (const String& name, bool addToDesktop);
  39114. /** Destructor. */
  39115. ~TopLevelWindow();
  39116. /** True if this is currently the TopLevelWindow that is actively being used.
  39117. This isn't quite the same as having keyboard focus, because the focus may be
  39118. on a child component or a temporary pop-up menu, etc, while this window is
  39119. still considered to be active.
  39120. @see activeWindowStatusChanged
  39121. */
  39122. bool isActiveWindow() const throw() { return windowIsActive_; }
  39123. /** This will set the bounds of the window so that it's centred in front of another
  39124. window.
  39125. If your app has a few windows open and want to pop up a dialog box for one of
  39126. them, you can use this to show it in front of the relevent parent window, which
  39127. is a bit neater than just having it appear in the middle of the screen.
  39128. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  39129. be used instead. If no window is focused, it'll just default to the middle of the
  39130. screen.
  39131. */
  39132. void centreAroundComponent (Component* componentToCentreAround,
  39133. int width, int height);
  39134. /** Turns the drop-shadow on and off. */
  39135. void setDropShadowEnabled (bool useShadow);
  39136. /** Sets whether an OS-native title bar will be used, or a Juce one.
  39137. @see isUsingNativeTitleBar
  39138. */
  39139. void setUsingNativeTitleBar (bool useNativeTitleBar);
  39140. /** Returns true if the window is currently using an OS-native title bar.
  39141. @see setUsingNativeTitleBar
  39142. */
  39143. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  39144. /** Returns the number of TopLevelWindow objects currently in use.
  39145. @see getTopLevelWindow
  39146. */
  39147. static int getNumTopLevelWindows() throw();
  39148. /** Returns one of the TopLevelWindow objects currently in use.
  39149. The index is 0 to (getNumTopLevelWindows() - 1).
  39150. */
  39151. static TopLevelWindow* getTopLevelWindow (int index) throw();
  39152. /** Returns the currently-active top level window.
  39153. There might not be one, of course, so this can return 0.
  39154. */
  39155. static TopLevelWindow* getActiveTopLevelWindow() throw();
  39156. /** @internal */
  39157. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  39158. protected:
  39159. /** This callback happens when this window becomes active or inactive.
  39160. @see isActiveWindow
  39161. */
  39162. virtual void activeWindowStatusChanged();
  39163. /** @internal */
  39164. void focusOfChildComponentChanged (FocusChangeType cause);
  39165. /** @internal */
  39166. void parentHierarchyChanged();
  39167. /** @internal */
  39168. virtual int getDesktopWindowStyleFlags() const;
  39169. /** @internal */
  39170. void recreateDesktopWindow();
  39171. /** @internal */
  39172. void visibilityChanged();
  39173. private:
  39174. friend class TopLevelWindowManager;
  39175. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  39176. ScopedPointer <DropShadower> shadower;
  39177. void setWindowActive (bool isNowActive);
  39178. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  39179. };
  39180. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  39181. /*** End of inlined file: juce_TopLevelWindow.h ***/
  39182. /*** Start of inlined file: juce_ComponentDragger.h ***/
  39183. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  39184. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  39185. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  39186. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  39187. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  39188. /**
  39189. A class that imposes restrictions on a Component's size or position.
  39190. This is used by classes such as ResizableCornerComponent,
  39191. ResizableBorderComponent and ResizableWindow.
  39192. The base class can impose some basic size and position limits, but you can
  39193. also subclass this for custom uses.
  39194. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  39195. */
  39196. class JUCE_API ComponentBoundsConstrainer
  39197. {
  39198. public:
  39199. /** When first created, the object will not impose any restrictions on the components. */
  39200. ComponentBoundsConstrainer() throw();
  39201. /** Destructor. */
  39202. virtual ~ComponentBoundsConstrainer();
  39203. /** Imposes a minimum width limit. */
  39204. void setMinimumWidth (int minimumWidth) throw();
  39205. /** Returns the current minimum width. */
  39206. int getMinimumWidth() const throw() { return minW; }
  39207. /** Imposes a maximum width limit. */
  39208. void setMaximumWidth (int maximumWidth) throw();
  39209. /** Returns the current maximum width. */
  39210. int getMaximumWidth() const throw() { return maxW; }
  39211. /** Imposes a minimum height limit. */
  39212. void setMinimumHeight (int minimumHeight) throw();
  39213. /** Returns the current minimum height. */
  39214. int getMinimumHeight() const throw() { return minH; }
  39215. /** Imposes a maximum height limit. */
  39216. void setMaximumHeight (int maximumHeight) throw();
  39217. /** Returns the current maximum height. */
  39218. int getMaximumHeight() const throw() { return maxH; }
  39219. /** Imposes a minimum width and height limit. */
  39220. void setMinimumSize (int minimumWidth,
  39221. int minimumHeight) throw();
  39222. /** Imposes a maximum width and height limit. */
  39223. void setMaximumSize (int maximumWidth,
  39224. int maximumHeight) throw();
  39225. /** Set all the maximum and minimum dimensions. */
  39226. void setSizeLimits (int minimumWidth,
  39227. int minimumHeight,
  39228. int maximumWidth,
  39229. int maximumHeight) throw();
  39230. /** Sets the amount by which the component is allowed to go off-screen.
  39231. The values indicate how many pixels must remain on-screen when dragged off
  39232. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  39233. when the component goes off the top of the screen, its y-position will be
  39234. clipped so that there are always at least 10 pixels on-screen. In other words,
  39235. the lowest y-position it can take would be (10 - the component's height).
  39236. If you pass 0 or less for one of these amounts, the component is allowed
  39237. to move beyond that edge completely, with no restrictions at all.
  39238. If you pass a very large number (i.e. larger that the dimensions of the
  39239. component itself), then the component won't be allowed to overlap that
  39240. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  39241. the component will bump into the left side of the screen and go no further.
  39242. */
  39243. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  39244. int minimumWhenOffTheLeft,
  39245. int minimumWhenOffTheBottom,
  39246. int minimumWhenOffTheRight) throw();
  39247. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  39248. int getMinimumWhenOffTheTop() const throw() { return minOffTop; }
  39249. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  39250. int getMinimumWhenOffTheLeft() const throw() { return minOffLeft; }
  39251. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  39252. int getMinimumWhenOffTheBottom() const throw() { return minOffBottom; }
  39253. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  39254. int getMinimumWhenOffTheRight() const throw() { return minOffRight; }
  39255. /** Specifies a width-to-height ratio that the resizer should always maintain.
  39256. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  39257. will always be maintained as this multiple of the height.
  39258. @see setResizeLimits
  39259. */
  39260. void setFixedAspectRatio (double widthOverHeight) throw();
  39261. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  39262. If no aspect ratio is being enforced, this will return 0.
  39263. */
  39264. double getFixedAspectRatio() const throw();
  39265. /** This callback changes the given co-ordinates to impose whatever the current
  39266. constraints are set to be.
  39267. @param bounds the target position that should be examined and adjusted
  39268. @param previousBounds the component's current size
  39269. @param limits the region in which the component can be positioned
  39270. @param isStretchingTop whether the top edge of the component is being resized
  39271. @param isStretchingLeft whether the left edge of the component is being resized
  39272. @param isStretchingBottom whether the bottom edge of the component is being resized
  39273. @param isStretchingRight whether the right edge of the component is being resized
  39274. */
  39275. virtual void checkBounds (Rectangle<int>& bounds,
  39276. const Rectangle<int>& previousBounds,
  39277. const Rectangle<int>& limits,
  39278. bool isStretchingTop,
  39279. bool isStretchingLeft,
  39280. bool isStretchingBottom,
  39281. bool isStretchingRight);
  39282. /** This callback happens when the resizer is about to start dragging. */
  39283. virtual void resizeStart();
  39284. /** This callback happens when the resizer has finished dragging. */
  39285. virtual void resizeEnd();
  39286. /** Checks the given bounds, and then sets the component to the corrected size. */
  39287. void setBoundsForComponent (Component* component,
  39288. const Rectangle<int>& bounds,
  39289. bool isStretchingTop,
  39290. bool isStretchingLeft,
  39291. bool isStretchingBottom,
  39292. bool isStretchingRight);
  39293. /** Performs a check on the current size of a component, and moves or resizes
  39294. it if it fails the constraints.
  39295. */
  39296. void checkComponentBounds (Component* component);
  39297. /** Called by setBoundsForComponent() to apply a new constrained size to a
  39298. component.
  39299. By default this just calls setBounds(), but it virtual in case it's needed for
  39300. extremely cunning purposes.
  39301. */
  39302. virtual void applyBoundsToComponent (Component* component,
  39303. const Rectangle<int>& bounds);
  39304. private:
  39305. int minW, maxW, minH, maxH;
  39306. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  39307. double aspectRatio;
  39308. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  39309. };
  39310. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  39311. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  39312. /**
  39313. An object to take care of the logic for dragging components around with the mouse.
  39314. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  39315. then in your mouseDrag() callback, call dragComponent().
  39316. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  39317. to limit the component's position and keep it on-screen.
  39318. e.g. @code
  39319. class MyDraggableComp
  39320. {
  39321. ComponentDragger myDragger;
  39322. void mouseDown (const MouseEvent& e)
  39323. {
  39324. myDragger.startDraggingComponent (this, e);
  39325. }
  39326. void mouseDrag (const MouseEvent& e)
  39327. {
  39328. myDragger.dragComponent (this, e, 0);
  39329. }
  39330. };
  39331. @endcode
  39332. */
  39333. class JUCE_API ComponentDragger
  39334. {
  39335. public:
  39336. /** Creates a ComponentDragger. */
  39337. ComponentDragger();
  39338. /** Destructor. */
  39339. virtual ~ComponentDragger();
  39340. /** Call this from your component's mouseDown() method, to prepare for dragging.
  39341. @param componentToDrag the component that you want to drag
  39342. @param e the mouse event that is triggering the drag
  39343. @see dragComponent
  39344. */
  39345. void startDraggingComponent (Component* componentToDrag,
  39346. const MouseEvent& e);
  39347. /** Call this from your mouseDrag() callback to move the component.
  39348. This will move the component, but will first check the validity of the
  39349. component's new position using the checkPosition() method, which you
  39350. can override if you need to enforce special positioning limits on the
  39351. component.
  39352. @param componentToDrag the component that you want to drag
  39353. @param e the current mouse-drag event
  39354. @param constrainer an optional constrainer object that should be used
  39355. to apply limits to the component's position. Pass
  39356. null if you don't want to contrain the movement.
  39357. @see startDraggingComponent
  39358. */
  39359. void dragComponent (Component* componentToDrag,
  39360. const MouseEvent& e,
  39361. ComponentBoundsConstrainer* constrainer);
  39362. private:
  39363. Point<int> mouseDownWithinTarget;
  39364. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  39365. };
  39366. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  39367. /*** End of inlined file: juce_ComponentDragger.h ***/
  39368. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  39369. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39370. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39371. /**
  39372. A component that resizes its parent window when dragged.
  39373. This component forms a frame around the edge of a component, allowing it to
  39374. be dragged by the edges or corners to resize it - like the way windows are
  39375. resized in MSWindows or Linux.
  39376. To use it, just add it to your component, making it fill the entire parent component
  39377. (there's a mouse hit-test that only traps mouse-events which land around the
  39378. edge of the component, so it's even ok to put it on top of any other components
  39379. you're using). Make sure you rescale the resizer component to fill the parent
  39380. each time the parent's size changes.
  39381. @see ResizableCornerComponent
  39382. */
  39383. class JUCE_API ResizableBorderComponent : public Component
  39384. {
  39385. public:
  39386. /** Creates a resizer.
  39387. Pass in the target component which you want to be resized when this one is
  39388. dragged.
  39389. The target component will usually be a parent of the resizer component, but this
  39390. isn't mandatory.
  39391. Remember that when the target component is resized, it'll need to move and
  39392. resize this component to keep it in place, as this won't happen automatically.
  39393. If the constrainer parameter is non-zero, then this object will be used to enforce
  39394. limits on the size and position that the component can be stretched to. Make sure
  39395. that the constrainer isn't deleted while still in use by this object.
  39396. @see ComponentBoundsConstrainer
  39397. */
  39398. ResizableBorderComponent (Component* componentToResize,
  39399. ComponentBoundsConstrainer* constrainer);
  39400. /** Destructor. */
  39401. ~ResizableBorderComponent();
  39402. /** Specifies how many pixels wide the draggable edges of this component are.
  39403. @see getBorderThickness
  39404. */
  39405. void setBorderThickness (const BorderSize& newBorderSize);
  39406. /** Returns the number of pixels wide that the draggable edges of this component are.
  39407. @see setBorderThickness
  39408. */
  39409. const BorderSize getBorderThickness() const;
  39410. /** Represents the different sections of a resizable border, which allow it to
  39411. resized in different ways.
  39412. */
  39413. class Zone
  39414. {
  39415. public:
  39416. enum Zones
  39417. {
  39418. centre = 0,
  39419. left = 1,
  39420. top = 2,
  39421. right = 4,
  39422. bottom = 8
  39423. };
  39424. /** Creates a Zone from a combination of the flags in \enum Zones. */
  39425. explicit Zone (int zoneFlags = 0) throw();
  39426. Zone (const Zone& other) throw();
  39427. Zone& operator= (const Zone& other) throw();
  39428. bool operator== (const Zone& other) const throw();
  39429. bool operator!= (const Zone& other) const throw();
  39430. /** Given a point within a rectangle with a resizable border, this returns the
  39431. zone that the point lies within.
  39432. */
  39433. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  39434. const BorderSize& border,
  39435. const Point<int>& position);
  39436. /** Returns an appropriate mouse-cursor for this resize zone. */
  39437. const MouseCursor getMouseCursor() const throw();
  39438. /** Returns true if dragging this zone will move the enire object without resizing it. */
  39439. bool isDraggingWholeObject() const throw() { return zone == centre; }
  39440. /** Returns true if dragging this zone will move the object's left edge. */
  39441. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  39442. /** Returns true if dragging this zone will move the object's right edge. */
  39443. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  39444. /** Returns true if dragging this zone will move the object's top edge. */
  39445. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  39446. /** Returns true if dragging this zone will move the object's bottom edge. */
  39447. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  39448. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  39449. applies to.
  39450. */
  39451. template <typename ValueType>
  39452. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  39453. const Point<ValueType>& distance) const throw()
  39454. {
  39455. if (isDraggingWholeObject())
  39456. return original + distance;
  39457. if (isDraggingLeftEdge())
  39458. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  39459. if (isDraggingRightEdge())
  39460. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  39461. if (isDraggingTopEdge())
  39462. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  39463. if (isDraggingBottomEdge())
  39464. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  39465. return original;
  39466. }
  39467. /** Returns the raw flags for this zone. */
  39468. int getZoneFlags() const throw() { return zone; }
  39469. private:
  39470. int zone;
  39471. };
  39472. protected:
  39473. /** @internal */
  39474. void paint (Graphics& g);
  39475. /** @internal */
  39476. void mouseEnter (const MouseEvent& e);
  39477. /** @internal */
  39478. void mouseMove (const MouseEvent& e);
  39479. /** @internal */
  39480. void mouseDown (const MouseEvent& e);
  39481. /** @internal */
  39482. void mouseDrag (const MouseEvent& e);
  39483. /** @internal */
  39484. void mouseUp (const MouseEvent& e);
  39485. /** @internal */
  39486. bool hitTest (int x, int y);
  39487. private:
  39488. WeakReference<Component> component;
  39489. ComponentBoundsConstrainer* constrainer;
  39490. BorderSize borderSize;
  39491. Rectangle<int> originalBounds;
  39492. Zone mouseZone;
  39493. void updateMouseZone (const MouseEvent& e);
  39494. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  39495. };
  39496. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39497. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  39498. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  39499. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39500. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39501. /** A component that resizes a parent window when dragged.
  39502. This is the small triangular stripey resizer component you get in the bottom-right
  39503. of windows (more commonly on the Mac than Windows). Put one in the corner of
  39504. a larger component and it will automatically resize its parent when it gets dragged
  39505. around.
  39506. @see ResizableFrameComponent
  39507. */
  39508. class JUCE_API ResizableCornerComponent : public Component
  39509. {
  39510. public:
  39511. /** Creates a resizer.
  39512. Pass in the target component which you want to be resized when this one is
  39513. dragged.
  39514. The target component will usually be a parent of the resizer component, but this
  39515. isn't mandatory.
  39516. Remember that when the target component is resized, it'll need to move and
  39517. resize this component to keep it in place, as this won't happen automatically.
  39518. If the constrainer parameter is non-zero, then this object will be used to enforce
  39519. limits on the size and position that the component can be stretched to. Make sure
  39520. that the constrainer isn't deleted while still in use by this object. If you
  39521. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  39522. @see ComponentBoundsConstrainer
  39523. */
  39524. ResizableCornerComponent (Component* componentToResize,
  39525. ComponentBoundsConstrainer* constrainer);
  39526. /** Destructor. */
  39527. ~ResizableCornerComponent();
  39528. protected:
  39529. /** @internal */
  39530. void paint (Graphics& g);
  39531. /** @internal */
  39532. void mouseDown (const MouseEvent& e);
  39533. /** @internal */
  39534. void mouseDrag (const MouseEvent& e);
  39535. /** @internal */
  39536. void mouseUp (const MouseEvent& e);
  39537. /** @internal */
  39538. bool hitTest (int x, int y);
  39539. private:
  39540. WeakReference<Component> component;
  39541. ComponentBoundsConstrainer* constrainer;
  39542. Rectangle<int> originalBounds;
  39543. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  39544. };
  39545. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39546. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  39547. /**
  39548. A base class for top-level windows that can be dragged around and resized.
  39549. To add content to the window, use its setContentComponent() method to
  39550. give it a component that will remain positioned inside it (leaving a gap around
  39551. the edges for a border).
  39552. It's not advisable to add child components directly to a ResizableWindow: put them
  39553. inside your content component instead. And overriding methods like resized(), moved(), etc
  39554. is also not recommended - instead override these methods for your content component.
  39555. (If for some obscure reason you do need to override these methods, always remember to
  39556. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  39557. decorations correctly).
  39558. By default resizing isn't enabled - use the setResizable() method to enable it and
  39559. to choose the style of resizing to use.
  39560. @see TopLevelWindow
  39561. */
  39562. class JUCE_API ResizableWindow : public TopLevelWindow
  39563. {
  39564. public:
  39565. /** Creates a ResizableWindow.
  39566. This constructor doesn't specify a background colour, so the LookAndFeel's default
  39567. background colour will be used.
  39568. @param name the name to give the component
  39569. @param addToDesktop if true, the window will be automatically added to the
  39570. desktop; if false, you can use it as a child component
  39571. */
  39572. ResizableWindow (const String& name,
  39573. bool addToDesktop);
  39574. /** Creates a ResizableWindow.
  39575. @param name the name to give the component
  39576. @param backgroundColour the colour to use for filling the window's background.
  39577. @param addToDesktop if true, the window will be automatically added to the
  39578. desktop; if false, you can use it as a child component
  39579. */
  39580. ResizableWindow (const String& name,
  39581. const Colour& backgroundColour,
  39582. bool addToDesktop);
  39583. /** Destructor.
  39584. If a content component has been set with setContentComponent(), it
  39585. will be deleted.
  39586. */
  39587. ~ResizableWindow();
  39588. /** Returns the colour currently being used for the window's background.
  39589. As a convenience the window will fill itself with this colour, but you
  39590. can override the paint() method if you need more customised behaviour.
  39591. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  39592. @see setBackgroundColour
  39593. */
  39594. const Colour getBackgroundColour() const throw();
  39595. /** Changes the colour currently being used for the window's background.
  39596. As a convenience the window will fill itself with this colour, but you
  39597. can override the paint() method if you need more customised behaviour.
  39598. Note that the opaque state of this window is altered by this call to reflect
  39599. the opacity of the colour passed-in. On window systems which can't support
  39600. semi-transparent windows this might cause problems, (though it's unlikely you'll
  39601. be using this class as a base for a semi-transparent component anyway).
  39602. You can also use the ResizableWindow::backgroundColourId colour id to set
  39603. this colour.
  39604. @see getBackgroundColour
  39605. */
  39606. void setBackgroundColour (const Colour& newColour);
  39607. /** Make the window resizable or fixed.
  39608. @param shouldBeResizable whether it's resizable at all
  39609. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  39610. bottom-right; if false, it'll use a ResizableBorderComponent
  39611. around the edge
  39612. @see setResizeLimits, isResizable
  39613. */
  39614. void setResizable (bool shouldBeResizable,
  39615. bool useBottomRightCornerResizer);
  39616. /** True if resizing is enabled.
  39617. @see setResizable
  39618. */
  39619. bool isResizable() const throw();
  39620. /** This sets the maximum and minimum sizes for the window.
  39621. If the window's current size is outside these limits, it will be resized to
  39622. make sure it's within them.
  39623. Calling setBounds() on the component will bypass any size checking - it's only when
  39624. the window is being resized by the user that these values are enforced.
  39625. @see setResizable, setFixedAspectRatio
  39626. */
  39627. void setResizeLimits (int newMinimumWidth,
  39628. int newMinimumHeight,
  39629. int newMaximumWidth,
  39630. int newMaximumHeight) throw();
  39631. /** Returns the bounds constrainer object that this window is using.
  39632. You can access this to change its properties.
  39633. */
  39634. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  39635. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  39636. A pointer to the object you pass in will be kept, but it won't be deleted
  39637. by this object, so it's the caller's responsiblity to manage it.
  39638. If you pass 0, then no contraints will be placed on the positioning of the window.
  39639. */
  39640. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  39641. /** Calls the window's setBounds method, after first checking these bounds
  39642. with the current constrainer.
  39643. @see setConstrainer
  39644. */
  39645. void setBoundsConstrained (const Rectangle<int>& bounds);
  39646. /** Returns true if the window is currently in full-screen mode.
  39647. @see setFullScreen
  39648. */
  39649. bool isFullScreen() const;
  39650. /** Puts the window into full-screen mode, or restores it to its normal size.
  39651. If true, the window will become full-screen; if false, it will return to the
  39652. last size it was before being made full-screen.
  39653. @see isFullScreen
  39654. */
  39655. void setFullScreen (bool shouldBeFullScreen);
  39656. /** Returns true if the window is currently minimised.
  39657. @see setMinimised
  39658. */
  39659. bool isMinimised() const;
  39660. /** Minimises the window, or restores it to its previous position and size.
  39661. When being un-minimised, it'll return to the last position and size it
  39662. was in before being minimised.
  39663. @see isMinimised
  39664. */
  39665. void setMinimised (bool shouldMinimise);
  39666. /** Returns a string which encodes the window's current size and position.
  39667. This string will encapsulate the window's size, position, and whether it's
  39668. in full-screen mode. It's intended for letting your application save and
  39669. restore a window's position.
  39670. Use the restoreWindowStateFromString() to restore from a saved state.
  39671. @see restoreWindowStateFromString
  39672. */
  39673. const String getWindowStateAsString();
  39674. /** Restores the window to a previously-saved size and position.
  39675. This restores the window's size, positon and full-screen status from an
  39676. string that was previously created with the getWindowStateAsString()
  39677. method.
  39678. @returns false if the string wasn't a valid window state
  39679. @see getWindowStateAsString
  39680. */
  39681. bool restoreWindowStateFromString (const String& previousState);
  39682. /** Returns the current content component.
  39683. This will be the component set by setContentComponent(), or 0 if none
  39684. has yet been specified.
  39685. @see setContentComponent
  39686. */
  39687. Component* getContentComponent() const throw() { return contentComponent; }
  39688. /** Changes the current content component.
  39689. This sets a component that will be placed in the centre of the ResizableWindow,
  39690. (leaving a space around the edge for the border).
  39691. You should never add components directly to a ResizableWindow (or any of its subclasses)
  39692. with addChildComponent(). Instead, add them to the content component.
  39693. @param newContentComponent the new component to use (or null to not use one) - this
  39694. component will be deleted either when replaced by another call
  39695. to this method, or when the ResizableWindow is deleted.
  39696. To remove a content component without deleting it, use
  39697. setContentComponent (0, false).
  39698. @param deleteOldOne if true, the previous content component will be deleted; if
  39699. false, the previous component will just be removed without
  39700. deleting it.
  39701. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  39702. it always fits around the size of the content component. If false, the
  39703. new content will be resized to fit the current space available.
  39704. */
  39705. void setContentComponent (Component* newContentComponent,
  39706. bool deleteOldOne = true,
  39707. bool resizeToFit = false);
  39708. /** Changes the window so that the content component ends up with the specified size.
  39709. This is basically a setSize call on the window, but which adds on the borders,
  39710. so you can specify the content component's target size.
  39711. */
  39712. void setContentComponentSize (int width, int height);
  39713. /** Returns the width of the frame to use around the window.
  39714. @see getContentComponentBorder
  39715. */
  39716. virtual const BorderSize getBorderThickness();
  39717. /** Returns the insets to use when positioning the content component.
  39718. @see getBorderThickness
  39719. */
  39720. virtual const BorderSize getContentComponentBorder();
  39721. /** A set of colour IDs to use to change the colour of various aspects of the window.
  39722. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39723. methods.
  39724. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39725. */
  39726. enum ColourIds
  39727. {
  39728. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  39729. };
  39730. protected:
  39731. /** @internal */
  39732. void paint (Graphics& g);
  39733. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  39734. void moved();
  39735. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  39736. void resized();
  39737. /** @internal */
  39738. void mouseDown (const MouseEvent& e);
  39739. /** @internal */
  39740. void mouseDrag (const MouseEvent& e);
  39741. /** @internal */
  39742. void lookAndFeelChanged();
  39743. /** @internal */
  39744. void childBoundsChanged (Component* child);
  39745. /** @internal */
  39746. void parentSizeChanged();
  39747. /** @internal */
  39748. void visibilityChanged();
  39749. /** @internal */
  39750. void activeWindowStatusChanged();
  39751. /** @internal */
  39752. int getDesktopWindowStyleFlags() const;
  39753. #if JUCE_DEBUG
  39754. /** Overridden to warn people about adding components directly to this component
  39755. instead of using setContentComponent().
  39756. If you know what you're doing and are sure you really want to add a component, specify
  39757. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  39758. */
  39759. void addChildComponent (Component* child, int zOrder = -1);
  39760. /** Overridden to warn people about adding components directly to this component
  39761. instead of using setContentComponent().
  39762. If you know what you're doing and are sure you really want to add a component, specify
  39763. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  39764. */
  39765. void addAndMakeVisible (Component* child, int zOrder = -1);
  39766. #endif
  39767. ScopedPointer <ResizableCornerComponent> resizableCorner;
  39768. ScopedPointer <ResizableBorderComponent> resizableBorder;
  39769. private:
  39770. Component::SafePointer <Component> contentComponent;
  39771. bool resizeToFitContent, fullscreen;
  39772. ComponentDragger dragger;
  39773. Rectangle<int> lastNonFullScreenPos;
  39774. ComponentBoundsConstrainer defaultConstrainer;
  39775. ComponentBoundsConstrainer* constrainer;
  39776. #if JUCE_DEBUG
  39777. bool hasBeenResized;
  39778. #endif
  39779. void updateLastPos();
  39780. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  39781. // The parameters for these methods have changed - please update your code!
  39782. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  39783. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  39784. #endif
  39785. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  39786. };
  39787. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  39788. /*** End of inlined file: juce_ResizableWindow.h ***/
  39789. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  39790. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  39791. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  39792. /**
  39793. A glyph from a particular font, with a particular size, style,
  39794. typeface and position.
  39795. @see GlyphArrangement, Font
  39796. */
  39797. class JUCE_API PositionedGlyph
  39798. {
  39799. public:
  39800. PositionedGlyph (const PositionedGlyph& other);
  39801. /** Returns the character the glyph represents. */
  39802. juce_wchar getCharacter() const { return character; }
  39803. /** Checks whether the glyph is actually empty. */
  39804. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  39805. /** Returns the position of the glyph's left-hand edge. */
  39806. float getLeft() const { return x; }
  39807. /** Returns the position of the glyph's right-hand edge. */
  39808. float getRight() const { return x + w; }
  39809. /** Returns the y position of the glyph's baseline. */
  39810. float getBaselineY() const { return y; }
  39811. /** Returns the y position of the top of the glyph. */
  39812. float getTop() const { return y - font.getAscent(); }
  39813. /** Returns the y position of the bottom of the glyph. */
  39814. float getBottom() const { return y + font.getDescent(); }
  39815. /** Returns the bounds of the glyph. */
  39816. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  39817. /** Shifts the glyph's position by a relative amount. */
  39818. void moveBy (float deltaX, float deltaY);
  39819. /** Draws the glyph into a graphics context. */
  39820. void draw (const Graphics& g) const;
  39821. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  39822. void draw (const Graphics& g, const AffineTransform& transform) const;
  39823. /** Returns the path for this glyph.
  39824. @param path the glyph's outline will be appended to this path
  39825. */
  39826. void createPath (Path& path) const;
  39827. /** Checks to see if a point lies within this glyph. */
  39828. bool hitTest (float x, float y) const;
  39829. private:
  39830. friend class GlyphArrangement;
  39831. float x, y, w;
  39832. Font font;
  39833. juce_wchar character;
  39834. int glyph;
  39835. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  39836. JUCE_LEAK_DETECTOR (PositionedGlyph);
  39837. };
  39838. /**
  39839. A set of glyphs, each with a position.
  39840. You can create a GlyphArrangement, text to it and then draw it onto a
  39841. graphics context. It's used internally by the text methods in the
  39842. Graphics class, but can be used directly if more control is needed.
  39843. @see Font, PositionedGlyph
  39844. */
  39845. class JUCE_API GlyphArrangement
  39846. {
  39847. public:
  39848. /** Creates an empty arrangement. */
  39849. GlyphArrangement();
  39850. /** Takes a copy of another arrangement. */
  39851. GlyphArrangement (const GlyphArrangement& other);
  39852. /** Copies another arrangement onto this one.
  39853. To add another arrangement without clearing this one, use addGlyphArrangement().
  39854. */
  39855. GlyphArrangement& operator= (const GlyphArrangement& other);
  39856. /** Destructor. */
  39857. ~GlyphArrangement();
  39858. /** Returns the total number of glyphs in the arrangement. */
  39859. int getNumGlyphs() const throw() { return glyphs.size(); }
  39860. /** Returns one of the glyphs from the arrangement.
  39861. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  39862. careful not to pass an out-of-range index here, as it
  39863. doesn't do any bounds-checking.
  39864. */
  39865. PositionedGlyph& getGlyph (int index) const;
  39866. /** Clears all text from the arrangement and resets it.
  39867. */
  39868. void clear();
  39869. /** Appends a line of text to the arrangement.
  39870. This will add the text as a single line, where x is the left-hand edge of the
  39871. first character, and y is the position for the text's baseline.
  39872. If the text contains new-lines or carriage-returns, this will ignore them - use
  39873. addJustifiedText() to add multi-line arrangements.
  39874. */
  39875. void addLineOfText (const Font& font,
  39876. const String& text,
  39877. float x, float y);
  39878. /** Adds a line of text, truncating it if it's wider than a specified size.
  39879. This is the same as addLineOfText(), but if the line's width exceeds the value
  39880. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  39881. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  39882. */
  39883. void addCurtailedLineOfText (const Font& font,
  39884. const String& text,
  39885. float x, float y,
  39886. float maxWidthPixels,
  39887. bool useEllipsis);
  39888. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  39889. This will add text to the arrangement, breaking it into new lines either where there
  39890. is a new-line or carriage-return character in the text, or where a line's width
  39891. exceeds the value set in maxLineWidth.
  39892. Each line that is added will be laid out using the flags set in horizontalLayout, so
  39893. the lines can be left- or right-justified, or centred horizontally in the space
  39894. between x and (x + maxLineWidth).
  39895. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  39896. lines will be placed below it, separated by a distance of font.getHeight().
  39897. */
  39898. void addJustifiedText (const Font& font,
  39899. const String& text,
  39900. float x, float y,
  39901. float maxLineWidth,
  39902. const Justification& horizontalLayout);
  39903. /** Tries to fit some text withing a given space.
  39904. This does its best to make the given text readable within the specified rectangle,
  39905. so it useful for labelling things.
  39906. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  39907. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  39908. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  39909. it's been truncated.
  39910. A Justification parameter lets you specify how the text is laid out within the rectangle,
  39911. both horizontally and vertically.
  39912. @see Graphics::drawFittedText
  39913. */
  39914. void addFittedText (const Font& font,
  39915. const String& text,
  39916. float x, float y, float width, float height,
  39917. const Justification& layout,
  39918. int maximumLinesToUse,
  39919. float minimumHorizontalScale = 0.7f);
  39920. /** Appends another glyph arrangement to this one. */
  39921. void addGlyphArrangement (const GlyphArrangement& other);
  39922. /** Draws this glyph arrangement to a graphics context.
  39923. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  39924. method, which renders the glyphs as filled vectors.
  39925. */
  39926. void draw (const Graphics& g) const;
  39927. /** Draws this glyph arrangement to a graphics context.
  39928. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  39929. method for non-transformed arrangements.
  39930. */
  39931. void draw (const Graphics& g, const AffineTransform& transform) const;
  39932. /** Converts the set of glyphs into a path.
  39933. @param path the glyphs' outlines will be appended to this path
  39934. */
  39935. void createPath (Path& path) const;
  39936. /** Looks for a glyph that contains the given co-ordinate.
  39937. @returns the index of the glyph, or -1 if none were found.
  39938. */
  39939. int findGlyphIndexAt (float x, float y) const;
  39940. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  39941. @param startIndex the first glyph to test
  39942. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  39943. startIndex will be included
  39944. @param includeWhitespace if true, the extent of any whitespace characters will also
  39945. be taken into account
  39946. */
  39947. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  39948. /** Shifts a set of glyphs by a given amount.
  39949. @param startIndex the first glyph to transform
  39950. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  39951. startIndex will be used
  39952. @param deltaX the amount to add to their x-positions
  39953. @param deltaY the amount to add to their y-positions
  39954. */
  39955. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  39956. float deltaX, float deltaY);
  39957. /** Removes a set of glyphs from the arrangement.
  39958. @param startIndex the first glyph to remove
  39959. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  39960. startIndex will be deleted
  39961. */
  39962. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  39963. /** Expands or compresses a set of glyphs horizontally.
  39964. @param startIndex the first glyph to transform
  39965. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  39966. startIndex will be used
  39967. @param horizontalScaleFactor how much to scale their horizontal width by
  39968. */
  39969. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  39970. float horizontalScaleFactor);
  39971. /** Justifies a set of glyphs within a given space.
  39972. This moves the glyphs as a block so that the whole thing is located within the
  39973. given rectangle with the specified layout.
  39974. If the Justification::horizontallyJustified flag is specified, each line will
  39975. be stretched out to fill the specified width.
  39976. */
  39977. void justifyGlyphs (int startIndex, int numGlyphs,
  39978. float x, float y, float width, float height,
  39979. const Justification& justification);
  39980. private:
  39981. OwnedArray <PositionedGlyph> glyphs;
  39982. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  39983. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  39984. const Justification& justification, float minimumHorizontalScale);
  39985. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  39986. JUCE_LEAK_DETECTOR (GlyphArrangement);
  39987. };
  39988. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  39989. /*** End of inlined file: juce_GlyphArrangement.h ***/
  39990. /**
  39991. A file open/save dialog box.
  39992. This is a Juce-based file dialog box; to use a native file chooser, see the
  39993. FileChooser class.
  39994. To use one of these, create it and call its show() method. e.g.
  39995. @code
  39996. {
  39997. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  39998. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  39999. File::nonexistent,
  40000. &wildcardFilter,
  40001. 0);
  40002. FileChooserDialogBox dialogBox ("Open some kind of file",
  40003. "Please choose some kind of file that you want to open...",
  40004. browser,
  40005. getLookAndFeel().alertWindowBackground);
  40006. if (dialogBox.show())
  40007. {
  40008. File selectedFile = browser.getCurrentFile();
  40009. ...
  40010. }
  40011. }
  40012. @endcode
  40013. @see FileChooser
  40014. */
  40015. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  40016. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  40017. public FileBrowserListener
  40018. {
  40019. public:
  40020. /** Creates a file chooser box.
  40021. @param title the main title to show at the top of the box
  40022. @param instructions an optional longer piece of text to show below the title in
  40023. a smaller font, describing in more detail what's required.
  40024. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  40025. box. Make sure you delete this after (but not before!) the
  40026. dialog box has been deleted.
  40027. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  40028. if they try to select a file that already exists. (This
  40029. flag is only used when saving files)
  40030. @param backgroundColour the background colour for the top level window
  40031. @see FileBrowserComponent, FilePreviewComponent
  40032. */
  40033. FileChooserDialogBox (const String& title,
  40034. const String& instructions,
  40035. FileBrowserComponent& browserComponent,
  40036. bool warnAboutOverwritingExistingFiles,
  40037. const Colour& backgroundColour);
  40038. /** Destructor. */
  40039. ~FileChooserDialogBox();
  40040. /** Displays and runs the dialog box modally.
  40041. This will show the box with the specified size, returning true if the user
  40042. pressed 'ok', or false if they cancelled.
  40043. Leave the width or height as 0 to use the default size
  40044. */
  40045. bool show (int width = 0, int height = 0);
  40046. /** Displays and runs the dialog box modally.
  40047. This will show the box with the specified size at the specified location,
  40048. returning true if the user pressed 'ok', or false if they cancelled.
  40049. Leave the width or height as 0 to use the default size.
  40050. */
  40051. bool showAt (int x, int y, int width, int height);
  40052. /** A set of colour IDs to use to change the colour of various aspects of the box.
  40053. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40054. methods.
  40055. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40056. */
  40057. enum ColourIds
  40058. {
  40059. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  40060. };
  40061. /** @internal */
  40062. void buttonClicked (Button* button);
  40063. /** @internal */
  40064. void closeButtonPressed();
  40065. /** @internal */
  40066. void selectionChanged();
  40067. /** @internal */
  40068. void fileClicked (const File& file, const MouseEvent& e);
  40069. /** @internal */
  40070. void fileDoubleClicked (const File& file);
  40071. private:
  40072. class ContentComponent : public Component
  40073. {
  40074. public:
  40075. ContentComponent (const String& name, const String& instructions, FileBrowserComponent& chooserComponent);
  40076. void paint (Graphics& g);
  40077. void resized();
  40078. String instructions;
  40079. GlyphArrangement text;
  40080. FileBrowserComponent& chooserComponent;
  40081. TextButton okButton, cancelButton, newFolderButton;
  40082. };
  40083. ContentComponent* content;
  40084. const bool warnAboutOverwritingExistingFiles;
  40085. void okButtonPressed();
  40086. void createNewFolder();
  40087. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  40088. };
  40089. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  40090. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  40091. #endif
  40092. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  40093. #endif
  40094. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  40095. /*** Start of inlined file: juce_FileListComponent.h ***/
  40096. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  40097. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  40098. /**
  40099. A component that displays the files in a directory as a listbox.
  40100. This implements the DirectoryContentsDisplayComponent base class so that
  40101. it can be used in a FileBrowserComponent.
  40102. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  40103. class and the FileBrowserListener class.
  40104. @see DirectoryContentsList, FileTreeComponent
  40105. */
  40106. class JUCE_API FileListComponent : public ListBox,
  40107. public DirectoryContentsDisplayComponent,
  40108. private ListBoxModel,
  40109. private ChangeListener
  40110. {
  40111. public:
  40112. /** Creates a listbox to show the contents of a specified directory.
  40113. */
  40114. FileListComponent (DirectoryContentsList& listToShow);
  40115. /** Destructor. */
  40116. ~FileListComponent();
  40117. /** Returns the number of files the user has got selected.
  40118. @see getSelectedFile
  40119. */
  40120. int getNumSelectedFiles() const;
  40121. /** Returns one of the files that the user has currently selected.
  40122. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  40123. @see getNumSelectedFiles
  40124. */
  40125. const File getSelectedFile (int index = 0) const;
  40126. /** Deselects any files that are currently selected. */
  40127. void deselectAllFiles();
  40128. /** Scrolls to the top of the list. */
  40129. void scrollToTop();
  40130. /** @internal */
  40131. void changeListenerCallback (ChangeBroadcaster*);
  40132. /** @internal */
  40133. int getNumRows();
  40134. /** @internal */
  40135. void paintListBoxItem (int, Graphics&, int, int, bool);
  40136. /** @internal */
  40137. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  40138. /** @internal */
  40139. void selectedRowsChanged (int lastRowSelected);
  40140. /** @internal */
  40141. void deleteKeyPressed (int currentSelectedRow);
  40142. /** @internal */
  40143. void returnKeyPressed (int currentSelectedRow);
  40144. private:
  40145. File lastDirectory;
  40146. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  40147. };
  40148. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  40149. /*** End of inlined file: juce_FileListComponent.h ***/
  40150. #endif
  40151. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  40152. /*** Start of inlined file: juce_FilenameComponent.h ***/
  40153. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  40154. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  40155. class FilenameComponent;
  40156. /**
  40157. Listens for events happening to a FilenameComponent.
  40158. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  40159. register one of these objects for event callbacks when the filename is changed.
  40160. @see FilenameComponent
  40161. */
  40162. class JUCE_API FilenameComponentListener
  40163. {
  40164. public:
  40165. /** Destructor. */
  40166. virtual ~FilenameComponentListener() {}
  40167. /** This method is called after the FilenameComponent's file has been changed. */
  40168. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  40169. };
  40170. /**
  40171. Shows a filename as an editable text box, with a 'browse' button and a
  40172. drop-down list for recently selected files.
  40173. A handy component for dialogue boxes where you want the user to be able to
  40174. select a file or directory.
  40175. Attach an FilenameComponentListener using the addListener() method, and it will
  40176. get called each time the user changes the filename, either by browsing for a file
  40177. and clicking 'ok', or by typing a new filename into the box and pressing return.
  40178. @see FileChooser, ComboBox
  40179. */
  40180. class JUCE_API FilenameComponent : public Component,
  40181. public SettableTooltipClient,
  40182. public FileDragAndDropTarget,
  40183. private AsyncUpdater,
  40184. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  40185. private ComboBoxListener
  40186. {
  40187. public:
  40188. /** Creates a FilenameComponent.
  40189. @param name the name for this component.
  40190. @param currentFile the file to initially show in the box
  40191. @param canEditFilename if true, the user can manually edit the filename; if false,
  40192. they can only change it by browsing for a new file
  40193. @param isDirectory if true, the file will be treated as a directory, and
  40194. an appropriate directory browser used
  40195. @param isForSaving if true, the file browser will allow non-existent files to
  40196. be picked, as the file is assumed to be used for saving rather
  40197. than loading
  40198. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  40199. If an empty string is passed in, then the pattern is assumed to be "*"
  40200. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  40201. to any filenames that are entered or chosen
  40202. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  40203. will only appear if the initial file isn't valid)
  40204. */
  40205. FilenameComponent (const String& name,
  40206. const File& currentFile,
  40207. bool canEditFilename,
  40208. bool isDirectory,
  40209. bool isForSaving,
  40210. const String& fileBrowserWildcard,
  40211. const String& enforcedSuffix,
  40212. const String& textWhenNothingSelected);
  40213. /** Destructor. */
  40214. ~FilenameComponent();
  40215. /** Returns the currently displayed filename. */
  40216. const File getCurrentFile() const;
  40217. /** Changes the current filename.
  40218. If addToRecentlyUsedList is true, the filename will also be added to the
  40219. drop-down list of recent files.
  40220. If sendChangeNotification is false, then the listeners won't be told of the
  40221. change.
  40222. */
  40223. void setCurrentFile (File newFile,
  40224. bool addToRecentlyUsedList,
  40225. bool sendChangeNotification = true);
  40226. /** Changes whether the use can type into the filename box.
  40227. */
  40228. void setFilenameIsEditable (bool shouldBeEditable);
  40229. /** Sets a file or directory to be the default starting point for the browser to show.
  40230. This is only used if the current file hasn't been set.
  40231. */
  40232. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  40233. /** Returns all the entries on the recent files list.
  40234. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  40235. state of this list.
  40236. @see setRecentlyUsedFilenames
  40237. */
  40238. const StringArray getRecentlyUsedFilenames() const;
  40239. /** Sets all the entries on the recent files list.
  40240. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  40241. state of this list.
  40242. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  40243. */
  40244. void setRecentlyUsedFilenames (const StringArray& filenames);
  40245. /** Adds an entry to the recently-used files dropdown list.
  40246. If the file is already in the list, it will be moved to the top. A limit
  40247. is also placed on the number of items that are kept in the list.
  40248. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  40249. */
  40250. void addRecentlyUsedFile (const File& file);
  40251. /** Changes the limit for the number of files that will be stored in the recent-file list.
  40252. */
  40253. void setMaxNumberOfRecentFiles (int newMaximum);
  40254. /** Changes the text shown on the 'browse' button.
  40255. By default this button just says "..." but you can change it. The button itself
  40256. can be changed using the look-and-feel classes, so it might not actually have any
  40257. text on it.
  40258. */
  40259. void setBrowseButtonText (const String& browseButtonText);
  40260. /** Adds a listener that will be called when the selected file is changed. */
  40261. void addListener (FilenameComponentListener* listener);
  40262. /** Removes a previously-registered listener. */
  40263. void removeListener (FilenameComponentListener* listener);
  40264. /** Gives the component a tooltip. */
  40265. void setTooltip (const String& newTooltip);
  40266. /** @internal */
  40267. void paintOverChildren (Graphics& g);
  40268. /** @internal */
  40269. void resized();
  40270. /** @internal */
  40271. void lookAndFeelChanged();
  40272. /** @internal */
  40273. bool isInterestedInFileDrag (const StringArray& files);
  40274. /** @internal */
  40275. void filesDropped (const StringArray& files, int, int);
  40276. /** @internal */
  40277. void fileDragEnter (const StringArray& files, int, int);
  40278. /** @internal */
  40279. void fileDragExit (const StringArray& files);
  40280. private:
  40281. ComboBox filenameBox;
  40282. String lastFilename;
  40283. ScopedPointer<Button> browseButton;
  40284. int maxRecentFiles;
  40285. bool isDir, isSaving, isFileDragOver;
  40286. String wildcard, enforcedSuffix, browseButtonText;
  40287. ListenerList <FilenameComponentListener> listeners;
  40288. File defaultBrowseFile;
  40289. void comboBoxChanged (ComboBox*);
  40290. void buttonClicked (Button* button);
  40291. void handleAsyncUpdate();
  40292. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  40293. };
  40294. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  40295. /*** End of inlined file: juce_FilenameComponent.h ***/
  40296. #endif
  40297. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  40298. #endif
  40299. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  40300. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  40301. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  40302. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  40303. /**
  40304. Shows a set of file paths in a list, allowing them to be added, removed or
  40305. re-ordered.
  40306. @see FileSearchPath
  40307. */
  40308. class JUCE_API FileSearchPathListComponent : public Component,
  40309. public SettableTooltipClient,
  40310. public FileDragAndDropTarget,
  40311. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  40312. private ListBoxModel
  40313. {
  40314. public:
  40315. /** Creates an empty FileSearchPathListComponent. */
  40316. FileSearchPathListComponent();
  40317. /** Destructor. */
  40318. ~FileSearchPathListComponent();
  40319. /** Returns the path as it is currently shown. */
  40320. const FileSearchPath& getPath() const throw() { return path; }
  40321. /** Changes the current path. */
  40322. void setPath (const FileSearchPath& newPath);
  40323. /** Sets a file or directory to be the default starting point for the browser to show.
  40324. This is only used if the current file hasn't been set.
  40325. */
  40326. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  40327. /** A set of colour IDs to use to change the colour of various aspects of the label.
  40328. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40329. methods.
  40330. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40331. */
  40332. enum ColourIds
  40333. {
  40334. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  40335. Make this transparent if you don't want the background to be filled. */
  40336. };
  40337. /** @internal */
  40338. int getNumRows();
  40339. /** @internal */
  40340. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  40341. /** @internal */
  40342. void deleteKeyPressed (int lastRowSelected);
  40343. /** @internal */
  40344. void returnKeyPressed (int lastRowSelected);
  40345. /** @internal */
  40346. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  40347. /** @internal */
  40348. void selectedRowsChanged (int lastRowSelected);
  40349. /** @internal */
  40350. void resized();
  40351. /** @internal */
  40352. void paint (Graphics& g);
  40353. /** @internal */
  40354. bool isInterestedInFileDrag (const StringArray& files);
  40355. /** @internal */
  40356. void filesDropped (const StringArray& files, int, int);
  40357. /** @internal */
  40358. void buttonClicked (Button* button);
  40359. private:
  40360. FileSearchPath path;
  40361. File defaultBrowseTarget;
  40362. ListBox listBox;
  40363. TextButton addButton, removeButton, changeButton;
  40364. DrawableButton upButton, downButton;
  40365. void changed();
  40366. void updateButtons();
  40367. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  40368. };
  40369. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  40370. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  40371. #endif
  40372. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  40373. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  40374. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  40375. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  40376. /**
  40377. A component that displays the files in a directory as a treeview.
  40378. This implements the DirectoryContentsDisplayComponent base class so that
  40379. it can be used in a FileBrowserComponent.
  40380. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  40381. class and the FileBrowserListener class.
  40382. @see DirectoryContentsList, FileListComponent
  40383. */
  40384. class JUCE_API FileTreeComponent : public TreeView,
  40385. public DirectoryContentsDisplayComponent
  40386. {
  40387. public:
  40388. /** Creates a listbox to show the contents of a specified directory.
  40389. */
  40390. FileTreeComponent (DirectoryContentsList& listToShow);
  40391. /** Destructor. */
  40392. ~FileTreeComponent();
  40393. /** Returns the number of files the user has got selected.
  40394. @see getSelectedFile
  40395. */
  40396. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  40397. /** Returns one of the files that the user has currently selected.
  40398. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  40399. @see getNumSelectedFiles
  40400. */
  40401. const File getSelectedFile (int index = 0) const;
  40402. /** Deselects any files that are currently selected. */
  40403. void deselectAllFiles();
  40404. /** Scrolls the list to the top. */
  40405. void scrollToTop();
  40406. /** Setting a name for this allows tree items to be dragged.
  40407. The string that you pass in here will be returned by the getDragSourceDescription()
  40408. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  40409. */
  40410. void setDragAndDropDescription (const String& description);
  40411. /** Returns the last value that was set by setDragAndDropDescription().
  40412. */
  40413. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  40414. private:
  40415. String dragAndDropDescription;
  40416. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  40417. };
  40418. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  40419. /*** End of inlined file: juce_FileTreeComponent.h ***/
  40420. #endif
  40421. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  40422. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  40423. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  40424. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  40425. /**
  40426. A simple preview component that shows thumbnails of image files.
  40427. @see FileChooserDialogBox, FilePreviewComponent
  40428. */
  40429. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  40430. private Timer
  40431. {
  40432. public:
  40433. /** Creates an ImagePreviewComponent. */
  40434. ImagePreviewComponent();
  40435. /** Destructor. */
  40436. ~ImagePreviewComponent();
  40437. /** @internal */
  40438. void selectedFileChanged (const File& newSelectedFile);
  40439. /** @internal */
  40440. void paint (Graphics& g);
  40441. /** @internal */
  40442. void timerCallback();
  40443. private:
  40444. File fileToLoad;
  40445. Image currentThumbnail;
  40446. String currentDetails;
  40447. void getThumbSize (int& w, int& h) const;
  40448. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  40449. };
  40450. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  40451. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  40452. #endif
  40453. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  40454. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  40455. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  40456. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  40457. /**
  40458. A type of FileFilter that works by wildcard pattern matching.
  40459. This filter only allows files that match one of the specified patterns, but
  40460. allows all directories through.
  40461. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  40462. */
  40463. class JUCE_API WildcardFileFilter : public FileFilter
  40464. {
  40465. public:
  40466. /**
  40467. Creates a wildcard filter for one or more patterns.
  40468. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  40469. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  40470. or .aiff.
  40471. The description is a name to show the user in a list of possible patterns, so
  40472. for the wav/aiff example, your description might be "audio files".
  40473. */
  40474. WildcardFileFilter (const String& fileWildcardPatterns,
  40475. const String& directoryWildcardPatterns,
  40476. const String& description);
  40477. /** Destructor. */
  40478. ~WildcardFileFilter();
  40479. /** Returns true if the filename matches one of the patterns specified. */
  40480. bool isFileSuitable (const File& file) const;
  40481. /** This always returns true. */
  40482. bool isDirectorySuitable (const File& file) const;
  40483. private:
  40484. StringArray fileWildcards, directoryWildcards;
  40485. static void parse (const String& pattern, StringArray& result);
  40486. static bool match (const File& file, const StringArray& wildcards);
  40487. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  40488. };
  40489. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  40490. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  40491. #endif
  40492. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  40493. #endif
  40494. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  40495. #endif
  40496. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  40497. #endif
  40498. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  40499. #endif
  40500. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  40501. #endif
  40502. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  40503. #endif
  40504. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  40505. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  40506. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  40507. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  40508. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  40509. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  40510. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  40511. /**
  40512. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  40513. command in a ApplicationCommandManager.
  40514. Normally, you won't actually create a KeyPressMappingSet directly, because
  40515. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  40516. you'd create yourself an ApplicationCommandManager, and call its
  40517. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  40518. KeyPressMappingSet.
  40519. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  40520. to the top-level component for which you want to handle keystrokes. So for example:
  40521. @code
  40522. class MyMainWindow : public Component
  40523. {
  40524. ApplicationCommandManager* myCommandManager;
  40525. public:
  40526. MyMainWindow()
  40527. {
  40528. myCommandManager = new ApplicationCommandManager();
  40529. // first, make sure the command manager has registered all the commands that its
  40530. // targets can perform..
  40531. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  40532. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  40533. // this will use the command manager to initialise the KeyPressMappingSet with
  40534. // the default keypresses that were specified when the targets added their commands
  40535. // to the manager.
  40536. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  40537. // having set up the default key-mappings, you might now want to load the last set
  40538. // of mappings that the user configured.
  40539. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  40540. // Now tell our top-level window to send any keypresses that arrive to the
  40541. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  40542. addKeyListener (myCommandManager->getKeyMappings());
  40543. }
  40544. ...
  40545. }
  40546. @endcode
  40547. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  40548. register to be told when a command or mapping is added, removed, etc.
  40549. There's also a UI component called KeyMappingEditorComponent that can be used
  40550. to easily edit the key mappings.
  40551. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  40552. */
  40553. class JUCE_API KeyPressMappingSet : public KeyListener,
  40554. public ChangeBroadcaster,
  40555. public FocusChangeListener
  40556. {
  40557. public:
  40558. /** Creates a KeyPressMappingSet for a given command manager.
  40559. Normally, you won't actually create a KeyPressMappingSet directly, because
  40560. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  40561. best thing to do is to create your ApplicationCommandManager, and use the
  40562. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  40563. When a suitable keypress happens, the manager's invoke() method will be
  40564. used to invoke the appropriate command.
  40565. @see ApplicationCommandManager
  40566. */
  40567. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  40568. /** Creates an copy of a KeyPressMappingSet. */
  40569. KeyPressMappingSet (const KeyPressMappingSet& other);
  40570. /** Destructor. */
  40571. ~KeyPressMappingSet();
  40572. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  40573. /** Returns a list of keypresses that are assigned to a particular command.
  40574. @param commandID the command's ID
  40575. */
  40576. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  40577. /** Assigns a keypress to a command.
  40578. If the keypress is already assigned to a different command, it will first be
  40579. removed from that command, to avoid it triggering multiple functions.
  40580. @param commandID the ID of the command that you want to add a keypress to. If
  40581. this is 0, the keypress will be removed from anything that it
  40582. was previously assigned to, but not re-assigned
  40583. @param newKeyPress the new key-press
  40584. @param insertIndex if this is less than zero, the key will be appended to the
  40585. end of the list of keypresses; otherwise the new keypress will
  40586. be inserted into the existing list at this index
  40587. */
  40588. void addKeyPress (CommandID commandID,
  40589. const KeyPress& newKeyPress,
  40590. int insertIndex = -1);
  40591. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  40592. @see resetToDefaultMapping
  40593. */
  40594. void resetToDefaultMappings();
  40595. /** Resets all key-mappings to the defaults for a particular command.
  40596. @see resetToDefaultMappings
  40597. */
  40598. void resetToDefaultMapping (CommandID commandID);
  40599. /** Removes all keypresses that are assigned to any commands. */
  40600. void clearAllKeyPresses();
  40601. /** Removes all keypresses that are assigned to a particular command. */
  40602. void clearAllKeyPresses (CommandID commandID);
  40603. /** Removes one of the keypresses that are assigned to a command.
  40604. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  40605. which the keyPressIndex refers.
  40606. */
  40607. void removeKeyPress (CommandID commandID, int keyPressIndex);
  40608. /** Removes a keypress from any command that it may be assigned to.
  40609. */
  40610. void removeKeyPress (const KeyPress& keypress);
  40611. /** Returns true if the given command is linked to this key. */
  40612. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  40613. /** Looks for a command that corresponds to a keypress.
  40614. @returns the UID of the command or 0 if none was found
  40615. */
  40616. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  40617. /** Tries to recreate the mappings from a previously stored state.
  40618. The XML passed in must have been created by the createXml() method.
  40619. If the stored state makes any reference to commands that aren't
  40620. currently available, these will be ignored.
  40621. If the set of mappings being loaded was a set of differences (using createXml (true)),
  40622. then this will call resetToDefaultMappings() and then merge the saved mappings
  40623. on top. If the saved set was created with createXml (false), then this method
  40624. will first clear all existing mappings and load the saved ones as a complete set.
  40625. @returns true if it manages to load the XML correctly
  40626. @see createXml
  40627. */
  40628. bool restoreFromXml (const XmlElement& xmlVersion);
  40629. /** Creates an XML representation of the current mappings.
  40630. This will produce a lump of XML that can be later reloaded using
  40631. restoreFromXml() to recreate the current mapping state.
  40632. The object that is returned must be deleted by the caller.
  40633. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  40634. will be saved into the XML. If it's true, then the XML will
  40635. only store the differences between the current mappings and
  40636. the default mappings you'd get from calling resetToDefaultMappings().
  40637. The advantage of saving a set of differences from the default is that
  40638. if you change the default mappings (in a new version of your app, for
  40639. example), then these will be merged into a user's saved preferences.
  40640. @see restoreFromXml
  40641. */
  40642. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  40643. /** @internal */
  40644. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  40645. /** @internal */
  40646. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  40647. /** @internal */
  40648. void globalFocusChanged (Component* focusedComponent);
  40649. private:
  40650. ApplicationCommandManager* commandManager;
  40651. struct CommandMapping
  40652. {
  40653. CommandID commandID;
  40654. Array <KeyPress> keypresses;
  40655. bool wantsKeyUpDownCallbacks;
  40656. };
  40657. OwnedArray <CommandMapping> mappings;
  40658. struct KeyPressTime
  40659. {
  40660. KeyPress key;
  40661. uint32 timeWhenPressed;
  40662. };
  40663. OwnedArray <KeyPressTime> keysDown;
  40664. void handleMessage (const Message& message);
  40665. void invokeCommand (const CommandID commandID,
  40666. const KeyPress& keyPress,
  40667. const bool isKeyDown,
  40668. const int millisecsSinceKeyPressed,
  40669. Component* const originatingComponent) const;
  40670. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  40671. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  40672. };
  40673. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  40674. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  40675. /**
  40676. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  40677. object.
  40678. @see KeyPressMappingSet
  40679. */
  40680. class JUCE_API KeyMappingEditorComponent : public Component
  40681. {
  40682. public:
  40683. /** Creates a KeyMappingEditorComponent.
  40684. @param mappingSet this is the set of mappings to display and edit. Make sure the
  40685. mappings object is not deleted before this component!
  40686. @param showResetToDefaultButton if true, then at the bottom of the list, the
  40687. component will include a 'reset to defaults' button.
  40688. */
  40689. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  40690. bool showResetToDefaultButton);
  40691. /** Destructor. */
  40692. virtual ~KeyMappingEditorComponent();
  40693. /** Sets up the colours to use for parts of the component.
  40694. @param mainBackground colour to use for most of the background
  40695. @param textColour colour to use for the text
  40696. */
  40697. void setColours (const Colour& mainBackground,
  40698. const Colour& textColour);
  40699. /** Returns the KeyPressMappingSet that this component is acting upon. */
  40700. KeyPressMappingSet& getMappings() const throw() { return mappings; }
  40701. /** Can be overridden if some commands need to be excluded from the list.
  40702. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  40703. method to decide what to return, but you can override it to handle special cases.
  40704. */
  40705. virtual bool shouldCommandBeIncluded (CommandID commandID);
  40706. /** Can be overridden to indicate that some commands are shown as read-only.
  40707. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  40708. method to decide what to return, but you can override it to handle special cases.
  40709. */
  40710. virtual bool isCommandReadOnly (CommandID commandID);
  40711. /** This can be overridden to let you change the format of the string used
  40712. to describe a keypress.
  40713. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  40714. keys that are triggered by something else externally. If you override the
  40715. method, be sure to let the base class's method handle keys you're not
  40716. interested in.
  40717. */
  40718. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  40719. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  40720. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40721. methods.
  40722. To change the colours of the menu that pops up
  40723. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40724. */
  40725. enum ColourIds
  40726. {
  40727. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  40728. textColourId = 0x100ad01, /**< The colour for the text. */
  40729. };
  40730. /** @internal */
  40731. void parentHierarchyChanged();
  40732. /** @internal */
  40733. void resized();
  40734. private:
  40735. KeyPressMappingSet& mappings;
  40736. TreeView tree;
  40737. TextButton resetButton;
  40738. class TopLevelItem;
  40739. class ChangeKeyButton;
  40740. class MappingItem;
  40741. class CategoryItem;
  40742. class ItemComponent;
  40743. friend class TopLevelItem;
  40744. friend class OwnedArray <ChangeKeyButton>;
  40745. friend class ScopedPointer<TopLevelItem>;
  40746. ScopedPointer<TopLevelItem> treeItem;
  40747. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  40748. };
  40749. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  40750. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  40751. #endif
  40752. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  40753. #endif
  40754. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  40755. #endif
  40756. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  40757. #endif
  40758. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  40759. #endif
  40760. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  40761. #endif
  40762. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  40763. #endif
  40764. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  40765. #endif
  40766. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  40767. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  40768. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  40769. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  40770. /** An object that watches for any movement of a component or any of its parent components.
  40771. This makes it easy to check when a component is moved relative to its top-level
  40772. peer window. The normal Component::moved() method is only called when a component
  40773. moves relative to its immediate parent, and sometimes you want to know if any of
  40774. components higher up the tree have moved (which of course will affect the overall
  40775. position of all their sub-components).
  40776. It also includes a callback that lets you know when the top-level peer is changed.
  40777. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  40778. because they need to keep their custom windows in the right place and respond to
  40779. changes in the peer.
  40780. */
  40781. class JUCE_API ComponentMovementWatcher : public ComponentListener
  40782. {
  40783. public:
  40784. /** Creates a ComponentMovementWatcher to watch a given target component. */
  40785. ComponentMovementWatcher (Component* component);
  40786. /** Destructor. */
  40787. ~ComponentMovementWatcher();
  40788. /** This callback happens when the component that is being watched is moved
  40789. relative to its top-level peer window, or when it is resized. */
  40790. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  40791. /** This callback happens when the component's top-level peer is changed. */
  40792. virtual void componentPeerChanged() = 0;
  40793. /** This callback happens when the component's visibility state changes, possibly due to
  40794. one of its parents being made visible or invisible.
  40795. */
  40796. virtual void componentVisibilityChanged() = 0;
  40797. /** @internal */
  40798. void componentParentHierarchyChanged (Component& component);
  40799. /** @internal */
  40800. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  40801. /** @internal */
  40802. void componentBeingDeleted (Component& component);
  40803. /** @internal */
  40804. void componentVisibilityChanged (Component& component);
  40805. private:
  40806. WeakReference<Component> component;
  40807. ComponentPeer* lastPeer;
  40808. Array <Component*> registeredParentComps;
  40809. bool reentrant, wasShowing;
  40810. Rectangle<int> lastBounds;
  40811. void unregister();
  40812. void registerWithParentComps();
  40813. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  40814. };
  40815. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  40816. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  40817. #endif
  40818. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  40819. /*** Start of inlined file: juce_GroupComponent.h ***/
  40820. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  40821. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  40822. /**
  40823. A component that draws an outline around itself and has an optional title at
  40824. the top, for drawing an outline around a group of controls.
  40825. */
  40826. class JUCE_API GroupComponent : public Component
  40827. {
  40828. public:
  40829. /** Creates a GroupComponent.
  40830. @param componentName the name to give the component
  40831. @param labelText the text to show at the top of the outline
  40832. */
  40833. GroupComponent (const String& componentName = String::empty,
  40834. const String& labelText = String::empty);
  40835. /** Destructor. */
  40836. ~GroupComponent();
  40837. /** Changes the text that's shown at the top of the component. */
  40838. void setText (const String& newText);
  40839. /** Returns the currently displayed text label. */
  40840. const String getText() const;
  40841. /** Sets the positioning of the text label.
  40842. (The default is Justification::left)
  40843. @see getTextLabelPosition
  40844. */
  40845. void setTextLabelPosition (const Justification& justification);
  40846. /** Returns the current text label position.
  40847. @see setTextLabelPosition
  40848. */
  40849. const Justification getTextLabelPosition() const throw() { return justification; }
  40850. /** A set of colour IDs to use to change the colour of various aspects of the component.
  40851. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40852. methods.
  40853. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40854. */
  40855. enum ColourIds
  40856. {
  40857. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  40858. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  40859. };
  40860. /** @internal */
  40861. void paint (Graphics& g);
  40862. /** @internal */
  40863. void enablementChanged();
  40864. /** @internal */
  40865. void colourChanged();
  40866. private:
  40867. String text;
  40868. Justification justification;
  40869. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  40870. };
  40871. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  40872. /*** End of inlined file: juce_GroupComponent.h ***/
  40873. #endif
  40874. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  40875. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  40876. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  40877. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  40878. /*** Start of inlined file: juce_TabbedComponent.h ***/
  40879. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  40880. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  40881. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  40882. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  40883. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  40884. class TabbedButtonBar;
  40885. /** In a TabbedButtonBar, this component is used for each of the buttons.
  40886. If you want to create a TabbedButtonBar with custom tab components, derive
  40887. your component from this class, and override the TabbedButtonBar::createTabButton()
  40888. method to create it instead of the default one.
  40889. @see TabbedButtonBar
  40890. */
  40891. class JUCE_API TabBarButton : public Button
  40892. {
  40893. public:
  40894. /** Creates the tab button. */
  40895. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  40896. /** Destructor. */
  40897. ~TabBarButton();
  40898. /** Chooses the best length for the tab, given the specified depth.
  40899. If the tab is horizontal, this should return its width, and the depth
  40900. specifies its height. If it's vertical, it should return the height, and
  40901. the depth is actually its width.
  40902. */
  40903. virtual int getBestTabLength (int depth);
  40904. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  40905. void clicked (const ModifierKeys& mods);
  40906. bool hitTest (int x, int y);
  40907. protected:
  40908. friend class TabbedButtonBar;
  40909. TabbedButtonBar& owner;
  40910. int overlapPixels;
  40911. DropShadowEffect shadow;
  40912. /** Returns an area of the component that's safe to draw in.
  40913. This deals with the orientation of the tabs, which affects which side is
  40914. touching the tabbed box's content component.
  40915. */
  40916. const Rectangle<int> getActiveArea();
  40917. /** Returns this tab's index in its tab bar. */
  40918. int getIndex() const;
  40919. private:
  40920. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  40921. };
  40922. /**
  40923. A vertical or horizontal bar containing tabs that you can select.
  40924. You can use one of these to generate things like a dialog box that has
  40925. tabbed pages you can flip between. Attach a ChangeListener to the
  40926. button bar to be told when the user changes the page.
  40927. An easier method than doing this is to use a TabbedComponent, which
  40928. contains its own TabbedButtonBar and which takes care of the layout
  40929. and other housekeeping.
  40930. @see TabbedComponent
  40931. */
  40932. class JUCE_API TabbedButtonBar : public Component,
  40933. public ChangeBroadcaster
  40934. {
  40935. public:
  40936. /** The placement of the tab-bar
  40937. @see setOrientation, getOrientation
  40938. */
  40939. enum Orientation
  40940. {
  40941. TabsAtTop,
  40942. TabsAtBottom,
  40943. TabsAtLeft,
  40944. TabsAtRight
  40945. };
  40946. /** Creates a TabbedButtonBar with a given placement.
  40947. You can change the orientation later if you need to.
  40948. */
  40949. TabbedButtonBar (Orientation orientation);
  40950. /** Destructor. */
  40951. ~TabbedButtonBar();
  40952. /** Changes the bar's orientation.
  40953. This won't change the bar's actual size - you'll need to do that yourself,
  40954. but this determines which direction the tabs go in, and which side they're
  40955. stuck to.
  40956. */
  40957. void setOrientation (Orientation orientation);
  40958. /** Returns the current orientation.
  40959. @see setOrientation
  40960. */
  40961. Orientation getOrientation() const throw() { return orientation; }
  40962. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  40963. fit a lot of tabs on-screen.
  40964. */
  40965. void setMinimumTabScaleFactor (double newMinimumScale);
  40966. /** Deletes all the tabs from the bar.
  40967. @see addTab
  40968. */
  40969. void clearTabs();
  40970. /** Adds a tab to the bar.
  40971. Tabs are added in left-to-right reading order.
  40972. If this is the first tab added, it'll also be automatically selected.
  40973. */
  40974. void addTab (const String& tabName,
  40975. const Colour& tabBackgroundColour,
  40976. int insertIndex = -1);
  40977. /** Changes the name of one of the tabs. */
  40978. void setTabName (int tabIndex,
  40979. const String& newName);
  40980. /** Gets rid of one of the tabs. */
  40981. void removeTab (int tabIndex);
  40982. /** Moves a tab to a new index in the list.
  40983. Pass -1 as the index to move it to the end of the list.
  40984. */
  40985. void moveTab (int currentIndex, int newIndex);
  40986. /** Returns the number of tabs in the bar. */
  40987. int getNumTabs() const;
  40988. /** Returns a list of all the tab names in the bar. */
  40989. const StringArray getTabNames() const;
  40990. /** Changes the currently selected tab.
  40991. This will send a change message and cause a synchronous callback to
  40992. the currentTabChanged() method. (But if the given tab is already selected,
  40993. nothing will be done).
  40994. To deselect all the tabs, use an index of -1.
  40995. */
  40996. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  40997. /** Returns the name of the currently selected tab.
  40998. This could be an empty string if none are selected.
  40999. */
  41000. const String getCurrentTabName() const;
  41001. /** Returns the index of the currently selected tab.
  41002. This could return -1 if none are selected.
  41003. */
  41004. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  41005. /** Returns the button for a specific tab.
  41006. The button that is returned may be deleted later by this component, so don't hang
  41007. on to the pointer that is returned. A null pointer may be returned if the index is
  41008. out of range.
  41009. */
  41010. TabBarButton* getTabButton (int index) const;
  41011. /** Returns the index of a TabBarButton if it belongs to this bar. */
  41012. int indexOfTabButton (const TabBarButton* button) const;
  41013. /** Callback method to indicate the selected tab has been changed.
  41014. @see setCurrentTabIndex
  41015. */
  41016. virtual void currentTabChanged (int newCurrentTabIndex,
  41017. const String& newCurrentTabName);
  41018. /** Callback method to indicate that the user has right-clicked on a tab.
  41019. (Or ctrl-clicked on the Mac)
  41020. */
  41021. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  41022. /** Returns the colour of a tab.
  41023. This is the colour that was specified in addTab().
  41024. */
  41025. const Colour getTabBackgroundColour (int tabIndex);
  41026. /** Changes the background colour of a tab.
  41027. @see addTab, getTabBackgroundColour
  41028. */
  41029. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  41030. /** A set of colour IDs to use to change the colour of various aspects of the component.
  41031. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41032. methods.
  41033. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41034. */
  41035. enum ColourIds
  41036. {
  41037. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  41038. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  41039. the look and feel will choose an appropriate colour. */
  41040. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  41041. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  41042. this isn't specified, the look and feel will choose an appropriate
  41043. colour. */
  41044. };
  41045. /** @internal */
  41046. void resized();
  41047. /** @internal */
  41048. void lookAndFeelChanged();
  41049. protected:
  41050. /** This creates one of the tabs.
  41051. If you need to use custom tab components, you can override this method and
  41052. return your own class instead of the default.
  41053. */
  41054. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  41055. private:
  41056. Orientation orientation;
  41057. struct TabInfo
  41058. {
  41059. ScopedPointer<TabBarButton> component;
  41060. String name;
  41061. Colour colour;
  41062. };
  41063. OwnedArray <TabInfo> tabs;
  41064. double minimumScale;
  41065. int currentTabIndex;
  41066. class BehindFrontTabComp;
  41067. friend class BehindFrontTabComp;
  41068. friend class ScopedPointer<BehindFrontTabComp>;
  41069. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  41070. ScopedPointer<Button> extraTabsButton;
  41071. void showExtraItemsMenu();
  41072. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  41073. };
  41074. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  41075. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  41076. /**
  41077. A component with a TabbedButtonBar along one of its sides.
  41078. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  41079. with addTab(), and this will take care of showing the pages for you when the
  41080. user clicks on a different tab.
  41081. @see TabbedButtonBar
  41082. */
  41083. class JUCE_API TabbedComponent : public Component
  41084. {
  41085. public:
  41086. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  41087. Once created, add some tabs with the addTab() method.
  41088. */
  41089. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  41090. /** Destructor. */
  41091. ~TabbedComponent();
  41092. /** Changes the placement of the tabs.
  41093. This will rearrange the layout to place the tabs along the appropriate
  41094. side of this component, and will shift the content component accordingly.
  41095. @see TabbedButtonBar::setOrientation
  41096. */
  41097. void setOrientation (TabbedButtonBar::Orientation orientation);
  41098. /** Returns the current tab placement.
  41099. @see setOrientation, TabbedButtonBar::getOrientation
  41100. */
  41101. TabbedButtonBar::Orientation getOrientation() const throw();
  41102. /** Specifies how many pixels wide or high the tab-bar should be.
  41103. If the tabs are placed along the top or bottom, this specified the height
  41104. of the bar; if they're along the left or right edges, it'll be the width
  41105. of the bar.
  41106. */
  41107. void setTabBarDepth (int newDepth);
  41108. /** Returns the current thickness of the tab bar.
  41109. @see setTabBarDepth
  41110. */
  41111. int getTabBarDepth() const throw() { return tabDepth; }
  41112. /** Specifies the thickness of an outline that should be drawn around the content component.
  41113. If this thickness is > 0, a line will be drawn around the three sides of the content
  41114. component which don't touch the tab-bar, and the content component will be inset by this amount.
  41115. To set the colour of the line, use setColour (outlineColourId, ...).
  41116. */
  41117. void setOutline (int newThickness);
  41118. /** Specifies a gap to leave around the edge of the content component.
  41119. Each edge of the content component will be indented by the given number of pixels.
  41120. */
  41121. void setIndent (int indentThickness);
  41122. /** Removes all the tabs from the bar.
  41123. @see TabbedButtonBar::clearTabs
  41124. */
  41125. void clearTabs();
  41126. /** Adds a tab to the tab-bar.
  41127. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  41128. is true, it will be deleted when the tab is removed or when this object is
  41129. deleted.
  41130. @see TabbedButtonBar::addTab
  41131. */
  41132. void addTab (const String& tabName,
  41133. const Colour& tabBackgroundColour,
  41134. Component* contentComponent,
  41135. bool deleteComponentWhenNotNeeded,
  41136. int insertIndex = -1);
  41137. /** Changes the name of one of the tabs. */
  41138. void setTabName (int tabIndex, const String& newName);
  41139. /** Gets rid of one of the tabs. */
  41140. void removeTab (int tabIndex);
  41141. /** Returns the number of tabs in the bar. */
  41142. int getNumTabs() const;
  41143. /** Returns a list of all the tab names in the bar. */
  41144. const StringArray getTabNames() const;
  41145. /** Returns the content component that was added for the given index.
  41146. Be sure not to use or delete the components that are returned, as this may interfere
  41147. with the TabbedComponent's use of them.
  41148. */
  41149. Component* getTabContentComponent (int tabIndex) const throw();
  41150. /** Returns the colour of one of the tabs. */
  41151. const Colour getTabBackgroundColour (int tabIndex) const throw();
  41152. /** Changes the background colour of one of the tabs. */
  41153. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  41154. /** Changes the currently-selected tab.
  41155. To deselect all the tabs, pass -1 as the index.
  41156. @see TabbedButtonBar::setCurrentTabIndex
  41157. */
  41158. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  41159. /** Returns the index of the currently selected tab.
  41160. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  41161. */
  41162. int getCurrentTabIndex() const;
  41163. /** Returns the name of the currently selected tab.
  41164. @see addTab, TabbedButtonBar::getCurrentTabName()
  41165. */
  41166. const String getCurrentTabName() const;
  41167. /** Returns the current component that's filling the panel.
  41168. This will return 0 if there isn't one.
  41169. */
  41170. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  41171. /** Callback method to indicate the selected tab has been changed.
  41172. @see setCurrentTabIndex
  41173. */
  41174. virtual void currentTabChanged (int newCurrentTabIndex,
  41175. const String& newCurrentTabName);
  41176. /** Callback method to indicate that the user has right-clicked on a tab.
  41177. (Or ctrl-clicked on the Mac)
  41178. */
  41179. virtual void popupMenuClickOnTab (int tabIndex,
  41180. const String& tabName);
  41181. /** Returns the tab button bar component that is being used.
  41182. */
  41183. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  41184. /** A set of colour IDs to use to change the colour of various aspects of the component.
  41185. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41186. methods.
  41187. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41188. */
  41189. enum ColourIds
  41190. {
  41191. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  41192. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  41193. (See setOutline) */
  41194. };
  41195. /** @internal */
  41196. void paint (Graphics& g);
  41197. /** @internal */
  41198. void resized();
  41199. /** @internal */
  41200. void lookAndFeelChanged();
  41201. protected:
  41202. /** This creates one of the tab buttons.
  41203. If you need to use custom tab components, you can override this method and
  41204. return your own class instead of the default.
  41205. */
  41206. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  41207. /** @internal */
  41208. ScopedPointer<TabbedButtonBar> tabs;
  41209. private:
  41210. Array <WeakReference<Component> > contentComponents;
  41211. WeakReference<Component> panelComponent;
  41212. int tabDepth;
  41213. int outlineThickness, edgeIndent;
  41214. class ButtonBar;
  41215. friend class ButtonBar;
  41216. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  41217. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  41218. };
  41219. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  41220. /*** End of inlined file: juce_TabbedComponent.h ***/
  41221. /*** Start of inlined file: juce_DocumentWindow.h ***/
  41222. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  41223. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  41224. /*** Start of inlined file: juce_MenuBarModel.h ***/
  41225. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  41226. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  41227. /**
  41228. A class for controlling MenuBar components.
  41229. This class is used to tell a MenuBar what menus to show, and to respond
  41230. to a menu being selected.
  41231. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  41232. */
  41233. class JUCE_API MenuBarModel : private AsyncUpdater,
  41234. private ApplicationCommandManagerListener
  41235. {
  41236. public:
  41237. MenuBarModel() throw();
  41238. /** Destructor. */
  41239. virtual ~MenuBarModel();
  41240. /** Call this when some of your menu items have changed.
  41241. This method will cause a callback to any MenuBarListener objects that
  41242. are registered with this model.
  41243. If this model is displaying items from an ApplicationCommandManager, you
  41244. can use the setApplicationCommandManagerToWatch() method to cause
  41245. change messages to be sent automatically when the ApplicationCommandManager
  41246. is changed.
  41247. @see addListener, removeListener, MenuBarListener
  41248. */
  41249. void menuItemsChanged();
  41250. /** Tells the menu bar to listen to the specified command manager, and to update
  41251. itself when the commands change.
  41252. This will also allow it to flash a menu name when a command from that menu
  41253. is invoked using a keystroke.
  41254. */
  41255. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  41256. /** A class to receive callbacks when a MenuBarModel changes.
  41257. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  41258. */
  41259. class JUCE_API Listener
  41260. {
  41261. public:
  41262. /** Destructor. */
  41263. virtual ~Listener() {}
  41264. /** This callback is made when items are changed in the menu bar model.
  41265. */
  41266. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  41267. /** This callback is made when an application command is invoked that
  41268. is represented by one of the items in the menu bar model.
  41269. */
  41270. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  41271. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  41272. };
  41273. /** Registers a listener for callbacks when the menu items in this model change.
  41274. The listener object will get callbacks when this object's menuItemsChanged()
  41275. method is called.
  41276. @see removeListener
  41277. */
  41278. void addListener (Listener* listenerToAdd) throw();
  41279. /** Removes a listener.
  41280. @see addListener
  41281. */
  41282. void removeListener (Listener* listenerToRemove) throw();
  41283. /** This method must return a list of the names of the menus. */
  41284. virtual const StringArray getMenuBarNames() = 0;
  41285. /** This should return the popup menu to display for a given top-level menu.
  41286. @param topLevelMenuIndex the index of the top-level menu to show
  41287. @param menuName the name of the top-level menu item to show
  41288. */
  41289. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  41290. const String& menuName) = 0;
  41291. /** This is called when a menu item has been clicked on.
  41292. @param menuItemID the item ID of the PopupMenu item that was selected
  41293. @param topLevelMenuIndex the index of the top-level menu from which the item was
  41294. chosen (just in case you've used duplicate ID numbers
  41295. on more than one of the popup menus)
  41296. */
  41297. virtual void menuItemSelected (int menuItemID,
  41298. int topLevelMenuIndex) = 0;
  41299. #if JUCE_MAC || DOXYGEN
  41300. /** MAC ONLY - Sets the model that is currently being shown as the main
  41301. menu bar at the top of the screen on the Mac.
  41302. You can pass 0 to stop the current model being displayed. Be careful
  41303. not to delete a model while it is being used.
  41304. An optional extra menu can be specified, containing items to add to the top of
  41305. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  41306. an apple, it's the one next to it, with your application's name at the top
  41307. and the services menu etc on it). When one of these items is selected, the
  41308. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  41309. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  41310. object then newMenuBarModel must be non-null.
  41311. */
  41312. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  41313. const PopupMenu* extraAppleMenuItems = 0);
  41314. /** MAC ONLY - Returns the menu model that is currently being shown as
  41315. the main menu bar.
  41316. */
  41317. static MenuBarModel* getMacMainMenu();
  41318. #endif
  41319. /** @internal */
  41320. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  41321. /** @internal */
  41322. void applicationCommandListChanged();
  41323. /** @internal */
  41324. void handleAsyncUpdate();
  41325. private:
  41326. ApplicationCommandManager* manager;
  41327. ListenerList <Listener> listeners;
  41328. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  41329. };
  41330. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  41331. typedef MenuBarModel::Listener MenuBarModelListener;
  41332. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  41333. /*** End of inlined file: juce_MenuBarModel.h ***/
  41334. /**
  41335. A resizable window with a title bar and maximise, minimise and close buttons.
  41336. This subclass of ResizableWindow creates a fairly standard type of window with
  41337. a title bar and various buttons. The name of the component is shown in the
  41338. title bar, and an icon can optionally be specified with setIcon().
  41339. All the methods available to a ResizableWindow are also available to this,
  41340. so it can easily be made resizable, minimised, maximised, etc.
  41341. It's not advisable to add child components directly to a DocumentWindow: put them
  41342. inside your content component instead. And overriding methods like resized(), moved(), etc
  41343. is also not recommended - instead override these methods for your content component.
  41344. (If for some obscure reason you do need to override these methods, always remember to
  41345. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  41346. decorations correctly).
  41347. You can also automatically add a menu bar to the window, using the setMenuBar()
  41348. method.
  41349. @see ResizableWindow, DialogWindow
  41350. */
  41351. class JUCE_API DocumentWindow : public ResizableWindow
  41352. {
  41353. public:
  41354. /** The set of available button-types that can be put on the title bar.
  41355. @see setTitleBarButtonsRequired
  41356. */
  41357. enum TitleBarButtons
  41358. {
  41359. minimiseButton = 1,
  41360. maximiseButton = 2,
  41361. closeButton = 4,
  41362. /** A combination of all the buttons above. */
  41363. allButtons = 7
  41364. };
  41365. /** Creates a DocumentWindow.
  41366. @param name the name to give the component - this is also
  41367. the title shown at the top of the window. To change
  41368. this later, use setName()
  41369. @param backgroundColour the colour to use for filling the window's background.
  41370. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  41371. should be shown on the title bar. This value is a bitwise
  41372. combination of values from the TitleBarButtons enum. Note
  41373. that it can be "allButtons" to get them all. You
  41374. can change this later with the setTitleBarButtonsRequired()
  41375. method, which can also specify where they are positioned.
  41376. @param addToDesktop if true, the window will be automatically added to the
  41377. desktop; if false, you can use it as a child component
  41378. @see TitleBarButtons
  41379. */
  41380. DocumentWindow (const String& name,
  41381. const Colour& backgroundColour,
  41382. int requiredButtons,
  41383. bool addToDesktop = true);
  41384. /** Destructor.
  41385. If a content component has been set with setContentComponent(), it
  41386. will be deleted.
  41387. */
  41388. ~DocumentWindow();
  41389. /** Changes the component's name.
  41390. (This is overridden from Component::setName() to cause a repaint, as
  41391. the name is what gets drawn across the window's title bar).
  41392. */
  41393. void setName (const String& newName);
  41394. /** Sets an icon to show in the title bar, next to the title.
  41395. A copy is made internally of the image, so the caller can delete the
  41396. image after calling this. If 0 is passed-in, any existing icon will be
  41397. removed.
  41398. */
  41399. void setIcon (const Image& imageToUse);
  41400. /** Changes the height of the title-bar. */
  41401. void setTitleBarHeight (int newHeight);
  41402. /** Returns the current title bar height. */
  41403. int getTitleBarHeight() const;
  41404. /** Changes the set of title-bar buttons being shown.
  41405. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  41406. should be shown on the title bar. This value is a bitwise
  41407. combination of values from the TitleBarButtons enum. Note
  41408. that it can be "allButtons" to get them all.
  41409. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  41410. left side of the bar; if false, they'll be placed at the right
  41411. */
  41412. void setTitleBarButtonsRequired (int requiredButtons,
  41413. bool positionTitleBarButtonsOnLeft);
  41414. /** Sets whether the title should be centred within the window.
  41415. If true, the title text is shown in the middle of the title-bar; if false,
  41416. it'll be shown at the left of the bar.
  41417. */
  41418. void setTitleBarTextCentred (bool textShouldBeCentred);
  41419. /** Creates a menu inside this window.
  41420. @param menuBarModel this specifies a MenuBarModel that should be used to
  41421. generate the contents of a menu bar that will be placed
  41422. just below the title bar, and just above any content
  41423. component. If this value is zero, any existing menu bar
  41424. will be removed from the component; if non-zero, one will
  41425. be added if it's required.
  41426. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  41427. or less to use the look-and-feel's default size.
  41428. */
  41429. void setMenuBar (MenuBarModel* menuBarModel,
  41430. int menuBarHeight = 0);
  41431. /** Returns the current menu bar component, or null if there isn't one.
  41432. This is probably a MenuBarComponent, unless a custom one has been set using
  41433. setMenuBarComponent().
  41434. */
  41435. Component* getMenuBarComponent() const throw();
  41436. /** Replaces the current menu bar with a custom component.
  41437. The component will be owned and deleted by the document window.
  41438. */
  41439. void setMenuBarComponent (Component* newMenuBarComponent);
  41440. /** This method is called when the user tries to close the window.
  41441. This is triggered by the user clicking the close button, or using some other
  41442. OS-specific key shortcut or OS menu for getting rid of a window.
  41443. If the window is just a pop-up, you should override this closeButtonPressed()
  41444. method and make it delete the window in whatever way is appropriate for your
  41445. app. E.g. you might just want to call "delete this".
  41446. If your app is centred around this window such that the whole app should quit when
  41447. the window is closed, then you will probably want to use this method as an opportunity
  41448. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  41449. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  41450. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  41451. or closing it via the taskbar icon on Windows).
  41452. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  41453. redirects it to call this method, so any methods of closing the window that are
  41454. caught by userTriedToCloseWindow() will also end up here).
  41455. */
  41456. virtual void closeButtonPressed();
  41457. /** Callback that is triggered when the minimise button is pressed.
  41458. The default implementation of this calls ResizableWindow::setMinimised(), but
  41459. you can override it to do more customised behaviour.
  41460. */
  41461. virtual void minimiseButtonPressed();
  41462. /** Callback that is triggered when the maximise button is pressed, or when the
  41463. title-bar is double-clicked.
  41464. The default implementation of this calls ResizableWindow::setFullScreen(), but
  41465. you can override it to do more customised behaviour.
  41466. */
  41467. virtual void maximiseButtonPressed();
  41468. /** Returns the close button, (or 0 if there isn't one). */
  41469. Button* getCloseButton() const throw();
  41470. /** Returns the minimise button, (or 0 if there isn't one). */
  41471. Button* getMinimiseButton() const throw();
  41472. /** Returns the maximise button, (or 0 if there isn't one). */
  41473. Button* getMaximiseButton() const throw();
  41474. /** A set of colour IDs to use to change the colour of various aspects of the window.
  41475. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41476. methods.
  41477. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41478. */
  41479. enum ColourIds
  41480. {
  41481. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  41482. and feel class how this is used. */
  41483. };
  41484. /** @internal */
  41485. void paint (Graphics& g);
  41486. /** @internal */
  41487. void resized();
  41488. /** @internal */
  41489. void lookAndFeelChanged();
  41490. /** @internal */
  41491. const BorderSize getBorderThickness();
  41492. /** @internal */
  41493. const BorderSize getContentComponentBorder();
  41494. /** @internal */
  41495. void mouseDoubleClick (const MouseEvent& e);
  41496. /** @internal */
  41497. void userTriedToCloseWindow();
  41498. /** @internal */
  41499. void activeWindowStatusChanged();
  41500. /** @internal */
  41501. int getDesktopWindowStyleFlags() const;
  41502. /** @internal */
  41503. void parentHierarchyChanged();
  41504. /** @internal */
  41505. const Rectangle<int> getTitleBarArea();
  41506. private:
  41507. int titleBarHeight, menuBarHeight, requiredButtons;
  41508. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  41509. ScopedPointer <Button> titleBarButtons [3];
  41510. Image titleBarIcon;
  41511. ScopedPointer <Component> menuBar;
  41512. MenuBarModel* menuBarModel;
  41513. class ButtonListenerProxy;
  41514. friend class ScopedPointer <ButtonListenerProxy>;
  41515. ScopedPointer <ButtonListenerProxy> buttonListener;
  41516. void repaintTitleBar();
  41517. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  41518. };
  41519. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  41520. /*** End of inlined file: juce_DocumentWindow.h ***/
  41521. class MultiDocumentPanel;
  41522. class MDITabbedComponentInternal;
  41523. /**
  41524. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  41525. component.
  41526. It's like a normal DocumentWindow but has some extra functionality to make sure
  41527. everything works nicely inside a MultiDocumentPanel.
  41528. @see MultiDocumentPanel
  41529. */
  41530. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  41531. {
  41532. public:
  41533. /**
  41534. */
  41535. MultiDocumentPanelWindow (const Colour& backgroundColour);
  41536. /** Destructor. */
  41537. ~MultiDocumentPanelWindow();
  41538. /** @internal */
  41539. void maximiseButtonPressed();
  41540. /** @internal */
  41541. void closeButtonPressed();
  41542. /** @internal */
  41543. void activeWindowStatusChanged();
  41544. /** @internal */
  41545. void broughtToFront();
  41546. private:
  41547. void updateOrder();
  41548. MultiDocumentPanel* getOwner() const throw();
  41549. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  41550. };
  41551. /**
  41552. A component that contains a set of other components either in floating windows
  41553. or tabs.
  41554. This acts as a panel that can be used to hold a set of open document windows, with
  41555. different layout modes.
  41556. Use addDocument() and closeDocument() to add or remove components from the
  41557. panel - never use any of the Component methods to access the panel's child
  41558. components directly, as these are managed internally.
  41559. */
  41560. class JUCE_API MultiDocumentPanel : public Component,
  41561. private ComponentListener
  41562. {
  41563. public:
  41564. /** Creates an empty panel.
  41565. Use addDocument() and closeDocument() to add or remove components from the
  41566. panel - never use any of the Component methods to access the panel's child
  41567. components directly, as these are managed internally.
  41568. */
  41569. MultiDocumentPanel();
  41570. /** Destructor.
  41571. When deleted, this will call closeAllDocuments (false) to make sure all its
  41572. components are deleted. If you need to make sure all documents are saved
  41573. before closing, then you should call closeAllDocuments (true) and check that
  41574. it returns true before deleting the panel.
  41575. */
  41576. ~MultiDocumentPanel();
  41577. /** Tries to close all the documents.
  41578. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  41579. be called for each open document, and any of these calls fails, this method
  41580. will stop and return false, leaving some documents still open.
  41581. If checkItsOkToCloseFirst is false, then all documents will be closed
  41582. unconditionally.
  41583. @see closeDocument
  41584. */
  41585. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  41586. /** Adds a document component to the panel.
  41587. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  41588. this will fail and return false. (If it does fail, the component passed-in will not be
  41589. deleted, even if deleteWhenRemoved was set to true).
  41590. The MultiDocumentPanel will deal with creating a window border to go around your component,
  41591. so just pass in the bare content component here, no need to give it a ResizableWindow
  41592. or DocumentWindow.
  41593. @param component the component to add
  41594. @param backgroundColour the background colour to use to fill the component's
  41595. window or tab
  41596. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  41597. or closeAllDocuments(), then it will be deleted. If false, then
  41598. the caller must handle the component's deletion
  41599. */
  41600. bool addDocument (Component* component,
  41601. const Colour& backgroundColour,
  41602. bool deleteWhenRemoved);
  41603. /** Closes one of the documents.
  41604. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  41605. be called, and if it fails, this method will return false without closing the
  41606. document.
  41607. If checkItsOkToCloseFirst is false, then the documents will be closed
  41608. unconditionally.
  41609. The component will be deleted if the deleteWhenRemoved parameter was set to
  41610. true when it was added with addDocument.
  41611. @see addDocument, closeAllDocuments
  41612. */
  41613. bool closeDocument (Component* component,
  41614. bool checkItsOkToCloseFirst);
  41615. /** Returns the number of open document windows.
  41616. @see getDocument
  41617. */
  41618. int getNumDocuments() const throw();
  41619. /** Returns one of the open documents.
  41620. The order of the documents in this array may change when they are added, removed
  41621. or moved around.
  41622. @see getNumDocuments
  41623. */
  41624. Component* getDocument (int index) const throw();
  41625. /** Returns the document component that is currently focused or on top.
  41626. If currently using floating windows, then this will be the component in the currently
  41627. active window, or the top component if none are active.
  41628. If it's currently in tabbed mode, then it'll return the component in the active tab.
  41629. @see setActiveDocument
  41630. */
  41631. Component* getActiveDocument() const throw();
  41632. /** Makes one of the components active and brings it to the top.
  41633. @see getActiveDocument
  41634. */
  41635. void setActiveDocument (Component* component);
  41636. /** Callback which gets invoked when the currently-active document changes. */
  41637. virtual void activeDocumentChanged();
  41638. /** Sets a limit on how many windows can be open at once.
  41639. If this is zero or less there's no limit (the default). addDocument() will fail
  41640. if this number is exceeded.
  41641. */
  41642. void setMaximumNumDocuments (int maximumNumDocuments);
  41643. /** Sets an option to make the document fullscreen if there's only one document open.
  41644. If set to true, then if there's only one document, it'll fill the whole of this
  41645. component without tabs or a window border. If false, then tabs or a window
  41646. will always be shown, even if there's only one document. If there's more than
  41647. one document open, then this option makes no difference.
  41648. */
  41649. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  41650. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  41651. */
  41652. bool isFullscreenWhenOneDocument() const throw();
  41653. /** The different layout modes available. */
  41654. enum LayoutMode
  41655. {
  41656. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  41657. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  41658. };
  41659. /** Changes the panel's mode.
  41660. @see LayoutMode, getLayoutMode
  41661. */
  41662. void setLayoutMode (LayoutMode newLayoutMode);
  41663. /** Returns the current layout mode. */
  41664. LayoutMode getLayoutMode() const throw() { return mode; }
  41665. /** Sets the background colour for the whole panel.
  41666. Each document has its own background colour, but this is the one used to fill the areas
  41667. behind them.
  41668. */
  41669. void setBackgroundColour (const Colour& newBackgroundColour);
  41670. /** Returns the current background colour.
  41671. @see setBackgroundColour
  41672. */
  41673. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  41674. /** A subclass must override this to say whether its currently ok for a document
  41675. to be closed.
  41676. This method is called by closeDocument() and closeAllDocuments() to indicate that
  41677. a document should be saved if possible, ready for it to be closed.
  41678. If this method returns true, then it means the document is ok and can be closed.
  41679. If it returns false, then it means that the closeDocument() method should stop
  41680. and not close.
  41681. Normally, you'd use this method to ask the user if they want to save any changes,
  41682. then return true if the save operation went ok. If the user cancelled the save
  41683. operation you could return false here to abort the close operation.
  41684. If your component is based on the FileBasedDocument class, then you'd probably want
  41685. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  41686. FileBasedDocument::savedOk
  41687. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  41688. */
  41689. virtual bool tryToCloseDocument (Component* component) = 0;
  41690. /** Creates a new window to be used for a document.
  41691. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  41692. but you might want to override it to return a custom component.
  41693. */
  41694. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  41695. /** @internal */
  41696. void paint (Graphics& g);
  41697. /** @internal */
  41698. void resized();
  41699. /** @internal */
  41700. void componentNameChanged (Component&);
  41701. private:
  41702. LayoutMode mode;
  41703. Array <Component*> components;
  41704. ScopedPointer<TabbedComponent> tabComponent;
  41705. Colour backgroundColour;
  41706. int maximumNumDocuments, numDocsBeforeTabsUsed;
  41707. friend class MultiDocumentPanelWindow;
  41708. friend class MDITabbedComponentInternal;
  41709. Component* getContainerComp (Component* c) const;
  41710. void updateOrder();
  41711. void addWindow (Component* component);
  41712. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  41713. };
  41714. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  41715. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  41716. #endif
  41717. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  41718. #endif
  41719. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  41720. #endif
  41721. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  41722. #endif
  41723. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  41724. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  41725. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  41726. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  41727. /**
  41728. For laying out a set of components, where the components have preferred sizes
  41729. and size limits, but where they are allowed to stretch to fill the available
  41730. space.
  41731. For example, if you have a component containing several other components, and
  41732. each one should be given a share of the total size, you could use one of these
  41733. to resize the child components when the parent component is resized. Then
  41734. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  41735. A StretchableLayoutManager operates only in one dimension, so if you have a set
  41736. of components stacked vertically on top of each other, you'd use one to manage their
  41737. heights. To build up complex arrangements of components, e.g. for applications
  41738. with multiple nested panels, you would use more than one StretchableLayoutManager.
  41739. E.g. by using two (one vertical, one horizontal), you could create a resizable
  41740. spreadsheet-style table.
  41741. E.g.
  41742. @code
  41743. class MyComp : public Component
  41744. {
  41745. StretchableLayoutManager myLayout;
  41746. MyComp()
  41747. {
  41748. myLayout.setItemLayout (0, // for item 0
  41749. 50, 100, // must be between 50 and 100 pixels in size
  41750. -0.6); // and its preferred size is 60% of the total available space
  41751. myLayout.setItemLayout (1, // for item 1
  41752. -0.2, -0.6, // size must be between 20% and 60% of the available space
  41753. 50); // and its preferred size is 50 pixels
  41754. }
  41755. void resized()
  41756. {
  41757. // make a list of two of our child components that we want to reposition
  41758. Component* comps[] = { myComp1, myComp2 };
  41759. // this will position the 2 components, one above the other, to fit
  41760. // vertically into the rectangle provided.
  41761. myLayout.layOutComponents (comps, 2,
  41762. 0, 0, getWidth(), getHeight(),
  41763. true);
  41764. }
  41765. };
  41766. @endcode
  41767. @see StretchableLayoutResizerBar
  41768. */
  41769. class JUCE_API StretchableLayoutManager
  41770. {
  41771. public:
  41772. /** Creates an empty layout.
  41773. You'll need to add some item properties to the layout before it can be used
  41774. to resize things - see setItemLayout().
  41775. */
  41776. StretchableLayoutManager();
  41777. /** Destructor. */
  41778. ~StretchableLayoutManager();
  41779. /** For a numbered item, this sets its size limits and preferred size.
  41780. @param itemIndex the index of the item to change.
  41781. @param minimumSize the minimum size that this item is allowed to be - a positive number
  41782. indicates an absolute size in pixels. A negative number indicates a
  41783. proportion of the available space (e.g -0.5 is 50%)
  41784. @param maximumSize the maximum size that this item is allowed to be - a positive number
  41785. indicates an absolute size in pixels. A negative number indicates a
  41786. proportion of the available space
  41787. @param preferredSize the size that this item would like to be, if there's enough room. A
  41788. positive number indicates an absolute size in pixels. A negative number
  41789. indicates a proportion of the available space
  41790. @see getItemLayout
  41791. */
  41792. void setItemLayout (int itemIndex,
  41793. double minimumSize,
  41794. double maximumSize,
  41795. double preferredSize);
  41796. /** For a numbered item, this returns its size limits and preferred size.
  41797. @param itemIndex the index of the item.
  41798. @param minimumSize the minimum size that this item is allowed to be - a positive number
  41799. indicates an absolute size in pixels. A negative number indicates a
  41800. proportion of the available space (e.g -0.5 is 50%)
  41801. @param maximumSize the maximum size that this item is allowed to be - a positive number
  41802. indicates an absolute size in pixels. A negative number indicates a
  41803. proportion of the available space
  41804. @param preferredSize the size that this item would like to be, if there's enough room. A
  41805. positive number indicates an absolute size in pixels. A negative number
  41806. indicates a proportion of the available space
  41807. @returns false if the item's properties hadn't been set
  41808. @see setItemLayout
  41809. */
  41810. bool getItemLayout (int itemIndex,
  41811. double& minimumSize,
  41812. double& maximumSize,
  41813. double& preferredSize) const;
  41814. /** Clears all the properties that have been set with setItemLayout() and resets
  41815. this object to its initial state.
  41816. */
  41817. void clearAllItems();
  41818. /** Takes a set of components that correspond to the layout's items, and positions
  41819. them to fill a space.
  41820. This will try to give each item its preferred size, whether that's a relative size
  41821. or an absolute one.
  41822. @param components an array of components that correspond to each of the
  41823. numbered items that the StretchableLayoutManager object
  41824. has been told about with setItemLayout()
  41825. @param numComponents the number of components in the array that is passed-in. This
  41826. should be the same as the number of items this object has been
  41827. told about.
  41828. @param x the left of the rectangle in which the components should
  41829. be laid out
  41830. @param y the top of the rectangle in which the components should
  41831. be laid out
  41832. @param width the width of the rectangle in which the components should
  41833. be laid out
  41834. @param height the height of the rectangle in which the components should
  41835. be laid out
  41836. @param vertically if true, the components will be positioned in a vertical stack,
  41837. so that they fill the height of the rectangle. If false, they
  41838. will be placed side-by-side in a horizontal line, filling the
  41839. available width
  41840. @param resizeOtherDimension if true, this means that the components will have their
  41841. other dimension resized to fit the space - i.e. if the 'vertically'
  41842. parameter is true, their x-positions and widths are adjusted to fit
  41843. the x and width parameters; if 'vertically' is false, their y-positions
  41844. and heights are adjusted to fit the y and height parameters.
  41845. */
  41846. void layOutComponents (Component** components,
  41847. int numComponents,
  41848. int x, int y, int width, int height,
  41849. bool vertically,
  41850. bool resizeOtherDimension);
  41851. /** Returns the current position of one of the items.
  41852. This is only a valid call after layOutComponents() has been called, as it
  41853. returns the last position that this item was placed at. If the layout was
  41854. vertical, the value returned will be the y position of the top of the item,
  41855. relative to the top of the rectangle in which the items were placed (so for
  41856. example, item 0 will always have position of 0, even in the rectangle passed
  41857. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  41858. the position returned is the item's left-hand position, again relative to the
  41859. x position of the rectangle used.
  41860. @see getItemCurrentSize, setItemPosition
  41861. */
  41862. int getItemCurrentPosition (int itemIndex) const;
  41863. /** Returns the current size of one of the items.
  41864. This is only meaningful after layOutComponents() has been called, as it
  41865. returns the last size that this item was given. If the layout was done
  41866. vertically, it'll return the item's height in pixels; if it was horizontal,
  41867. it'll return its width.
  41868. @see getItemCurrentRelativeSize
  41869. */
  41870. int getItemCurrentAbsoluteSize (int itemIndex) const;
  41871. /** Returns the current size of one of the items.
  41872. This is only meaningful after layOutComponents() has been called, as it
  41873. returns the last size that this item was given. If the layout was done
  41874. vertically, it'll return a negative value representing the item's height relative
  41875. to the last size used for laying the components out; if the layout was done
  41876. horizontally it'll be the proportion of its width.
  41877. @see getItemCurrentAbsoluteSize
  41878. */
  41879. double getItemCurrentRelativeSize (int itemIndex) const;
  41880. /** Moves one of the items, shifting along any other items as necessary in
  41881. order to get it to the desired position.
  41882. Calling this method will also update the preferred sizes of the items it
  41883. shuffles along, so that they reflect their new positions.
  41884. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  41885. about when it's dragged).
  41886. @param itemIndex the item to move
  41887. @param newPosition the absolute position that you'd like this item to move
  41888. to. The item might not be able to always reach exactly this position,
  41889. because other items may have minimum sizes that constrain how
  41890. far it can go
  41891. */
  41892. void setItemPosition (int itemIndex,
  41893. int newPosition);
  41894. private:
  41895. struct ItemLayoutProperties
  41896. {
  41897. int itemIndex;
  41898. int currentSize;
  41899. double minSize, maxSize, preferredSize;
  41900. };
  41901. OwnedArray <ItemLayoutProperties> items;
  41902. int totalSize;
  41903. static int sizeToRealSize (double size, int totalSpace);
  41904. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  41905. void setTotalSize (int newTotalSize);
  41906. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  41907. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  41908. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  41909. void updatePrefSizesToMatchCurrentPositions();
  41910. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  41911. };
  41912. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  41913. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  41914. #endif
  41915. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  41916. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  41917. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  41918. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  41919. /**
  41920. A component that acts as one of the vertical or horizontal bars you see being
  41921. used to resize panels in a window.
  41922. One of these acts with a StretchableLayoutManager to resize the other components.
  41923. @see StretchableLayoutManager
  41924. */
  41925. class JUCE_API StretchableLayoutResizerBar : public Component
  41926. {
  41927. public:
  41928. /** Creates a resizer bar for use on a specified layout.
  41929. @param layoutToUse the layout that will be affected when this bar
  41930. is dragged
  41931. @param itemIndexInLayout the item index in the layout that corresponds to
  41932. this bar component. You'll need to set up the item
  41933. properties in a suitable way for a divider bar, e.g.
  41934. for an 8-pixel wide bar which, you could call
  41935. myLayout->setItemLayout (barIndex, 8, 8, 8)
  41936. @param isBarVertical true if it's an upright bar that you drag left and
  41937. right; false for a horizontal one that you drag up and
  41938. down
  41939. */
  41940. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  41941. int itemIndexInLayout,
  41942. bool isBarVertical);
  41943. /** Destructor. */
  41944. ~StretchableLayoutResizerBar();
  41945. /** This is called when the bar is dragged.
  41946. This method must update the positions of any components whose position is
  41947. determined by the StretchableLayoutManager, because they might have just
  41948. moved.
  41949. The default implementation calls the resized() method of this component's
  41950. parent component, because that's often where you're likely to apply the
  41951. layout, but it can be overridden for more specific needs.
  41952. */
  41953. virtual void hasBeenMoved();
  41954. /** @internal */
  41955. void paint (Graphics& g);
  41956. /** @internal */
  41957. void mouseDown (const MouseEvent& e);
  41958. /** @internal */
  41959. void mouseDrag (const MouseEvent& e);
  41960. private:
  41961. StretchableLayoutManager* layout;
  41962. int itemIndex, mouseDownPos;
  41963. bool isVertical;
  41964. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  41965. };
  41966. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  41967. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  41968. #endif
  41969. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  41970. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  41971. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  41972. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  41973. /**
  41974. A utility class for fitting a set of objects whose sizes can vary between
  41975. a minimum and maximum size, into a space.
  41976. This is a trickier algorithm than it would first seem, so I've put it in this
  41977. class to allow it to be shared by various bits of code.
  41978. To use it, create one of these objects, call addItem() to add the list of items
  41979. you need, then call resizeToFit(), which will change all their sizes. You can
  41980. then retrieve the new sizes with getItemSize() and getNumItems().
  41981. It's currently used by the TableHeaderComponent for stretching out the table
  41982. headings to fill the table's width.
  41983. */
  41984. class StretchableObjectResizer
  41985. {
  41986. public:
  41987. /** Creates an empty object resizer. */
  41988. StretchableObjectResizer();
  41989. /** Destructor. */
  41990. ~StretchableObjectResizer();
  41991. /** Adds an item to the list.
  41992. The order parameter lets you specify groups of items that are resized first when some
  41993. space needs to be found. Those items with an order of 0 will be the first ones to be
  41994. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  41995. will then try resizing the items with an order of 1, then 2, and so on.
  41996. */
  41997. void addItem (double currentSize,
  41998. double minSize,
  41999. double maxSize,
  42000. int order = 0);
  42001. /** Resizes all the items to fit this amount of space.
  42002. This will attempt to fit them in without exceeding each item's miniumum and
  42003. maximum sizes. In cases where none of the items can be expanded or enlarged any
  42004. further, the final size may be greater or less than the size passed in.
  42005. After calling this method, you can retrieve the new sizes with the getItemSize()
  42006. method.
  42007. */
  42008. void resizeToFit (double targetSize);
  42009. /** Returns the number of items that have been added. */
  42010. int getNumItems() const throw() { return items.size(); }
  42011. /** Returns the size of one of the items. */
  42012. double getItemSize (int index) const throw();
  42013. private:
  42014. struct Item
  42015. {
  42016. double size;
  42017. double minSize;
  42018. double maxSize;
  42019. int order;
  42020. };
  42021. OwnedArray <Item> items;
  42022. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  42023. };
  42024. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  42025. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  42026. #endif
  42027. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  42028. #endif
  42029. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  42030. #endif
  42031. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  42032. #endif
  42033. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  42034. /*** Start of inlined file: juce_LookAndFeel.h ***/
  42035. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  42036. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  42037. /*** Start of inlined file: juce_AlertWindow.h ***/
  42038. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  42039. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  42040. /*** Start of inlined file: juce_TextLayout.h ***/
  42041. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  42042. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  42043. class Graphics;
  42044. /**
  42045. A laid-out arrangement of text.
  42046. You can add text in different fonts to a TextLayout object, then call its
  42047. layout() method to word-wrap it into lines. The layout can then be drawn
  42048. using a graphics context.
  42049. It's handy if you've got a message to display, because you can format it,
  42050. measure the extent of the layout, and then create a suitably-sized window
  42051. to show it in.
  42052. @see Font, Graphics::drawFittedText, GlyphArrangement
  42053. */
  42054. class JUCE_API TextLayout
  42055. {
  42056. public:
  42057. /** Creates an empty text layout.
  42058. Text can then be appended using the appendText() method.
  42059. */
  42060. TextLayout();
  42061. /** Creates a copy of another layout object. */
  42062. TextLayout (const TextLayout& other);
  42063. /** Creates a text layout from an initial string and font. */
  42064. TextLayout (const String& text, const Font& font);
  42065. /** Destructor. */
  42066. ~TextLayout();
  42067. /** Copies another layout onto this one. */
  42068. TextLayout& operator= (const TextLayout& layoutToCopy);
  42069. /** Clears the layout, removing all its text. */
  42070. void clear();
  42071. /** Adds a string to the end of the arrangement.
  42072. The string will be broken onto new lines wherever it contains
  42073. carriage-returns or linefeeds. After adding it, you can call layout()
  42074. to wrap long lines into a paragraph and justify it.
  42075. */
  42076. void appendText (const String& textToAppend,
  42077. const Font& fontToUse);
  42078. /** Replaces all the text with a new string.
  42079. This is equivalent to calling clear() followed by appendText().
  42080. */
  42081. void setText (const String& newText,
  42082. const Font& fontToUse);
  42083. /** Returns true if the layout has not had any text added yet. */
  42084. bool isEmpty() const;
  42085. /** Breaks the text up to form a paragraph with the given width.
  42086. @param maximumWidth any text wider than this will be split
  42087. across multiple lines
  42088. @param justification how the lines are to be laid-out horizontally
  42089. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  42090. width that keeps all the lines of text at a
  42091. similar length - this is good when you're displaying
  42092. a short message and don't want it to get split
  42093. onto two lines with only a couple of words on
  42094. the second line, which looks untidy.
  42095. */
  42096. void layout (int maximumWidth,
  42097. const Justification& justification,
  42098. bool attemptToBalanceLineLengths);
  42099. /** Returns the overall width of the entire text layout. */
  42100. int getWidth() const;
  42101. /** Returns the overall height of the entire text layout. */
  42102. int getHeight() const;
  42103. /** Returns the total number of lines of text. */
  42104. int getNumLines() const { return totalLines; }
  42105. /** Returns the width of a particular line of text.
  42106. @param lineNumber the line, from 0 to (getNumLines() - 1)
  42107. */
  42108. int getLineWidth (int lineNumber) const;
  42109. /** Renders the text at a specified position using a graphics context.
  42110. */
  42111. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  42112. /** Renders the text within a specified rectangle using a graphics context.
  42113. The justification flags dictate how the block of text should be positioned
  42114. within the rectangle.
  42115. */
  42116. void drawWithin (Graphics& g,
  42117. int x, int y, int w, int h,
  42118. const Justification& layoutFlags) const;
  42119. private:
  42120. class Token;
  42121. friend class OwnedArray <Token>;
  42122. OwnedArray <Token> tokens;
  42123. int totalLines;
  42124. JUCE_LEAK_DETECTOR (TextLayout);
  42125. };
  42126. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  42127. /*** End of inlined file: juce_TextLayout.h ***/
  42128. /** A window that displays a message and has buttons for the user to react to it.
  42129. For simple dialog boxes with just a couple of buttons on them, there are
  42130. some static methods for running these.
  42131. For more complex dialogs, an AlertWindow can be created, then it can have some
  42132. buttons and components added to it, and its runModalLoop() method is then used to
  42133. show it. The value returned by runModalLoop() shows which button the
  42134. user pressed to dismiss the box.
  42135. @see ThreadWithProgressWindow
  42136. */
  42137. class JUCE_API AlertWindow : public TopLevelWindow,
  42138. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  42139. {
  42140. public:
  42141. /** The type of icon to show in the dialog box. */
  42142. enum AlertIconType
  42143. {
  42144. NoIcon, /**< No icon will be shown on the dialog box. */
  42145. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  42146. user to answer a question. */
  42147. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  42148. warning about something and shouldn't be ignored. */
  42149. InfoIcon /**< An icon that indicates that the dialog box is just
  42150. giving the user some information, which doesn't require
  42151. a response from them. */
  42152. };
  42153. /** Creates an AlertWindow.
  42154. @param title the headline to show at the top of the dialog box
  42155. @param message a longer, more descriptive message to show underneath the
  42156. headline
  42157. @param iconType the type of icon to display
  42158. @param associatedComponent if this is non-zero, it specifies the component that the
  42159. alert window should be associated with. Depending on the look
  42160. and feel, this might be used for positioning of the alert window.
  42161. */
  42162. AlertWindow (const String& title,
  42163. const String& message,
  42164. AlertIconType iconType,
  42165. Component* associatedComponent = 0);
  42166. /** Destroys the AlertWindow */
  42167. ~AlertWindow();
  42168. /** Returns the type of alert icon that was specified when the window
  42169. was created. */
  42170. AlertIconType getAlertType() const throw() { return alertIconType; }
  42171. /** Changes the dialog box's message.
  42172. This will also resize the window to fit the new message if required.
  42173. */
  42174. void setMessage (const String& message);
  42175. /** Adds a button to the window.
  42176. @param name the text to show on the button
  42177. @param returnValue the value that should be returned from runModalLoop()
  42178. if this is the button that the user presses.
  42179. @param shortcutKey1 an optional key that can be pressed to trigger this button
  42180. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  42181. */
  42182. void addButton (const String& name,
  42183. int returnValue,
  42184. const KeyPress& shortcutKey1 = KeyPress(),
  42185. const KeyPress& shortcutKey2 = KeyPress());
  42186. /** Returns the number of buttons that the window currently has. */
  42187. int getNumButtons() const;
  42188. /** Invokes a click of one of the buttons. */
  42189. void triggerButtonClick (const String& buttonName);
  42190. /** Adds a textbox to the window for entering strings.
  42191. @param name an internal name for the text-box. This is the name to pass to
  42192. the getTextEditorContents() method to find out what the
  42193. user typed-in.
  42194. @param initialContents a string to show in the text box when it's first shown
  42195. @param onScreenLabel if this is non-empty, it will be displayed next to the
  42196. text-box to label it.
  42197. @param isPasswordBox if true, the text editor will display asterisks instead of
  42198. the actual text
  42199. @see getTextEditorContents
  42200. */
  42201. void addTextEditor (const String& name,
  42202. const String& initialContents,
  42203. const String& onScreenLabel = String::empty,
  42204. bool isPasswordBox = false);
  42205. /** Returns the contents of a named textbox.
  42206. After showing an AlertWindow that contains a text editor, this can be
  42207. used to find out what the user has typed into it.
  42208. @param nameOfTextEditor the name of the text box that you're interested in
  42209. @see addTextEditor
  42210. */
  42211. const String getTextEditorContents (const String& nameOfTextEditor) const;
  42212. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  42213. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  42214. /** Adds a drop-down list of choices to the box.
  42215. After the box has been shown, the getComboBoxComponent() method can
  42216. be used to find out which item the user picked.
  42217. @param name the label to use for the drop-down list
  42218. @param items the list of items to show in it
  42219. @param onScreenLabel if this is non-empty, it will be displayed next to the
  42220. combo-box to label it.
  42221. @see getComboBoxComponent
  42222. */
  42223. void addComboBox (const String& name,
  42224. const StringArray& items,
  42225. const String& onScreenLabel = String::empty);
  42226. /** Returns a drop-down list that was added to the AlertWindow.
  42227. @param nameOfList the name that was passed into the addComboBox() method
  42228. when creating the drop-down
  42229. @returns the ComboBox component, or 0 if none was found for the given name.
  42230. */
  42231. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  42232. /** Adds a block of text.
  42233. This is handy for adding a multi-line note next to a textbox or combo-box,
  42234. to provide more details about what's going on.
  42235. */
  42236. void addTextBlock (const String& text);
  42237. /** Adds a progress-bar to the window.
  42238. @param progressValue a variable that will be repeatedly checked while the
  42239. dialog box is visible, to see how far the process has
  42240. got. The value should be in the range 0 to 1.0
  42241. */
  42242. void addProgressBarComponent (double& progressValue);
  42243. /** Adds a user-defined component to the dialog box.
  42244. @param component the component to add - its size should be set up correctly
  42245. before it is passed in. The caller is responsible for deleting
  42246. the component later on - the AlertWindow won't delete it.
  42247. */
  42248. void addCustomComponent (Component* component);
  42249. /** Returns the number of custom components in the dialog box.
  42250. @see getCustomComponent, addCustomComponent
  42251. */
  42252. int getNumCustomComponents() const;
  42253. /** Returns one of the custom components in the dialog box.
  42254. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  42255. will return 0
  42256. @see getNumCustomComponents, addCustomComponent
  42257. */
  42258. Component* getCustomComponent (int index) const;
  42259. /** Removes one of the custom components in the dialog box.
  42260. Note that this won't delete it, it just removes the component from the window
  42261. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  42262. will return 0
  42263. @returns the component that was removed (or zero)
  42264. @see getNumCustomComponents, addCustomComponent
  42265. */
  42266. Component* removeCustomComponent (int index);
  42267. /** Returns true if the window contains any components other than just buttons.*/
  42268. bool containsAnyExtraComponents() const;
  42269. // easy-to-use message box functions:
  42270. /** Shows a dialog box that just has a message and a single button to get rid of it.
  42271. The box is shown modally, and the method returns after the user
  42272. has clicked the button (or pressed the escape or return keys).
  42273. @param iconType the type of icon to show
  42274. @param title the headline to show at the top of the box
  42275. @param message a longer, more descriptive message to show underneath the
  42276. headline
  42277. @param buttonText the text to show in the button - if this string is empty, the
  42278. default string "ok" (or a localised version) will be used.
  42279. @param associatedComponent if this is non-zero, it specifies the component that the
  42280. alert window should be associated with. Depending on the look
  42281. and feel, this might be used for positioning of the alert window.
  42282. */
  42283. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  42284. const String& title,
  42285. const String& message,
  42286. const String& buttonText = String::empty,
  42287. Component* associatedComponent = 0);
  42288. /** Shows a dialog box with two buttons.
  42289. Ideal for ok/cancel or yes/no choices. The return key can also be used
  42290. to trigger the first button, and the escape key for the second button.
  42291. @param iconType the type of icon to show
  42292. @param title the headline to show at the top of the box
  42293. @param message a longer, more descriptive message to show underneath the
  42294. headline
  42295. @param button1Text the text to show in the first button - if this string is
  42296. empty, the default string "ok" (or a localised version of it)
  42297. will be used.
  42298. @param button2Text the text to show in the second button - if this string is
  42299. empty, the default string "cancel" (or a localised version of it)
  42300. will be used.
  42301. @param associatedComponent if this is non-zero, it specifies the component that the
  42302. alert window should be associated with. Depending on the look
  42303. and feel, this might be used for positioning of the alert window.
  42304. @returns true if button 1 was clicked, false if it was button 2
  42305. */
  42306. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  42307. const String& title,
  42308. const String& message,
  42309. const String& button1Text = String::empty,
  42310. const String& button2Text = String::empty,
  42311. Component* associatedComponent = 0);
  42312. /** Shows a dialog box with three buttons.
  42313. Ideal for yes/no/cancel boxes.
  42314. The escape key can be used to trigger the third button.
  42315. @param iconType the type of icon to show
  42316. @param title the headline to show at the top of the box
  42317. @param message a longer, more descriptive message to show underneath the
  42318. headline
  42319. @param button1Text the text to show in the first button - if an empty string, then
  42320. "yes" will be used (or a localised version of it)
  42321. @param button2Text the text to show in the first button - if an empty string, then
  42322. "no" will be used (or a localised version of it)
  42323. @param button3Text the text to show in the first button - if an empty string, then
  42324. "cancel" will be used (or a localised version of it)
  42325. @param associatedComponent if this is non-zero, it specifies the component that the
  42326. alert window should be associated with. Depending on the look
  42327. and feel, this might be used for positioning of the alert window.
  42328. @returns one of the following values:
  42329. - 0 if the third button was pressed (normally used for 'cancel')
  42330. - 1 if the first button was pressed (normally used for 'yes')
  42331. - 2 if the middle button was pressed (normally used for 'no')
  42332. */
  42333. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  42334. const String& title,
  42335. const String& message,
  42336. const String& button1Text = String::empty,
  42337. const String& button2Text = String::empty,
  42338. const String& button3Text = String::empty,
  42339. Component* associatedComponent = 0);
  42340. /** Shows an operating-system native dialog box.
  42341. @param title the title to use at the top
  42342. @param bodyText the longer message to show
  42343. @param isOkCancel if true, this will show an ok/cancel box, if false,
  42344. it'll show a box with just an ok button
  42345. @returns true if the ok button was pressed, false if they pressed cancel.
  42346. */
  42347. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  42348. const String& bodyText,
  42349. bool isOkCancel);
  42350. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  42351. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42352. methods.
  42353. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42354. */
  42355. enum ColourIds
  42356. {
  42357. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  42358. textColourId = 0x1001810, /**< The colour for the text. */
  42359. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  42360. };
  42361. protected:
  42362. /** @internal */
  42363. void paint (Graphics& g);
  42364. /** @internal */
  42365. void mouseDown (const MouseEvent& e);
  42366. /** @internal */
  42367. void mouseDrag (const MouseEvent& e);
  42368. /** @internal */
  42369. bool keyPressed (const KeyPress& key);
  42370. /** @internal */
  42371. void buttonClicked (Button* button);
  42372. /** @internal */
  42373. void lookAndFeelChanged();
  42374. /** @internal */
  42375. void userTriedToCloseWindow();
  42376. /** @internal */
  42377. int getDesktopWindowStyleFlags() const;
  42378. private:
  42379. String text;
  42380. TextLayout textLayout;
  42381. AlertIconType alertIconType;
  42382. ComponentBoundsConstrainer constrainer;
  42383. ComponentDragger dragger;
  42384. Rectangle<int> textArea;
  42385. OwnedArray<TextButton> buttons;
  42386. OwnedArray<TextEditor> textBoxes;
  42387. OwnedArray<ComboBox> comboBoxes;
  42388. OwnedArray<ProgressBar> progressBars;
  42389. Array<Component*> customComps;
  42390. OwnedArray<Component> textBlocks;
  42391. Array<Component*> allComps;
  42392. StringArray textboxNames, comboBoxNames;
  42393. Font font;
  42394. Component* associatedComponent;
  42395. void updateLayout (bool onlyIncreaseSize);
  42396. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  42397. };
  42398. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  42399. /*** End of inlined file: juce_AlertWindow.h ***/
  42400. class ToggleButton;
  42401. class TextButton;
  42402. class AlertWindow;
  42403. class TextLayout;
  42404. class ScrollBar;
  42405. class BubbleComponent;
  42406. class ComboBox;
  42407. class Button;
  42408. class FilenameComponent;
  42409. class DocumentWindow;
  42410. class ResizableWindow;
  42411. class GroupComponent;
  42412. class MenuBarComponent;
  42413. class DropShadower;
  42414. class GlyphArrangement;
  42415. class PropertyComponent;
  42416. class TableHeaderComponent;
  42417. class Toolbar;
  42418. class ToolbarItemComponent;
  42419. class PopupMenu;
  42420. class ProgressBar;
  42421. class FileBrowserComponent;
  42422. class DirectoryContentsDisplayComponent;
  42423. class FilePreviewComponent;
  42424. class ImageButton;
  42425. class CallOutBox;
  42426. class Drawable;
  42427. /**
  42428. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  42429. can be used to apply different 'skins' to the application.
  42430. */
  42431. class JUCE_API LookAndFeel
  42432. {
  42433. public:
  42434. /** Creates the default JUCE look and feel. */
  42435. LookAndFeel();
  42436. /** Destructor. */
  42437. virtual ~LookAndFeel();
  42438. /** Returns the current default look-and-feel for a component to use when it
  42439. hasn't got one explicitly set.
  42440. @see setDefaultLookAndFeel
  42441. */
  42442. static LookAndFeel& getDefaultLookAndFeel() throw();
  42443. /** Changes the default look-and-feel.
  42444. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  42445. set to 0, it will revert to using the default one. The
  42446. object passed-in must be deleted by the caller when
  42447. it's no longer needed.
  42448. @see getDefaultLookAndFeel
  42449. */
  42450. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  42451. /** Looks for a colour that has been registered with the given colour ID number.
  42452. If a colour has been set for this ID number using setColour(), then it is
  42453. returned. If none has been set, it will just return Colours::black.
  42454. The colour IDs for various purposes are stored as enums in the components that
  42455. they are relevent to - for an example, see Slider::ColourIds,
  42456. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  42457. If you're looking up a colour for use in drawing a component, it's usually
  42458. best not to call this directly, but to use the Component::findColour() method
  42459. instead. That will first check whether a suitable colour has been registered
  42460. directly with the component, and will fall-back on calling the component's
  42461. LookAndFeel's findColour() method if none is found.
  42462. @see setColour, Component::findColour, Component::setColour
  42463. */
  42464. const Colour findColour (int colourId) const throw();
  42465. /** Registers a colour to be used for a particular purpose.
  42466. For more details, see the comments for findColour().
  42467. @see findColour, Component::findColour, Component::setColour
  42468. */
  42469. void setColour (int colourId, const Colour& colour) throw();
  42470. /** Returns true if the specified colour ID has been explicitly set using the
  42471. setColour() method.
  42472. */
  42473. bool isColourSpecified (int colourId) const throw();
  42474. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  42475. /** Allows you to change the default sans-serif font.
  42476. If you need to supply your own Typeface object for any of the default fonts, rather
  42477. than just supplying the name (e.g. if you want to use an embedded font), then
  42478. you should instead override getTypefaceForFont() to create and return the typeface.
  42479. */
  42480. void setDefaultSansSerifTypefaceName (const String& newName);
  42481. /** Override this to get the chance to swap a component's mouse cursor for a
  42482. customised one.
  42483. */
  42484. virtual const MouseCursor getMouseCursorFor (Component& component);
  42485. /** Draws the lozenge-shaped background for a standard button. */
  42486. virtual void drawButtonBackground (Graphics& g,
  42487. Button& button,
  42488. const Colour& backgroundColour,
  42489. bool isMouseOverButton,
  42490. bool isButtonDown);
  42491. virtual const Font getFontForTextButton (TextButton& button);
  42492. /** Draws the text for a TextButton. */
  42493. virtual void drawButtonText (Graphics& g,
  42494. TextButton& button,
  42495. bool isMouseOverButton,
  42496. bool isButtonDown);
  42497. /** Draws the contents of a standard ToggleButton. */
  42498. virtual void drawToggleButton (Graphics& g,
  42499. ToggleButton& button,
  42500. bool isMouseOverButton,
  42501. bool isButtonDown);
  42502. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  42503. virtual void drawTickBox (Graphics& g,
  42504. Component& component,
  42505. float x, float y, float w, float h,
  42506. bool ticked,
  42507. bool isEnabled,
  42508. bool isMouseOverButton,
  42509. bool isButtonDown);
  42510. /* AlertWindow handling..
  42511. */
  42512. virtual AlertWindow* createAlertWindow (const String& title,
  42513. const String& message,
  42514. const String& button1,
  42515. const String& button2,
  42516. const String& button3,
  42517. AlertWindow::AlertIconType iconType,
  42518. int numButtons,
  42519. Component* associatedComponent);
  42520. virtual void drawAlertBox (Graphics& g,
  42521. AlertWindow& alert,
  42522. const Rectangle<int>& textArea,
  42523. TextLayout& textLayout);
  42524. virtual int getAlertBoxWindowFlags();
  42525. virtual int getAlertWindowButtonHeight();
  42526. virtual const Font getAlertWindowMessageFont();
  42527. virtual const Font getAlertWindowFont();
  42528. /** Draws a progress bar.
  42529. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  42530. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  42531. isn't known). It can use the current time as a basis for playing an animation.
  42532. (Used by progress bars in AlertWindow).
  42533. */
  42534. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  42535. int width, int height,
  42536. double progress, const String& textToShow);
  42537. // Draws a small image that spins to indicate that something's happening..
  42538. // This method should use the current time to animate itself, so just keep
  42539. // repainting it every so often.
  42540. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  42541. int x, int y, int w, int h);
  42542. /** Draws one of the buttons on a scrollbar.
  42543. @param g the context to draw into
  42544. @param scrollbar the bar itself
  42545. @param width the width of the button
  42546. @param height the height of the button
  42547. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  42548. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  42549. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  42550. @param isButtonDown whether the mouse button's held down
  42551. */
  42552. virtual void drawScrollbarButton (Graphics& g,
  42553. ScrollBar& scrollbar,
  42554. int width, int height,
  42555. int buttonDirection,
  42556. bool isScrollbarVertical,
  42557. bool isMouseOverButton,
  42558. bool isButtonDown);
  42559. /** Draws the thumb area of a scrollbar.
  42560. @param g the context to draw into
  42561. @param scrollbar the bar itself
  42562. @param x the x position of the left edge of the thumb area to draw in
  42563. @param y the y position of the top edge of the thumb area to draw in
  42564. @param width the width of the thumb area to draw in
  42565. @param height the height of the thumb area to draw in
  42566. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  42567. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  42568. thumb, or its x position for horizontal bars
  42569. @param thumbSize for vertical bars, the height of the thumb, or its width for
  42570. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  42571. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  42572. currently dragging the thumb
  42573. @param isMouseDown whether the mouse is currently dragging the scrollbar
  42574. */
  42575. virtual void drawScrollbar (Graphics& g,
  42576. ScrollBar& scrollbar,
  42577. int x, int y,
  42578. int width, int height,
  42579. bool isScrollbarVertical,
  42580. int thumbStartPosition,
  42581. int thumbSize,
  42582. bool isMouseOver,
  42583. bool isMouseDown);
  42584. /** Returns the component effect to use for a scrollbar */
  42585. virtual ImageEffectFilter* getScrollbarEffect();
  42586. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  42587. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  42588. /** Returns the default thickness to use for a scrollbar. */
  42589. virtual int getDefaultScrollbarWidth();
  42590. /** Returns the length in pixels to use for a scrollbar button. */
  42591. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  42592. /** Returns a tick shape for use in yes/no boxes, etc. */
  42593. virtual const Path getTickShape (float height);
  42594. /** Returns a cross shape for use in yes/no boxes, etc. */
  42595. virtual const Path getCrossShape (float height);
  42596. /** Draws the + or - box in a treeview. */
  42597. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  42598. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  42599. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  42600. // These return a pointer to an internally cached drawable - make sure you don't keep
  42601. // a copy of this pointer anywhere, as it may become invalid in the future.
  42602. virtual const Drawable* getDefaultFolderImage();
  42603. virtual const Drawable* getDefaultDocumentFileImage();
  42604. virtual void createFileChooserHeaderText (const String& title,
  42605. const String& instructions,
  42606. GlyphArrangement& destArrangement,
  42607. int width);
  42608. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  42609. const String& filename, Image* icon,
  42610. const String& fileSizeDescription,
  42611. const String& fileTimeDescription,
  42612. bool isDirectory,
  42613. bool isItemSelected,
  42614. int itemIndex,
  42615. DirectoryContentsDisplayComponent& component);
  42616. virtual Button* createFileBrowserGoUpButton();
  42617. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  42618. DirectoryContentsDisplayComponent* fileListComponent,
  42619. FilePreviewComponent* previewComp,
  42620. ComboBox* currentPathBox,
  42621. TextEditor* filenameBox,
  42622. Button* goUpButton);
  42623. virtual void drawBubble (Graphics& g,
  42624. float tipX, float tipY,
  42625. float boxX, float boxY, float boxW, float boxH);
  42626. /** Fills the background of a popup menu component. */
  42627. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  42628. /** Draws one of the items in a popup menu. */
  42629. virtual void drawPopupMenuItem (Graphics& g,
  42630. int width, int height,
  42631. bool isSeparator,
  42632. bool isActive,
  42633. bool isHighlighted,
  42634. bool isTicked,
  42635. bool hasSubMenu,
  42636. const String& text,
  42637. const String& shortcutKeyText,
  42638. Image* image,
  42639. const Colour* const textColour);
  42640. /** Returns the size and style of font to use in popup menus. */
  42641. virtual const Font getPopupMenuFont();
  42642. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  42643. int width, int height,
  42644. bool isScrollUpArrow);
  42645. /** Finds the best size for an item in a popup menu. */
  42646. virtual void getIdealPopupMenuItemSize (const String& text,
  42647. bool isSeparator,
  42648. int standardMenuItemHeight,
  42649. int& idealWidth,
  42650. int& idealHeight);
  42651. virtual int getMenuWindowFlags();
  42652. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  42653. bool isMouseOverBar,
  42654. MenuBarComponent& menuBar);
  42655. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  42656. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  42657. virtual void drawMenuBarItem (Graphics& g,
  42658. int width, int height,
  42659. int itemIndex,
  42660. const String& itemText,
  42661. bool isMouseOverItem,
  42662. bool isMenuOpen,
  42663. bool isMouseOverBar,
  42664. MenuBarComponent& menuBar);
  42665. virtual void drawComboBox (Graphics& g, int width, int height,
  42666. bool isButtonDown,
  42667. int buttonX, int buttonY,
  42668. int buttonW, int buttonH,
  42669. ComboBox& box);
  42670. virtual const Font getComboBoxFont (ComboBox& box);
  42671. virtual Label* createComboBoxTextBox (ComboBox& box);
  42672. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  42673. virtual void drawLabel (Graphics& g, Label& label);
  42674. virtual void drawLinearSlider (Graphics& g,
  42675. int x, int y,
  42676. int width, int height,
  42677. float sliderPos,
  42678. float minSliderPos,
  42679. float maxSliderPos,
  42680. const Slider::SliderStyle style,
  42681. Slider& slider);
  42682. virtual void drawLinearSliderBackground (Graphics& g,
  42683. int x, int y,
  42684. int width, int height,
  42685. float sliderPos,
  42686. float minSliderPos,
  42687. float maxSliderPos,
  42688. const Slider::SliderStyle style,
  42689. Slider& slider);
  42690. virtual void drawLinearSliderThumb (Graphics& g,
  42691. int x, int y,
  42692. int width, int height,
  42693. float sliderPos,
  42694. float minSliderPos,
  42695. float maxSliderPos,
  42696. const Slider::SliderStyle style,
  42697. Slider& slider);
  42698. virtual int getSliderThumbRadius (Slider& slider);
  42699. virtual void drawRotarySlider (Graphics& g,
  42700. int x, int y,
  42701. int width, int height,
  42702. float sliderPosProportional,
  42703. float rotaryStartAngle,
  42704. float rotaryEndAngle,
  42705. Slider& slider);
  42706. virtual Button* createSliderButton (bool isIncrement);
  42707. virtual Label* createSliderTextBox (Slider& slider);
  42708. virtual ImageEffectFilter* getSliderEffect();
  42709. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  42710. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  42711. virtual Button* createFilenameComponentBrowseButton (const String& text);
  42712. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  42713. ComboBox* filenameBox, Button* browseButton);
  42714. virtual void drawCornerResizer (Graphics& g,
  42715. int w, int h,
  42716. bool isMouseOver,
  42717. bool isMouseDragging);
  42718. virtual void drawResizableFrame (Graphics& g,
  42719. int w, int h,
  42720. const BorderSize& borders);
  42721. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  42722. const BorderSize& border,
  42723. ResizableWindow& window);
  42724. virtual void drawResizableWindowBorder (Graphics& g,
  42725. int w, int h,
  42726. const BorderSize& border,
  42727. ResizableWindow& window);
  42728. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  42729. Graphics& g, int w, int h,
  42730. int titleSpaceX, int titleSpaceW,
  42731. const Image* icon,
  42732. bool drawTitleTextOnLeft);
  42733. virtual Button* createDocumentWindowButton (int buttonType);
  42734. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  42735. int titleBarX, int titleBarY,
  42736. int titleBarW, int titleBarH,
  42737. Button* minimiseButton,
  42738. Button* maximiseButton,
  42739. Button* closeButton,
  42740. bool positionTitleBarButtonsOnLeft);
  42741. virtual int getDefaultMenuBarHeight();
  42742. virtual DropShadower* createDropShadowerForComponent (Component* component);
  42743. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  42744. int w, int h,
  42745. bool isVerticalBar,
  42746. bool isMouseOver,
  42747. bool isMouseDragging);
  42748. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  42749. const String& text,
  42750. const Justification& position,
  42751. GroupComponent& group);
  42752. virtual void createTabButtonShape (Path& p,
  42753. int width, int height,
  42754. int tabIndex,
  42755. const String& text,
  42756. Button& button,
  42757. TabbedButtonBar::Orientation orientation,
  42758. bool isMouseOver,
  42759. bool isMouseDown,
  42760. bool isFrontTab);
  42761. virtual void fillTabButtonShape (Graphics& g,
  42762. const Path& path,
  42763. const Colour& preferredBackgroundColour,
  42764. int tabIndex,
  42765. const String& text,
  42766. Button& button,
  42767. TabbedButtonBar::Orientation orientation,
  42768. bool isMouseOver,
  42769. bool isMouseDown,
  42770. bool isFrontTab);
  42771. virtual void drawTabButtonText (Graphics& g,
  42772. int x, int y, int w, int h,
  42773. const Colour& preferredBackgroundColour,
  42774. int tabIndex,
  42775. const String& text,
  42776. Button& button,
  42777. TabbedButtonBar::Orientation orientation,
  42778. bool isMouseOver,
  42779. bool isMouseDown,
  42780. bool isFrontTab);
  42781. virtual int getTabButtonOverlap (int tabDepth);
  42782. virtual int getTabButtonSpaceAroundImage();
  42783. virtual int getTabButtonBestWidth (int tabIndex,
  42784. const String& text,
  42785. int tabDepth,
  42786. Button& button);
  42787. virtual void drawTabButton (Graphics& g,
  42788. int w, int h,
  42789. const Colour& preferredColour,
  42790. int tabIndex,
  42791. const String& text,
  42792. Button& button,
  42793. TabbedButtonBar::Orientation orientation,
  42794. bool isMouseOver,
  42795. bool isMouseDown,
  42796. bool isFrontTab);
  42797. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  42798. int w, int h,
  42799. TabbedButtonBar& tabBar,
  42800. TabbedButtonBar::Orientation orientation);
  42801. virtual Button* createTabBarExtrasButton();
  42802. virtual void drawImageButton (Graphics& g, Image* image,
  42803. int imageX, int imageY, int imageW, int imageH,
  42804. const Colour& overlayColour,
  42805. float imageOpacity,
  42806. ImageButton& button);
  42807. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  42808. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  42809. int width, int height,
  42810. bool isMouseOver, bool isMouseDown,
  42811. int columnFlags);
  42812. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  42813. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  42814. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  42815. bool isMouseOver, bool isMouseDown,
  42816. ToolbarItemComponent& component);
  42817. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  42818. const String& text, ToolbarItemComponent& component);
  42819. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  42820. bool isOpen, int width, int height);
  42821. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  42822. PropertyComponent& component);
  42823. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  42824. PropertyComponent& component);
  42825. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  42826. void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  42827. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  42828. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  42829. /**
  42830. */
  42831. virtual void playAlertSound();
  42832. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  42833. static void drawGlassSphere (Graphics& g,
  42834. float x, float y,
  42835. float diameter,
  42836. const Colour& colour,
  42837. float outlineThickness) throw();
  42838. static void drawGlassPointer (Graphics& g,
  42839. float x, float y,
  42840. float diameter,
  42841. const Colour& colour, float outlineThickness,
  42842. int direction) throw();
  42843. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  42844. static void drawGlassLozenge (Graphics& g,
  42845. float x, float y,
  42846. float width, float height,
  42847. const Colour& colour,
  42848. float outlineThickness,
  42849. float cornerSize,
  42850. bool flatOnLeft, bool flatOnRight,
  42851. bool flatOnTop, bool flatOnBottom) throw();
  42852. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  42853. private:
  42854. friend JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  42855. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  42856. Array <int> colourIds;
  42857. Array <Colour> colours;
  42858. // default typeface names
  42859. String defaultSans, defaultSerif, defaultFixed;
  42860. ScopedPointer<Drawable> folderImage, documentImage;
  42861. void drawShinyButtonShape (Graphics& g,
  42862. float x, float y, float w, float h, float maxCornerSize,
  42863. const Colour& baseColour,
  42864. float strokeWidth,
  42865. bool flatOnLeft,
  42866. bool flatOnRight,
  42867. bool flatOnTop,
  42868. bool flatOnBottom) throw();
  42869. // This has been deprecated - see the new parameter list..
  42870. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  42871. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  42872. };
  42873. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  42874. /*** End of inlined file: juce_LookAndFeel.h ***/
  42875. #endif
  42876. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  42877. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  42878. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  42879. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  42880. /**
  42881. The original Juce look-and-feel.
  42882. */
  42883. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  42884. {
  42885. public:
  42886. /** Creates the default JUCE look and feel. */
  42887. OldSchoolLookAndFeel();
  42888. /** Destructor. */
  42889. virtual ~OldSchoolLookAndFeel();
  42890. /** Draws the lozenge-shaped background for a standard button. */
  42891. virtual void drawButtonBackground (Graphics& g,
  42892. Button& button,
  42893. const Colour& backgroundColour,
  42894. bool isMouseOverButton,
  42895. bool isButtonDown);
  42896. /** Draws the contents of a standard ToggleButton. */
  42897. virtual void drawToggleButton (Graphics& g,
  42898. ToggleButton& button,
  42899. bool isMouseOverButton,
  42900. bool isButtonDown);
  42901. virtual void drawTickBox (Graphics& g,
  42902. Component& component,
  42903. float x, float y, float w, float h,
  42904. bool ticked,
  42905. bool isEnabled,
  42906. bool isMouseOverButton,
  42907. bool isButtonDown);
  42908. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  42909. int width, int height,
  42910. double progress, const String& textToShow);
  42911. virtual void drawScrollbarButton (Graphics& g,
  42912. ScrollBar& scrollbar,
  42913. int width, int height,
  42914. int buttonDirection,
  42915. bool isScrollbarVertical,
  42916. bool isMouseOverButton,
  42917. bool isButtonDown);
  42918. virtual void drawScrollbar (Graphics& g,
  42919. ScrollBar& scrollbar,
  42920. int x, int y,
  42921. int width, int height,
  42922. bool isScrollbarVertical,
  42923. int thumbStartPosition,
  42924. int thumbSize,
  42925. bool isMouseOver,
  42926. bool isMouseDown);
  42927. virtual ImageEffectFilter* getScrollbarEffect();
  42928. virtual void drawTextEditorOutline (Graphics& g,
  42929. int width, int height,
  42930. TextEditor& textEditor);
  42931. /** Fills the background of a popup menu component. */
  42932. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  42933. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  42934. bool isMouseOverBar,
  42935. MenuBarComponent& menuBar);
  42936. virtual void drawComboBox (Graphics& g, int width, int height,
  42937. bool isButtonDown,
  42938. int buttonX, int buttonY,
  42939. int buttonW, int buttonH,
  42940. ComboBox& box);
  42941. virtual const Font getComboBoxFont (ComboBox& box);
  42942. virtual void drawLinearSlider (Graphics& g,
  42943. int x, int y,
  42944. int width, int height,
  42945. float sliderPos,
  42946. float minSliderPos,
  42947. float maxSliderPos,
  42948. const Slider::SliderStyle style,
  42949. Slider& slider);
  42950. virtual int getSliderThumbRadius (Slider& slider);
  42951. virtual Button* createSliderButton (bool isIncrement);
  42952. virtual ImageEffectFilter* getSliderEffect();
  42953. virtual void drawCornerResizer (Graphics& g,
  42954. int w, int h,
  42955. bool isMouseOver,
  42956. bool isMouseDragging);
  42957. virtual Button* createDocumentWindowButton (int buttonType);
  42958. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  42959. int titleBarX, int titleBarY,
  42960. int titleBarW, int titleBarH,
  42961. Button* minimiseButton,
  42962. Button* maximiseButton,
  42963. Button* closeButton,
  42964. bool positionTitleBarButtonsOnLeft);
  42965. private:
  42966. DropShadowEffect scrollbarShadow;
  42967. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  42968. };
  42969. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  42970. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  42971. #endif
  42972. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  42973. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  42974. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  42975. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  42976. /**
  42977. A menu bar component.
  42978. @see MenuBarModel
  42979. */
  42980. class JUCE_API MenuBarComponent : public Component,
  42981. private MenuBarModel::Listener,
  42982. private Timer
  42983. {
  42984. public:
  42985. /** Creates a menu bar.
  42986. @param model the model object to use to control this bar. You can
  42987. pass 0 into this if you like, and set the model later
  42988. using the setModel() method
  42989. */
  42990. MenuBarComponent (MenuBarModel* model);
  42991. /** Destructor. */
  42992. ~MenuBarComponent();
  42993. /** Changes the model object to use to control the bar.
  42994. This can be 0, in which case the bar will be empty. Don't delete the object
  42995. that is passed-in while it's still being used by this MenuBar.
  42996. */
  42997. void setModel (MenuBarModel* newModel);
  42998. /** Returns the current menu bar model being used.
  42999. */
  43000. MenuBarModel* getModel() const throw();
  43001. /** Pops up one of the menu items.
  43002. This lets you manually open one of the menus - it could be triggered by a
  43003. key shortcut, for example.
  43004. */
  43005. void showMenu (int menuIndex);
  43006. /** @internal */
  43007. void paint (Graphics& g);
  43008. /** @internal */
  43009. void resized();
  43010. /** @internal */
  43011. void mouseEnter (const MouseEvent& e);
  43012. /** @internal */
  43013. void mouseExit (const MouseEvent& e);
  43014. /** @internal */
  43015. void mouseDown (const MouseEvent& e);
  43016. /** @internal */
  43017. void mouseDrag (const MouseEvent& e);
  43018. /** @internal */
  43019. void mouseUp (const MouseEvent& e);
  43020. /** @internal */
  43021. void mouseMove (const MouseEvent& e);
  43022. /** @internal */
  43023. void handleCommandMessage (int commandId);
  43024. /** @internal */
  43025. bool keyPressed (const KeyPress& key);
  43026. /** @internal */
  43027. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  43028. /** @internal */
  43029. void menuCommandInvoked (MenuBarModel* menuBarModel,
  43030. const ApplicationCommandTarget::InvocationInfo& info);
  43031. private:
  43032. class AsyncCallback;
  43033. friend class AsyncCallback;
  43034. MenuBarModel* model;
  43035. StringArray menuNames;
  43036. Array <int> xPositions;
  43037. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  43038. int lastMouseX, lastMouseY;
  43039. int getItemAt (int x, int y);
  43040. void setItemUnderMouse (int index);
  43041. void setOpenItem (int index);
  43042. void updateItemUnderMouse (int x, int y);
  43043. void timerCallback();
  43044. void repaintMenuItem (int index);
  43045. void menuDismissed (int topLevelIndex, int itemId);
  43046. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  43047. };
  43048. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  43049. /*** End of inlined file: juce_MenuBarComponent.h ***/
  43050. #endif
  43051. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  43052. #endif
  43053. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  43054. #endif
  43055. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  43056. #endif
  43057. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  43058. #endif
  43059. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  43060. #endif
  43061. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  43062. #endif
  43063. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  43064. /*** Start of inlined file: juce_LassoComponent.h ***/
  43065. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  43066. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  43067. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  43068. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  43069. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  43070. /** Manages a list of selectable items.
  43071. Use one of these to keep a track of things that the user has highlighted, like
  43072. icons or things in a list.
  43073. The class is templated so that you can use it to hold either a set of pointers
  43074. to objects, or a set of ID numbers or handles, for cases where each item may
  43075. not always have a corresponding object.
  43076. To be informed when items are selected/deselected, register a ChangeListener with
  43077. this object.
  43078. @see SelectableObject
  43079. */
  43080. template <class SelectableItemType>
  43081. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  43082. {
  43083. public:
  43084. typedef SelectableItemType ItemType;
  43085. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  43086. /** Creates an empty set. */
  43087. SelectedItemSet()
  43088. {
  43089. }
  43090. /** Creates a set based on an array of items. */
  43091. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  43092. : selectedItems (items)
  43093. {
  43094. }
  43095. /** Creates a copy of another set. */
  43096. SelectedItemSet (const SelectedItemSet& other)
  43097. : selectedItems (other.selectedItems)
  43098. {
  43099. }
  43100. /** Creates a copy of another set. */
  43101. SelectedItemSet& operator= (const SelectedItemSet& other)
  43102. {
  43103. if (selectedItems != other.selectedItems)
  43104. {
  43105. selectedItems = other.selectedItems;
  43106. changed();
  43107. }
  43108. return *this;
  43109. }
  43110. /** Destructor. */
  43111. ~SelectedItemSet()
  43112. {
  43113. }
  43114. /** Clears any other currently selected items, and selects this item.
  43115. If this item is already the only thing selected, no change notification
  43116. will be sent out.
  43117. @see addToSelection, addToSelectionBasedOnModifiers
  43118. */
  43119. void selectOnly (ParameterType item)
  43120. {
  43121. if (isSelected (item))
  43122. {
  43123. for (int i = selectedItems.size(); --i >= 0;)
  43124. {
  43125. if (selectedItems.getUnchecked(i) != item)
  43126. {
  43127. deselect (selectedItems.getUnchecked(i));
  43128. i = jmin (i, selectedItems.size());
  43129. }
  43130. }
  43131. }
  43132. else
  43133. {
  43134. deselectAll();
  43135. changed();
  43136. selectedItems.add (item);
  43137. itemSelected (item);
  43138. }
  43139. }
  43140. /** Selects an item.
  43141. If the item is already selected, no change notification will be sent out.
  43142. @see selectOnly, addToSelectionBasedOnModifiers
  43143. */
  43144. void addToSelection (ParameterType item)
  43145. {
  43146. if (! isSelected (item))
  43147. {
  43148. changed();
  43149. selectedItems.add (item);
  43150. itemSelected (item);
  43151. }
  43152. }
  43153. /** Selects or deselects an item.
  43154. This will use the modifier keys to decide whether to deselect other items
  43155. first.
  43156. So if the shift key is held down, the item will be added without deselecting
  43157. anything (same as calling addToSelection() )
  43158. If no modifiers are down, the current selection will be cleared first (same
  43159. as calling selectOnly() )
  43160. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  43161. so it'll be added to the set unless it's already there, in which case it'll be
  43162. deselected.
  43163. If the items that you're selecting can also be dragged, you may need to use the
  43164. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  43165. subtleties of this kind of usage.
  43166. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  43167. */
  43168. void addToSelectionBasedOnModifiers (ParameterType item,
  43169. const ModifierKeys& modifiers)
  43170. {
  43171. if (modifiers.isShiftDown())
  43172. {
  43173. addToSelection (item);
  43174. }
  43175. else if (modifiers.isCommandDown())
  43176. {
  43177. if (isSelected (item))
  43178. deselect (item);
  43179. else
  43180. addToSelection (item);
  43181. }
  43182. else
  43183. {
  43184. selectOnly (item);
  43185. }
  43186. }
  43187. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  43188. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  43189. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  43190. makes it easy to handle multiple-selection of sets of objects that can also
  43191. be dragged.
  43192. For example, if you have several items already selected, and you click on
  43193. one of them (without dragging), then you'd expect this to deselect the other, and
  43194. just select the item you clicked on. But if you had clicked on this item and
  43195. dragged it, you'd have expected them all to stay selected.
  43196. When you call this method, you'll need to store the boolean result, because the
  43197. addToSelectionOnMouseUp() method will need to be know this value.
  43198. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  43199. */
  43200. bool addToSelectionOnMouseDown (ParameterType item,
  43201. const ModifierKeys& modifiers)
  43202. {
  43203. if (isSelected (item))
  43204. {
  43205. return ! modifiers.isPopupMenu();
  43206. }
  43207. else
  43208. {
  43209. addToSelectionBasedOnModifiers (item, modifiers);
  43210. return false;
  43211. }
  43212. }
  43213. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  43214. Call this during a mouseUp callback, when you have previously called the
  43215. addToSelectionOnMouseDown() method during your mouseDown event.
  43216. See addToSelectionOnMouseDown() for more info
  43217. @param item the item to select (or deselect)
  43218. @param modifiers the modifiers from the mouse-up event
  43219. @param wasItemDragged true if your item was dragged during the mouse click
  43220. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  43221. back from the addToSelectionOnMouseDown() call that you
  43222. should have made during the matching mouseDown event
  43223. */
  43224. void addToSelectionOnMouseUp (ParameterType item,
  43225. const ModifierKeys& modifiers,
  43226. const bool wasItemDragged,
  43227. const bool resultOfMouseDownSelectMethod)
  43228. {
  43229. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  43230. addToSelectionBasedOnModifiers (item, modifiers);
  43231. }
  43232. /** Deselects an item. */
  43233. void deselect (ParameterType item)
  43234. {
  43235. const int i = selectedItems.indexOf (item);
  43236. if (i >= 0)
  43237. {
  43238. changed();
  43239. itemDeselected (selectedItems.remove (i));
  43240. }
  43241. }
  43242. /** Deselects all items. */
  43243. void deselectAll()
  43244. {
  43245. if (selectedItems.size() > 0)
  43246. {
  43247. changed();
  43248. for (int i = selectedItems.size(); --i >= 0;)
  43249. {
  43250. itemDeselected (selectedItems.remove (i));
  43251. i = jmin (i, selectedItems.size());
  43252. }
  43253. }
  43254. }
  43255. /** Returns the number of currently selected items.
  43256. @see getSelectedItem
  43257. */
  43258. int getNumSelected() const throw()
  43259. {
  43260. return selectedItems.size();
  43261. }
  43262. /** Returns one of the currently selected items.
  43263. Returns 0 if the index is out-of-range.
  43264. @see getNumSelected
  43265. */
  43266. SelectableItemType getSelectedItem (const int index) const throw()
  43267. {
  43268. return selectedItems [index];
  43269. }
  43270. /** True if this item is currently selected. */
  43271. bool isSelected (ParameterType item) const throw()
  43272. {
  43273. return selectedItems.contains (item);
  43274. }
  43275. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  43276. /** Can be overridden to do special handling when an item is selected.
  43277. For example, if the item is an object, you might want to call it and tell
  43278. it that it's being selected.
  43279. */
  43280. virtual void itemSelected (SelectableItemType item) { (void) item; }
  43281. /** Can be overridden to do special handling when an item is deselected.
  43282. For example, if the item is an object, you might want to call it and tell
  43283. it that it's being deselected.
  43284. */
  43285. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  43286. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  43287. */
  43288. void changed (const bool synchronous = false)
  43289. {
  43290. if (synchronous)
  43291. sendSynchronousChangeMessage();
  43292. else
  43293. sendChangeMessage();
  43294. }
  43295. private:
  43296. Array <SelectableItemType> selectedItems;
  43297. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  43298. };
  43299. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  43300. /*** End of inlined file: juce_SelectedItemSet.h ***/
  43301. /**
  43302. A class used by the LassoComponent to manage the things that it selects.
  43303. This allows the LassoComponent to find out which items are within the lasso,
  43304. and to change the list of selected items.
  43305. @see LassoComponent, SelectedItemSet
  43306. */
  43307. template <class SelectableItemType>
  43308. class LassoSource
  43309. {
  43310. public:
  43311. /** Destructor. */
  43312. virtual ~LassoSource() {}
  43313. /** Returns the set of items that lie within a given lassoable region.
  43314. Your implementation of this method must find all the relevent items that lie
  43315. within the given rectangle. and add them to the itemsFound array.
  43316. The co-ordinates are relative to the top-left of the lasso component's parent
  43317. component. (i.e. they are the same as the size and position of the lasso
  43318. component itself).
  43319. */
  43320. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  43321. const Rectangle<int>& area) = 0;
  43322. /** Returns the SelectedItemSet that the lasso should update.
  43323. This set will be continuously updated by the LassoComponent as it gets
  43324. dragged around, so make sure that you've got a ChangeListener attached to
  43325. the set so that your UI objects will know when the selection changes and
  43326. be able to update themselves appropriately.
  43327. */
  43328. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  43329. };
  43330. /**
  43331. A component that acts as a rectangular selection region, which you drag with
  43332. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  43333. To use one of these:
  43334. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  43335. component, and call its beginLasso() method, giving it a
  43336. suitable LassoSource object that it can use to find out which items are in
  43337. the active area.
  43338. - Each time your parent component gets a mouseDrag event, call dragLasso()
  43339. to update the lasso's position - it will use its LassoSource to calculate and
  43340. update the current selection.
  43341. - After the drag has finished and you get a mouseUp callback, you should call
  43342. endLasso() to clean up. This will make the lasso component invisible, and you
  43343. can remove it from the parent component, or delete it.
  43344. The class takes into account the modifier keys that are being held down while
  43345. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  43346. be added to the original selection; if ctrl or command is pressed, they will be
  43347. xor'ed with any previously selected items.
  43348. @see LassoSource, SelectedItemSet
  43349. */
  43350. template <class SelectableItemType>
  43351. class LassoComponent : public Component
  43352. {
  43353. public:
  43354. /** Creates a Lasso component.
  43355. The fill colour is used to fill the lasso'ed rectangle, and the outline
  43356. colour is used to draw a line around its edge.
  43357. */
  43358. explicit LassoComponent (const int outlineThickness_ = 1)
  43359. : source (0),
  43360. outlineThickness (outlineThickness_)
  43361. {
  43362. }
  43363. /** Destructor. */
  43364. ~LassoComponent()
  43365. {
  43366. }
  43367. /** Call this in your mouseDown event, to initialise a drag.
  43368. Pass in a suitable LassoSource object which the lasso will use to find
  43369. the items and change the selection.
  43370. After using this method to initialise the lasso, repeatedly call dragLasso()
  43371. in your component's mouseDrag callback.
  43372. @see dragLasso, endLasso, LassoSource
  43373. */
  43374. void beginLasso (const MouseEvent& e,
  43375. LassoSource <SelectableItemType>* const lassoSource)
  43376. {
  43377. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  43378. jassert (lassoSource != 0); // the source can't be null!
  43379. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  43380. source = lassoSource;
  43381. if (lassoSource != 0)
  43382. originalSelection = lassoSource->getLassoSelection().getItemArray();
  43383. setSize (0, 0);
  43384. dragStartPos = e.getMouseDownPosition();
  43385. }
  43386. /** Call this in your mouseDrag event, to update the lasso's position.
  43387. This must be repeatedly calling when the mouse is dragged, after you've
  43388. first initialised the lasso with beginLasso().
  43389. This method takes into account the modifier keys that are being held down, so
  43390. if shift is pressed, then the lassoed items will be added to any that were
  43391. previously selected; if ctrl or command is pressed, then they will be xor'ed
  43392. with previously selected items.
  43393. @see beginLasso, endLasso
  43394. */
  43395. void dragLasso (const MouseEvent& e)
  43396. {
  43397. if (source != 0)
  43398. {
  43399. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  43400. setVisible (true);
  43401. Array <SelectableItemType> itemsInLasso;
  43402. source->findLassoItemsInArea (itemsInLasso, getBounds());
  43403. if (e.mods.isShiftDown())
  43404. {
  43405. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  43406. itemsInLasso.addArray (originalSelection);
  43407. }
  43408. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  43409. {
  43410. Array <SelectableItemType> originalMinusNew (originalSelection);
  43411. originalMinusNew.removeValuesIn (itemsInLasso);
  43412. itemsInLasso.removeValuesIn (originalSelection);
  43413. itemsInLasso.addArray (originalMinusNew);
  43414. }
  43415. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  43416. }
  43417. }
  43418. /** Call this in your mouseUp event, after the lasso has been dragged.
  43419. @see beginLasso, dragLasso
  43420. */
  43421. void endLasso()
  43422. {
  43423. source = 0;
  43424. originalSelection.clear();
  43425. setVisible (false);
  43426. }
  43427. /** A set of colour IDs to use to change the colour of various aspects of the label.
  43428. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43429. methods.
  43430. Note that you can also use the constants from TextEditor::ColourIds to change the
  43431. colour of the text editor that is opened when a label is editable.
  43432. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43433. */
  43434. enum ColourIds
  43435. {
  43436. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  43437. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  43438. };
  43439. /** @internal */
  43440. void paint (Graphics& g)
  43441. {
  43442. g.fillAll (findColour (lassoFillColourId));
  43443. g.setColour (findColour (lassoOutlineColourId));
  43444. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  43445. // this suggests that you've left a lasso comp lying around after the
  43446. // mouse drag has finished.. Be careful to call endLasso() when you get a
  43447. // mouse-up event.
  43448. jassert (isMouseButtonDownAnywhere());
  43449. }
  43450. /** @internal */
  43451. bool hitTest (int, int) { return false; }
  43452. private:
  43453. Array <SelectableItemType> originalSelection;
  43454. LassoSource <SelectableItemType>* source;
  43455. int outlineThickness;
  43456. Point<int> dragStartPos;
  43457. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  43458. };
  43459. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  43460. /*** End of inlined file: juce_LassoComponent.h ***/
  43461. #endif
  43462. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  43463. #endif
  43464. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  43465. #endif
  43466. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  43467. /*** Start of inlined file: juce_MouseInputSource.h ***/
  43468. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  43469. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  43470. class MouseInputSourceInternal;
  43471. /**
  43472. Represents a linear source of mouse events from a mouse device or individual finger
  43473. in a multi-touch environment.
  43474. Each MouseEvent object contains a reference to the MouseInputSource that generated
  43475. it. In an environment with a single mouse for input, all events will come from the
  43476. same source, but in a multi-touch system, there may be multiple MouseInputSource
  43477. obects active, each representing a stream of events coming from a particular finger.
  43478. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  43479. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  43480. the only events that can happen between a mouseDown and its corresponding mouseUp are
  43481. mouseDrags, etc.
  43482. When there are multiple touches arriving from multiple MouseInputSources, their
  43483. event streams may arrive in an interleaved order, so you should use the getIndex()
  43484. method to find out which finger each event came from.
  43485. @see MouseEvent
  43486. */
  43487. class JUCE_API MouseInputSource
  43488. {
  43489. public:
  43490. /** Creates a MouseInputSource.
  43491. You should never actually create a MouseInputSource in your own code - the
  43492. library takes care of managing these objects.
  43493. */
  43494. MouseInputSource (int index, bool isMouseDevice);
  43495. /** Destructor. */
  43496. ~MouseInputSource();
  43497. /** Returns true if this object represents a normal desk-based mouse device. */
  43498. bool isMouse() const;
  43499. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  43500. bool isTouch() const;
  43501. /** Returns true if this source has an on-screen pointer that can hover over
  43502. items without clicking them.
  43503. */
  43504. bool canHover() const;
  43505. /** Returns true if this source may have a scroll wheel. */
  43506. bool hasMouseWheel() const;
  43507. /** Returns this source's index in the global list of possible sources.
  43508. If the system only has a single mouse, there will only be a single MouseInputSource
  43509. with an index of 0.
  43510. If the system supports multi-touch input, then the index will represent a finger
  43511. number, starting from 0. When the first touch event begins, it will have finger
  43512. number 0, and then if a second touch happens while the first is still down, it
  43513. will have index 1, etc.
  43514. */
  43515. int getIndex() const;
  43516. /** Returns true if this device is currently being pressed. */
  43517. bool isDragging() const;
  43518. /** Returns the last-known screen position of this source. */
  43519. const Point<int> getScreenPosition() const;
  43520. /** Returns a set of modifiers that indicate which buttons are currently
  43521. held down on this device.
  43522. */
  43523. const ModifierKeys getCurrentModifiers() const;
  43524. /** Returns the component that was last known to be under this pointer. */
  43525. Component* getComponentUnderMouse() const;
  43526. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  43527. This is asynchronous - the event will occur on the message thread.
  43528. */
  43529. void triggerFakeMove() const;
  43530. /** Returns the number of clicks that should be counted as belonging to the
  43531. current mouse event.
  43532. So the mouse is currently down and it's the second click of a double-click, this
  43533. will return 2.
  43534. */
  43535. int getNumberOfMultipleClicks() const throw();
  43536. /** Returns the time at which the last mouse-down occurred. */
  43537. const Time getLastMouseDownTime() const throw();
  43538. /** Returns the screen position at which the last mouse-down occurred. */
  43539. const Point<int> getLastMouseDownPosition() const throw();
  43540. /** Returns true if this mouse is currently down, and if it has been dragged more
  43541. than a couple of pixels from the place it was pressed.
  43542. */
  43543. bool hasMouseMovedSignificantlySincePressed() const throw();
  43544. /** Returns true if this input source uses a visible mouse cursor. */
  43545. bool hasMouseCursor() const throw();
  43546. /** Changes the mouse cursor, (if there is one). */
  43547. void showMouseCursor (const MouseCursor& cursor);
  43548. /** Hides the mouse cursor (if there is one). */
  43549. void hideCursor();
  43550. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  43551. void revealCursor();
  43552. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  43553. void forceMouseCursorUpdate();
  43554. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  43555. bool canDoUnboundedMovement() const throw();
  43556. /** Allows the mouse to move beyond the edges of the screen.
  43557. Calling this method when the mouse button is currently pressed will remove the cursor
  43558. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  43559. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  43560. can be used for things like custom slider controls or dragging objects around, where
  43561. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  43562. The unbounded mode is automatically turned off when the mouse button is released, or
  43563. it can be turned off explicitly by calling this method again.
  43564. @param isEnabled whether to turn this mode on or off
  43565. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  43566. hidden; if true, it will only be hidden when it
  43567. is moved beyond the edge of the screen
  43568. */
  43569. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  43570. /** @internal */
  43571. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  43572. /** @internal */
  43573. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  43574. private:
  43575. friend class Desktop;
  43576. friend class ComponentPeer;
  43577. friend class MouseInputSourceInternal;
  43578. ScopedPointer<MouseInputSourceInternal> pimpl;
  43579. static const Point<int> getCurrentMousePosition();
  43580. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  43581. };
  43582. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  43583. /*** End of inlined file: juce_MouseInputSource.h ***/
  43584. #endif
  43585. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  43586. #endif
  43587. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  43588. #endif
  43589. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  43590. #endif
  43591. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  43592. #endif
  43593. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  43594. #endif
  43595. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  43596. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  43597. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  43598. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  43599. /**
  43600. A parallelogram defined by three RelativePoint positions.
  43601. @see RelativePoint, RelativeCoordinate
  43602. */
  43603. class JUCE_API RelativeParallelogram
  43604. {
  43605. public:
  43606. RelativeParallelogram();
  43607. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  43608. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  43609. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  43610. ~RelativeParallelogram();
  43611. void resolveThreePoints (Point<float>* points, Expression::EvaluationContext* coordFinder) const;
  43612. void resolveFourCorners (Point<float>* points, Expression::EvaluationContext* coordFinder) const;
  43613. const Rectangle<float> getBounds (Expression::EvaluationContext* coordFinder) const;
  43614. void getPath (Path& path, Expression::EvaluationContext* coordFinder) const;
  43615. const AffineTransform resetToPerpendicular (Expression::EvaluationContext* coordFinder);
  43616. bool isDynamic() const;
  43617. bool operator== (const RelativeParallelogram& other) const throw();
  43618. bool operator!= (const RelativeParallelogram& other) const throw();
  43619. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  43620. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  43621. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) throw();
  43622. RelativePoint topLeft, topRight, bottomLeft;
  43623. };
  43624. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  43625. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  43626. #endif
  43627. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  43628. #endif
  43629. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  43630. /*** Start of inlined file: juce_RelativePointPath.h ***/
  43631. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  43632. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  43633. class DrawablePath;
  43634. /**
  43635. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  43636. One of these paths can be converted into a Path object for drawing and manipulation, but
  43637. unlike a Path, its points can be dynamic instead of just fixed.
  43638. @see RelativePoint, RelativeCoordinate
  43639. */
  43640. class JUCE_API RelativePointPath
  43641. {
  43642. public:
  43643. RelativePointPath();
  43644. RelativePointPath (const RelativePointPath& other);
  43645. explicit RelativePointPath (const Path& path);
  43646. ~RelativePointPath();
  43647. bool operator== (const RelativePointPath& other) const throw();
  43648. bool operator!= (const RelativePointPath& other) const throw();
  43649. /** Resolves this points in this path and adds them to a normal Path object. */
  43650. void createPath (Path& path, Expression::EvaluationContext* coordFinder) const;
  43651. /** Returns true if the path contains any non-fixed points. */
  43652. bool containsAnyDynamicPoints() const;
  43653. /** Quickly swaps the contents of this path with another. */
  43654. void swapWith (RelativePointPath& other) throw();
  43655. /** The types of element that may be contained in this path.
  43656. @see RelativePointPath::ElementBase
  43657. */
  43658. enum ElementType
  43659. {
  43660. nullElement,
  43661. startSubPathElement,
  43662. closeSubPathElement,
  43663. lineToElement,
  43664. quadraticToElement,
  43665. cubicToElement
  43666. };
  43667. /** Base class for the elements that make up a RelativePointPath.
  43668. */
  43669. class JUCE_API ElementBase
  43670. {
  43671. public:
  43672. ElementBase (ElementType type);
  43673. virtual ~ElementBase() {}
  43674. virtual const ValueTree createTree() const = 0;
  43675. virtual void addToPath (Path& path, Expression::EvaluationContext* coordFinder) const = 0;
  43676. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  43677. virtual ElementBase* clone() const = 0;
  43678. bool isDynamic();
  43679. const ElementType type;
  43680. private:
  43681. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  43682. };
  43683. class JUCE_API StartSubPath : public ElementBase
  43684. {
  43685. public:
  43686. StartSubPath (const RelativePoint& pos);
  43687. const ValueTree createTree() const;
  43688. void addToPath (Path& path, Expression::EvaluationContext* coordFinder) const;
  43689. RelativePoint* getControlPoints (int& numPoints);
  43690. ElementBase* clone() const;
  43691. RelativePoint startPos;
  43692. private:
  43693. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  43694. };
  43695. class JUCE_API CloseSubPath : public ElementBase
  43696. {
  43697. public:
  43698. CloseSubPath();
  43699. const ValueTree createTree() const;
  43700. void addToPath (Path& path, Expression::EvaluationContext* coordFinder) const;
  43701. RelativePoint* getControlPoints (int& numPoints);
  43702. ElementBase* clone() const;
  43703. private:
  43704. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  43705. };
  43706. class JUCE_API LineTo : public ElementBase
  43707. {
  43708. public:
  43709. LineTo (const RelativePoint& endPoint);
  43710. const ValueTree createTree() const;
  43711. void addToPath (Path& path, Expression::EvaluationContext* coordFinder) const;
  43712. RelativePoint* getControlPoints (int& numPoints);
  43713. ElementBase* clone() const;
  43714. RelativePoint endPoint;
  43715. private:
  43716. JUCE_DECLARE_NON_COPYABLE (LineTo);
  43717. };
  43718. class JUCE_API QuadraticTo : public ElementBase
  43719. {
  43720. public:
  43721. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  43722. const ValueTree createTree() const;
  43723. void addToPath (Path& path, Expression::EvaluationContext* coordFinder) const;
  43724. RelativePoint* getControlPoints (int& numPoints);
  43725. ElementBase* clone() const;
  43726. RelativePoint controlPoints[2];
  43727. private:
  43728. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  43729. };
  43730. class JUCE_API CubicTo : public ElementBase
  43731. {
  43732. public:
  43733. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  43734. const ValueTree createTree() const;
  43735. void addToPath (Path& path, Expression::EvaluationContext* coordFinder) const;
  43736. RelativePoint* getControlPoints (int& numPoints);
  43737. ElementBase* clone() const;
  43738. RelativePoint controlPoints[3];
  43739. private:
  43740. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  43741. };
  43742. void addElement (ElementBase* newElement);
  43743. OwnedArray <ElementBase> elements;
  43744. bool usesNonZeroWinding;
  43745. private:
  43746. class Positioner;
  43747. friend class Positioner;
  43748. bool containsDynamicPoints;
  43749. void applyTo (DrawablePath& path) const;
  43750. RelativePointPath& operator= (const RelativePointPath&);
  43751. JUCE_LEAK_DETECTOR (RelativePointPath);
  43752. };
  43753. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  43754. /*** End of inlined file: juce_RelativePointPath.h ***/
  43755. #endif
  43756. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  43757. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  43758. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  43759. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  43760. class Component;
  43761. /**
  43762. An rectangle stored as a set of RelativeCoordinate values.
  43763. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  43764. @see RelativeCoordinate, RelativePoint
  43765. */
  43766. class JUCE_API RelativeRectangle
  43767. {
  43768. public:
  43769. /** Creates a zero-size rectangle at the origin. */
  43770. RelativeRectangle();
  43771. /** Creates an absolute rectangle, relative to the origin. */
  43772. explicit RelativeRectangle (const Rectangle<float>& rect);
  43773. /** Creates a rectangle from four coordinates. */
  43774. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  43775. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  43776. /** Creates a rectangle from a stringified representation.
  43777. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  43778. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  43779. RelativeCoordinate class.
  43780. @see toString
  43781. */
  43782. explicit RelativeRectangle (const String& stringVersion);
  43783. bool operator== (const RelativeRectangle& other) const throw();
  43784. bool operator!= (const RelativeRectangle& other) const throw();
  43785. /** Calculates the absolute position of this rectangle.
  43786. You'll need to provide a suitable Expression::EvaluationContext for looking up any coordinates that may
  43787. be needed to calculate the result.
  43788. */
  43789. const Rectangle<float> resolve (const Expression::EvaluationContext* evaluationContext) const;
  43790. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  43791. Calling this will leave any anchor points unchanged, but will set any absolute
  43792. or relative positions to whatever values are necessary to make the resultant position
  43793. match the position that is provided.
  43794. */
  43795. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* evaluationContext);
  43796. /** Returns true if this rectangle depends on any external symbols for its position.
  43797. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  43798. */
  43799. bool isDynamic() const;
  43800. /** Returns a string which represents this point.
  43801. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  43802. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  43803. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  43804. */
  43805. const String toString() const;
  43806. /** Renames a symbol if it is used by any of the coordinates.
  43807. This calls RelativeCoordinate::renameSymbolIfUsed() on the rectangle's coordinates.
  43808. */
  43809. void renameSymbolIfUsed (const String& oldName, const String& newName);
  43810. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  43811. keep it positioned with this rectangle.
  43812. */
  43813. void applyToComponent (Component& component) const;
  43814. // The actual rectangle coords...
  43815. RelativeCoordinate left, right, top, bottom;
  43816. };
  43817. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  43818. /*** End of inlined file: juce_RelativeRectangle.h ***/
  43819. #endif
  43820. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  43821. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  43822. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  43823. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  43824. /**
  43825. A PropertyComponent that contains an on/off toggle button.
  43826. This type of property component can be used if you have a boolean value to
  43827. toggle on/off.
  43828. @see PropertyComponent
  43829. */
  43830. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  43831. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  43832. {
  43833. protected:
  43834. /** Creates a button component.
  43835. If you use this constructor, you must override the getState() and setState()
  43836. methods.
  43837. @param propertyName the property name to be passed to the PropertyComponent
  43838. @param buttonTextWhenTrue the text shown in the button when the value is true
  43839. @param buttonTextWhenFalse the text shown in the button when the value is false
  43840. */
  43841. BooleanPropertyComponent (const String& propertyName,
  43842. const String& buttonTextWhenTrue,
  43843. const String& buttonTextWhenFalse);
  43844. public:
  43845. /** Creates a button component.
  43846. @param valueToControl a Value object that this property should refer to.
  43847. @param propertyName the property name to be passed to the PropertyComponent
  43848. @param buttonText the text shown in the ToggleButton component
  43849. */
  43850. BooleanPropertyComponent (const Value& valueToControl,
  43851. const String& propertyName,
  43852. const String& buttonText);
  43853. /** Destructor. */
  43854. ~BooleanPropertyComponent();
  43855. /** Called to change the state of the boolean value. */
  43856. virtual void setState (bool newState);
  43857. /** Must return the current value of the property. */
  43858. virtual bool getState() const;
  43859. /** @internal */
  43860. void paint (Graphics& g);
  43861. /** @internal */
  43862. void refresh();
  43863. /** @internal */
  43864. void buttonClicked (Button*);
  43865. private:
  43866. ToggleButton button;
  43867. String onText, offText;
  43868. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  43869. };
  43870. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  43871. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  43872. #endif
  43873. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  43874. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  43875. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  43876. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  43877. /**
  43878. A PropertyComponent that contains a button.
  43879. This type of property component can be used if you need a button to trigger some
  43880. kind of action.
  43881. @see PropertyComponent
  43882. */
  43883. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  43884. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  43885. {
  43886. public:
  43887. /** Creates a button component.
  43888. @param propertyName the property name to be passed to the PropertyComponent
  43889. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  43890. */
  43891. ButtonPropertyComponent (const String& propertyName,
  43892. bool triggerOnMouseDown);
  43893. /** Destructor. */
  43894. ~ButtonPropertyComponent();
  43895. /** Called when the user clicks the button.
  43896. */
  43897. virtual void buttonClicked() = 0;
  43898. /** Returns the string that should be displayed in the button.
  43899. If you need to change this string, call refresh() to update the component.
  43900. */
  43901. virtual const String getButtonText() const = 0;
  43902. /** @internal */
  43903. void refresh();
  43904. /** @internal */
  43905. void buttonClicked (Button*);
  43906. private:
  43907. TextButton button;
  43908. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  43909. };
  43910. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  43911. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  43912. #endif
  43913. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  43914. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  43915. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  43916. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  43917. /**
  43918. A PropertyComponent that shows its value as a combo box.
  43919. This type of property component contains a list of options and has a
  43920. combo box to choose one.
  43921. Your subclass's constructor must add some strings to the choices StringArray
  43922. and these are shown in the list.
  43923. The getIndex() method will be called to find out which option is the currently
  43924. selected one. If you call refresh() it will call getIndex() to check whether
  43925. the value has changed, and will update the combo box if needed.
  43926. If the user selects a different item from the list, setIndex() will be
  43927. called to let your class process this.
  43928. @see PropertyComponent, PropertyPanel
  43929. */
  43930. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  43931. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  43932. {
  43933. protected:
  43934. /** Creates the component.
  43935. Your subclass's constructor must add a list of options to the choices
  43936. member variable.
  43937. */
  43938. ChoicePropertyComponent (const String& propertyName);
  43939. public:
  43940. /** Creates the component.
  43941. @param valueToControl the value that the combo box will read and control
  43942. @param propertyName the name of the property
  43943. @param choices the list of possible values that the drop-down list will contain
  43944. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  43945. These are the values that will be read and written to the
  43946. valueToControl value. This array must contain the same number of items
  43947. as the choices array
  43948. */
  43949. ChoicePropertyComponent (const Value& valueToControl,
  43950. const String& propertyName,
  43951. const StringArray& choices,
  43952. const Array <var>& correspondingValues);
  43953. /** Destructor. */
  43954. ~ChoicePropertyComponent();
  43955. /** Called when the user selects an item from the combo box.
  43956. Your subclass must use this callback to update the value that this component
  43957. represents. The index is the index of the chosen item in the choices
  43958. StringArray.
  43959. */
  43960. virtual void setIndex (int newIndex);
  43961. /** Returns the index of the item that should currently be shown.
  43962. This is the index of the item in the choices StringArray that will be
  43963. shown.
  43964. */
  43965. virtual int getIndex() const;
  43966. /** Returns the list of options. */
  43967. const StringArray& getChoices() const;
  43968. /** @internal */
  43969. void refresh();
  43970. /** @internal */
  43971. void comboBoxChanged (ComboBox*);
  43972. protected:
  43973. /** The list of options that will be shown in the combo box.
  43974. Your subclass must populate this array in its constructor. If any empty
  43975. strings are added, these will be replaced with horizontal separators (see
  43976. ComboBox::addSeparator() for more info).
  43977. */
  43978. StringArray choices;
  43979. private:
  43980. ComboBox comboBox;
  43981. bool isCustomClass;
  43982. class RemapperValueSource;
  43983. void createComboBox();
  43984. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  43985. };
  43986. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  43987. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  43988. #endif
  43989. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  43990. #endif
  43991. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  43992. #endif
  43993. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  43994. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  43995. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  43996. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  43997. /**
  43998. A PropertyComponent that shows its value as a slider.
  43999. @see PropertyComponent, Slider
  44000. */
  44001. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  44002. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  44003. {
  44004. protected:
  44005. /** Creates the property component.
  44006. The ranges, interval and skew factor are passed to the Slider component.
  44007. If you need to customise the slider in other ways, your constructor can
  44008. access the slider member variable and change it directly.
  44009. */
  44010. SliderPropertyComponent (const String& propertyName,
  44011. double rangeMin,
  44012. double rangeMax,
  44013. double interval,
  44014. double skewFactor = 1.0);
  44015. public:
  44016. /** Creates the property component.
  44017. The ranges, interval and skew factor are passed to the Slider component.
  44018. If you need to customise the slider in other ways, your constructor can
  44019. access the slider member variable and change it directly.
  44020. */
  44021. SliderPropertyComponent (const Value& valueToControl,
  44022. const String& propertyName,
  44023. double rangeMin,
  44024. double rangeMax,
  44025. double interval,
  44026. double skewFactor = 1.0);
  44027. /** Destructor. */
  44028. ~SliderPropertyComponent();
  44029. /** Called when the user moves the slider to change its value.
  44030. Your subclass must use this method to update whatever item this property
  44031. represents.
  44032. */
  44033. virtual void setValue (double newValue);
  44034. /** Returns the value that the slider should show. */
  44035. virtual double getValue() const;
  44036. /** @internal */
  44037. void refresh();
  44038. /** @internal */
  44039. void sliderValueChanged (Slider*);
  44040. protected:
  44041. /** The slider component being used in this component.
  44042. Your subclass has access to this in case it needs to customise it in some way.
  44043. */
  44044. Slider slider;
  44045. private:
  44046. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  44047. };
  44048. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  44049. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  44050. #endif
  44051. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  44052. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  44053. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  44054. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  44055. /**
  44056. A PropertyComponent that shows its value as editable text.
  44057. @see PropertyComponent
  44058. */
  44059. class JUCE_API TextPropertyComponent : public PropertyComponent
  44060. {
  44061. protected:
  44062. /** Creates a text property component.
  44063. The maxNumChars is used to set the length of string allowable, and isMultiLine
  44064. sets whether the text editor allows carriage returns.
  44065. @see TextEditor
  44066. */
  44067. TextPropertyComponent (const String& propertyName,
  44068. int maxNumChars,
  44069. bool isMultiLine);
  44070. public:
  44071. /** Creates a text property component.
  44072. The maxNumChars is used to set the length of string allowable, and isMultiLine
  44073. sets whether the text editor allows carriage returns.
  44074. @see TextEditor
  44075. */
  44076. TextPropertyComponent (const Value& valueToControl,
  44077. const String& propertyName,
  44078. int maxNumChars,
  44079. bool isMultiLine);
  44080. /** Destructor. */
  44081. ~TextPropertyComponent();
  44082. /** Called when the user edits the text.
  44083. Your subclass must use this callback to change the value of whatever item
  44084. this property component represents.
  44085. */
  44086. virtual void setText (const String& newText);
  44087. /** Returns the text that should be shown in the text editor.
  44088. */
  44089. virtual const String getText() const;
  44090. /** @internal */
  44091. void refresh();
  44092. /** @internal */
  44093. void textWasEdited();
  44094. private:
  44095. ScopedPointer<Label> textEditor;
  44096. void createEditor (int maxNumChars, bool isMultiLine);
  44097. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  44098. };
  44099. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  44100. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  44101. #endif
  44102. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  44103. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  44104. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  44105. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  44106. #if JUCE_WINDOWS || DOXYGEN
  44107. /**
  44108. A Windows-specific class that can create and embed an ActiveX control inside
  44109. itself.
  44110. To use it, create one of these, put it in place and make sure it's visible in a
  44111. window, then use createControl() to instantiate an ActiveX control. The control
  44112. will then be moved and resized to follow the movements of this component.
  44113. Of course, since the control is a heavyweight window, it'll obliterate any
  44114. juce components that may overlap this component, but that's life.
  44115. */
  44116. class JUCE_API ActiveXControlComponent : public Component
  44117. {
  44118. public:
  44119. /** Create an initially-empty container. */
  44120. ActiveXControlComponent();
  44121. /** Destructor. */
  44122. ~ActiveXControlComponent();
  44123. /** Tries to create an ActiveX control and embed it in this peer.
  44124. The peer controlIID is a pointer to an IID structure - it's treated
  44125. as a void* because when including the Juce headers, you might not always
  44126. have included windows.h first, in which case IID wouldn't be defined.
  44127. e.g. @code
  44128. const IID myIID = __uuidof (QTControl);
  44129. myControlComp->createControl (&myIID);
  44130. @endcode
  44131. */
  44132. bool createControl (const void* controlIID);
  44133. /** Deletes the ActiveX control, if one has been created.
  44134. */
  44135. void deleteControl();
  44136. /** Returns true if a control is currently in use. */
  44137. bool isControlOpen() const throw() { return control != 0; }
  44138. /** Does a QueryInterface call on the embedded control object.
  44139. This allows you to cast the control to whatever type of COM object you need.
  44140. The iid parameter is a pointer to an IID structure - it's treated
  44141. as a void* because when including the Juce headers, you might not always
  44142. have included windows.h first, in which case IID wouldn't be defined, but
  44143. you should just pass a pointer to an IID.
  44144. e.g. @code
  44145. const IID iid = __uuidof (IOleWindow);
  44146. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  44147. if (oleWindow != 0)
  44148. {
  44149. HWND hwnd;
  44150. oleWindow->GetWindow (&hwnd);
  44151. ...
  44152. oleWindow->Release();
  44153. }
  44154. @endcode
  44155. */
  44156. void* queryInterface (const void* iid) const;
  44157. /** Set this to false to stop mouse events being allowed through to the control.
  44158. */
  44159. void setMouseEventsAllowed (bool eventsCanReachControl);
  44160. /** Returns true if mouse events are allowed to get through to the control.
  44161. */
  44162. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  44163. /** @internal */
  44164. void paint (Graphics& g);
  44165. /** @internal */
  44166. void* originalWndProc;
  44167. private:
  44168. class Pimpl;
  44169. friend class Pimpl;
  44170. friend class ScopedPointer <Pimpl>;
  44171. ScopedPointer <Pimpl> control;
  44172. bool mouseEventsAllowed;
  44173. void setControlBounds (const Rectangle<int>& bounds) const;
  44174. void setControlVisible (bool b) const;
  44175. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  44176. };
  44177. #endif
  44178. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  44179. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  44180. #endif
  44181. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  44182. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  44183. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  44184. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  44185. /**
  44186. A component containing controls to let the user change the audio settings of
  44187. an AudioDeviceManager object.
  44188. Very easy to use - just create one of these and show it to the user.
  44189. @see AudioDeviceManager
  44190. */
  44191. class JUCE_API AudioDeviceSelectorComponent : public Component,
  44192. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44193. public ButtonListener,
  44194. public ChangeListener
  44195. {
  44196. public:
  44197. /** Creates the component.
  44198. If your app needs only output channels, you might ask for a maximum of 0 input
  44199. channels, and the component won't display any options for choosing the input
  44200. channels. And likewise if you're doing an input-only app.
  44201. @param deviceManager the device manager that this component should control
  44202. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  44203. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  44204. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  44205. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  44206. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  44207. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  44208. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  44209. treated as a set of separate mono channels.
  44210. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  44211. are shown, with an "advanced" button that shows the rest of them
  44212. */
  44213. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  44214. const int minAudioInputChannels,
  44215. const int maxAudioInputChannels,
  44216. const int minAudioOutputChannels,
  44217. const int maxAudioOutputChannels,
  44218. const bool showMidiInputOptions,
  44219. const bool showMidiOutputSelector,
  44220. const bool showChannelsAsStereoPairs,
  44221. const bool hideAdvancedOptionsWithButton);
  44222. /** Destructor */
  44223. ~AudioDeviceSelectorComponent();
  44224. /** @internal */
  44225. void resized();
  44226. /** @internal */
  44227. void comboBoxChanged (ComboBox*);
  44228. /** @internal */
  44229. void buttonClicked (Button*);
  44230. /** @internal */
  44231. void changeListenerCallback (ChangeBroadcaster*);
  44232. /** @internal */
  44233. void childBoundsChanged (Component*);
  44234. private:
  44235. AudioDeviceManager& deviceManager;
  44236. ScopedPointer<ComboBox> deviceTypeDropDown;
  44237. ScopedPointer<Label> deviceTypeDropDownLabel;
  44238. ScopedPointer<Component> audioDeviceSettingsComp;
  44239. String audioDeviceSettingsCompType;
  44240. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  44241. const bool showChannelsAsStereoPairs;
  44242. const bool hideAdvancedOptionsWithButton;
  44243. class MidiInputSelectorComponentListBox;
  44244. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  44245. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  44246. ScopedPointer<ComboBox> midiOutputSelector;
  44247. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  44248. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  44249. };
  44250. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  44251. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  44252. #endif
  44253. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  44254. /*** Start of inlined file: juce_BubbleComponent.h ***/
  44255. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  44256. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  44257. /**
  44258. A component for showing a message or other graphics inside a speech-bubble-shaped
  44259. outline, pointing at a location on the screen.
  44260. This is a base class that just draws and positions the bubble shape, but leaves
  44261. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  44262. that draws a text message.
  44263. To use it, create your subclass, then either add it to a parent component or
  44264. put it on the desktop with addToDesktop (0), use setPosition() to
  44265. resize and position it, then make it visible.
  44266. @see BubbleMessageComponent
  44267. */
  44268. class JUCE_API BubbleComponent : public Component
  44269. {
  44270. protected:
  44271. /** Creates a BubbleComponent.
  44272. Your subclass will need to implement the getContentSize() and paintContent()
  44273. methods to draw the bubble's contents.
  44274. */
  44275. BubbleComponent();
  44276. public:
  44277. /** Destructor. */
  44278. ~BubbleComponent();
  44279. /** A list of permitted placements for the bubble, relative to the co-ordinates
  44280. at which it should be pointing.
  44281. @see setAllowedPlacement
  44282. */
  44283. enum BubblePlacement
  44284. {
  44285. above = 1,
  44286. below = 2,
  44287. left = 4,
  44288. right = 8
  44289. };
  44290. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  44291. point at which it's pointing.
  44292. By default when setPosition() is called, the bubble will place itself either
  44293. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  44294. the values in BubblePlacement to restrict this choice.
  44295. E.g. if you only want your bubble to appear above or below the target area,
  44296. use setAllowedPlacement (above | below);
  44297. @see BubblePlacement
  44298. */
  44299. void setAllowedPlacement (int newPlacement);
  44300. /** Moves and resizes the bubble to point at a given component.
  44301. This will resize the bubble to fit its content, then find a position for it
  44302. so that it's next to, but doesn't overlap the given component.
  44303. It'll put itself either above, below, or to the side of the component depending
  44304. on where there's the most space, honouring any restrictions that were set
  44305. with setAllowedPlacement().
  44306. */
  44307. void setPosition (Component* componentToPointTo);
  44308. /** Moves and resizes the bubble to point at a given point.
  44309. This will resize the bubble to fit its content, then position it
  44310. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  44311. are relative to either the bubble component's parent component if it has one, or
  44312. they are screen co-ordinates if not.
  44313. It'll put itself either above, below, or to the side of this point, depending
  44314. on where there's the most space, honouring any restrictions that were set
  44315. with setAllowedPlacement().
  44316. */
  44317. void setPosition (int arrowTipX,
  44318. int arrowTipY);
  44319. /** Moves and resizes the bubble to point at a given rectangle.
  44320. This will resize the bubble to fit its content, then find a position for it
  44321. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  44322. co-ordinates are relative to either the bubble component's parent component
  44323. if it has one, or they are screen co-ordinates if not.
  44324. It'll put itself either above, below, or to the side of the component depending
  44325. on where there's the most space, honouring any restrictions that were set
  44326. with setAllowedPlacement().
  44327. */
  44328. void setPosition (const Rectangle<int>& rectangleToPointTo);
  44329. protected:
  44330. /** Subclasses should override this to return the size of the content they
  44331. want to draw inside the bubble.
  44332. */
  44333. virtual void getContentSize (int& width, int& height) = 0;
  44334. /** Subclasses should override this to draw their bubble's contents.
  44335. The graphics object's clip region and the dimensions passed in here are
  44336. set up to paint just the rectangle inside the bubble.
  44337. */
  44338. virtual void paintContent (Graphics& g, int width, int height) = 0;
  44339. public:
  44340. /** @internal */
  44341. void paint (Graphics& g);
  44342. private:
  44343. Rectangle<int> content;
  44344. int side, allowablePlacements;
  44345. float arrowTipX, arrowTipY;
  44346. DropShadowEffect shadow;
  44347. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  44348. };
  44349. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  44350. /*** End of inlined file: juce_BubbleComponent.h ***/
  44351. #endif
  44352. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  44353. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  44354. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  44355. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  44356. /**
  44357. A speech-bubble component that displays a short message.
  44358. This can be used to show a message with the tail of the speech bubble
  44359. pointing to a particular component or location on the screen.
  44360. @see BubbleComponent
  44361. */
  44362. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  44363. private Timer
  44364. {
  44365. public:
  44366. /** Creates a bubble component.
  44367. After creating one a BubbleComponent, do the following:
  44368. - add it to an appropriate parent component, or put it on the
  44369. desktop with Component::addToDesktop (0).
  44370. - use the showAt() method to show a message.
  44371. - it will make itself invisible after it times-out (and can optionally
  44372. also delete itself), or you can reuse it somewhere else by calling
  44373. showAt() again.
  44374. */
  44375. BubbleMessageComponent (int fadeOutLengthMs = 150);
  44376. /** Destructor. */
  44377. ~BubbleMessageComponent();
  44378. /** Shows a message bubble at a particular position.
  44379. This shows the bubble with its stem pointing to the given location
  44380. (co-ordinates being relative to its parent component).
  44381. For details about exactly how it decides where to position itself, see
  44382. BubbleComponent::updatePosition().
  44383. @param x the x co-ordinate of end of the bubble's tail
  44384. @param y the y co-ordinate of end of the bubble's tail
  44385. @param message the text to display
  44386. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  44387. from its parent compnent. If this is 0 or less, it
  44388. will stay there until manually removed.
  44389. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  44390. mouse button is pressed (anywhere on the screen)
  44391. @param deleteSelfAfterUse if true, then the component will delete itself after
  44392. it becomes invisible
  44393. */
  44394. void showAt (int x, int y,
  44395. const String& message,
  44396. int numMillisecondsBeforeRemoving,
  44397. bool removeWhenMouseClicked = true,
  44398. bool deleteSelfAfterUse = false);
  44399. /** Shows a message bubble next to a particular component.
  44400. This shows the bubble with its stem pointing at the given component.
  44401. For details about exactly how it decides where to position itself, see
  44402. BubbleComponent::updatePosition().
  44403. @param component the component that you want to point at
  44404. @param message the text to display
  44405. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  44406. from its parent compnent. If this is 0 or less, it
  44407. will stay there until manually removed.
  44408. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  44409. mouse button is pressed (anywhere on the screen)
  44410. @param deleteSelfAfterUse if true, then the component will delete itself after
  44411. it becomes invisible
  44412. */
  44413. void showAt (Component* component,
  44414. const String& message,
  44415. int numMillisecondsBeforeRemoving,
  44416. bool removeWhenMouseClicked = true,
  44417. bool deleteSelfAfterUse = false);
  44418. /** @internal */
  44419. void getContentSize (int& w, int& h);
  44420. /** @internal */
  44421. void paintContent (Graphics& g, int w, int h);
  44422. /** @internal */
  44423. void timerCallback();
  44424. private:
  44425. int fadeOutLength, mouseClickCounter;
  44426. TextLayout textLayout;
  44427. int64 expiryTime;
  44428. bool deleteAfterUse;
  44429. void init (int numMillisecondsBeforeRemoving,
  44430. bool removeWhenMouseClicked,
  44431. bool deleteSelfAfterUse);
  44432. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  44433. };
  44434. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  44435. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  44436. #endif
  44437. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  44438. /*** Start of inlined file: juce_ColourSelector.h ***/
  44439. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  44440. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  44441. /**
  44442. A component that lets the user choose a colour.
  44443. This shows RGB sliders and a colourspace that the user can pick colours from.
  44444. This class is also a ChangeBroadcaster, so listeners can register to be told
  44445. when the colour changes.
  44446. */
  44447. class JUCE_API ColourSelector : public Component,
  44448. public ChangeBroadcaster,
  44449. protected SliderListener
  44450. {
  44451. public:
  44452. /** Options for the type of selector to show. These are passed into the constructor. */
  44453. enum ColourSelectorOptions
  44454. {
  44455. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  44456. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  44457. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  44458. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  44459. };
  44460. /** Creates a ColourSelector object.
  44461. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  44462. which of the selector's features should be visible.
  44463. The edgeGap value specifies the amount of space to leave around the edge.
  44464. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  44465. colourspace and hue selector components.
  44466. */
  44467. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  44468. int edgeGap = 4,
  44469. int gapAroundColourSpaceComponent = 7);
  44470. /** Destructor. */
  44471. ~ColourSelector();
  44472. /** Returns the colour that the user has currently selected.
  44473. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  44474. register to be told when the colour changes.
  44475. @see setCurrentColour
  44476. */
  44477. const Colour getCurrentColour() const;
  44478. /** Changes the colour that is currently being shown.
  44479. */
  44480. void setCurrentColour (const Colour& newColour);
  44481. /** Tells the selector how many preset colour swatches you want to have on the component.
  44482. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  44483. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  44484. their values.
  44485. */
  44486. virtual int getNumSwatches() const;
  44487. /** Called by the selector to find out the colour of one of the swatches.
  44488. Your subclass should return the colour of the swatch with the given index.
  44489. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  44490. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  44491. their values.
  44492. */
  44493. virtual const Colour getSwatchColour (int index) const;
  44494. /** Called by the selector when the user puts a new colour into one of the swatches.
  44495. Your subclass should change the colour of the swatch with the given index.
  44496. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  44497. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  44498. their values.
  44499. */
  44500. virtual void setSwatchColour (int index, const Colour& newColour) const;
  44501. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  44502. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44503. methods.
  44504. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44505. */
  44506. enum ColourIds
  44507. {
  44508. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  44509. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  44510. };
  44511. private:
  44512. class ColourSpaceView;
  44513. class HueSelectorComp;
  44514. class SwatchComponent;
  44515. friend class ColourSpaceView;
  44516. friend class ScopedPointer<ColourSpaceView>;
  44517. friend class HueSelectorComp;
  44518. friend class ScopedPointer<HueSelectorComp>;
  44519. Colour colour;
  44520. float h, s, v;
  44521. ScopedPointer<Slider> sliders[4];
  44522. ScopedPointer<ColourSpaceView> colourSpace;
  44523. ScopedPointer<HueSelectorComp> hueSelector;
  44524. OwnedArray <SwatchComponent> swatchComponents;
  44525. const int flags;
  44526. int edgeGap;
  44527. Rectangle<int> previewArea;
  44528. void setHue (float newH);
  44529. void setSV (float newS, float newV);
  44530. void updateHSV();
  44531. void update();
  44532. void sliderValueChanged (Slider*);
  44533. void paint (Graphics& g);
  44534. void resized();
  44535. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  44536. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  44537. // This constructor is here temporarily to prevent old code compiling, because the parameters
  44538. // have changed - if you get an error here, update your code to use the new constructor instead..
  44539. ColourSelector (bool);
  44540. #endif
  44541. };
  44542. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  44543. /*** End of inlined file: juce_ColourSelector.h ***/
  44544. #endif
  44545. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  44546. #endif
  44547. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  44548. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  44549. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  44550. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  44551. /**
  44552. A component that displays a piano keyboard, whose notes can be clicked on.
  44553. This component will mimic a physical midi keyboard, showing the current state of
  44554. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  44555. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  44556. Another feature is that the computer keyboard can also be used to play notes. By
  44557. default it maps the top two rows of a standard querty keyboard to the notes, but
  44558. these can be remapped if needed. It will only respond to keypresses when it has
  44559. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  44560. The component is also a ChangeBroadcaster, so if you want to be informed when the
  44561. keyboard is scrolled, you can register a ChangeListener for callbacks.
  44562. @see MidiKeyboardState
  44563. */
  44564. class JUCE_API MidiKeyboardComponent : public Component,
  44565. public MidiKeyboardStateListener,
  44566. public ChangeBroadcaster,
  44567. private Timer,
  44568. private AsyncUpdater
  44569. {
  44570. public:
  44571. /** The direction of the keyboard.
  44572. @see setOrientation
  44573. */
  44574. enum Orientation
  44575. {
  44576. horizontalKeyboard,
  44577. verticalKeyboardFacingLeft,
  44578. verticalKeyboardFacingRight,
  44579. };
  44580. /** Creates a MidiKeyboardComponent.
  44581. @param state the midi keyboard model that this component will represent
  44582. @param orientation whether the keyboard is horizonal or vertical
  44583. */
  44584. MidiKeyboardComponent (MidiKeyboardState& state,
  44585. Orientation orientation);
  44586. /** Destructor. */
  44587. ~MidiKeyboardComponent();
  44588. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  44589. on the component.
  44590. Values are 0 to 1.0, where 1.0 is the heaviest.
  44591. @see setMidiChannel
  44592. */
  44593. void setVelocity (float velocity, bool useMousePositionForVelocity);
  44594. /** Changes the midi channel number that will be used for events triggered by clicking
  44595. on the component.
  44596. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  44597. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  44598. Although this is the channel used for outgoing events, the component can display
  44599. incoming events from more than one channel - see setMidiChannelsToDisplay()
  44600. @see setVelocity
  44601. */
  44602. void setMidiChannel (int midiChannelNumber);
  44603. /** Returns the midi channel that the keyboard is using for midi messages.
  44604. @see setMidiChannel
  44605. */
  44606. int getMidiChannel() const throw() { return midiChannel; }
  44607. /** Sets a mask to indicate which incoming midi channels should be represented by
  44608. key movements.
  44609. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  44610. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  44611. in this mask, the on-screen keys will also go down.
  44612. By default, this mask is set to 0xffff (all channels displayed).
  44613. @see setMidiChannel
  44614. */
  44615. void setMidiChannelsToDisplay (int midiChannelMask);
  44616. /** Returns the current set of midi channels represented by the component.
  44617. This is the value that was set with setMidiChannelsToDisplay().
  44618. */
  44619. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  44620. /** Changes the width used to draw the white keys. */
  44621. void setKeyWidth (float widthInPixels);
  44622. /** Returns the width that was set by setKeyWidth(). */
  44623. float getKeyWidth() const throw() { return keyWidth; }
  44624. /** Changes the keyboard's current direction. */
  44625. void setOrientation (Orientation newOrientation);
  44626. /** Returns the keyboard's current direction. */
  44627. const Orientation getOrientation() const throw() { return orientation; }
  44628. /** Sets the range of midi notes that the keyboard will be limited to.
  44629. By default the range is 0 to 127 (inclusive), but you can limit this if you
  44630. only want a restricted set of the keys to be shown.
  44631. Note that the values here are inclusive and must be between 0 and 127.
  44632. */
  44633. void setAvailableRange (int lowestNote,
  44634. int highestNote);
  44635. /** Returns the first note in the available range.
  44636. @see setAvailableRange
  44637. */
  44638. int getRangeStart() const throw() { return rangeStart; }
  44639. /** Returns the last note in the available range.
  44640. @see setAvailableRange
  44641. */
  44642. int getRangeEnd() const throw() { return rangeEnd; }
  44643. /** If the keyboard extends beyond the size of the component, this will scroll
  44644. it to show the given key at the start.
  44645. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  44646. base class to send a callback to any ChangeListeners that have been registered.
  44647. */
  44648. void setLowestVisibleKey (int noteNumber);
  44649. /** Returns the number of the first key shown in the component.
  44650. @see setLowestVisibleKey
  44651. */
  44652. int getLowestVisibleKey() const throw() { return firstKey; }
  44653. /** Returns the length of the black notes.
  44654. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  44655. */
  44656. int getBlackNoteLength() const throw() { return blackNoteLength; }
  44657. /** If set to true, then scroll buttons will appear at either end of the keyboard
  44658. if there are too many notes to fit them all in the component at once.
  44659. */
  44660. void setScrollButtonsVisible (bool canScroll);
  44661. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  44662. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44663. methods.
  44664. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44665. */
  44666. enum ColourIds
  44667. {
  44668. whiteNoteColourId = 0x1005000,
  44669. blackNoteColourId = 0x1005001,
  44670. keySeparatorLineColourId = 0x1005002,
  44671. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  44672. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  44673. textLabelColourId = 0x1005005,
  44674. upDownButtonBackgroundColourId = 0x1005006,
  44675. upDownButtonArrowColourId = 0x1005007
  44676. };
  44677. /** Returns the position within the component of the left-hand edge of a key.
  44678. Depending on the keyboard's orientation, this may be a horizontal or vertical
  44679. distance, in either direction.
  44680. */
  44681. int getKeyStartPosition (const int midiNoteNumber) const;
  44682. /** Deletes all key-mappings.
  44683. @see setKeyPressForNote
  44684. */
  44685. void clearKeyMappings();
  44686. /** Maps a key-press to a given note.
  44687. @param key the key that should trigger the note
  44688. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  44689. be. The actual midi note that gets played will be
  44690. this value + (12 * the current base octave). To change
  44691. the base octave, see setKeyPressBaseOctave()
  44692. */
  44693. void setKeyPressForNote (const KeyPress& key,
  44694. int midiNoteOffsetFromC);
  44695. /** Removes any key-mappings for a given note.
  44696. For a description of what the note number means, see setKeyPressForNote().
  44697. */
  44698. void removeKeyPressForNote (int midiNoteOffsetFromC);
  44699. /** Changes the base note above which key-press-triggered notes are played.
  44700. The set of key-mappings that trigger notes can be moved up and down to cover
  44701. the entire scale using this method.
  44702. The value passed in is an octave number between 0 and 10 (inclusive), and
  44703. indicates which C is the base note to which the key-mapped notes are
  44704. relative.
  44705. */
  44706. void setKeyPressBaseOctave (int newOctaveNumber);
  44707. /** This sets the octave number which is shown as the octave number for middle C.
  44708. This affects only the default implementation of getWhiteNoteText(), which
  44709. passes this octave number to MidiMessage::getMidiNoteName() in order to
  44710. get the note text. See MidiMessage::getMidiNoteName() for more info about
  44711. the parameter.
  44712. By default this value is set to 3.
  44713. @see getOctaveForMiddleC
  44714. */
  44715. void setOctaveForMiddleC (int octaveNumForMiddleC);
  44716. /** This returns the value set by setOctaveForMiddleC().
  44717. @see setOctaveForMiddleC
  44718. */
  44719. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  44720. /** @internal */
  44721. void paint (Graphics& g);
  44722. /** @internal */
  44723. void resized();
  44724. /** @internal */
  44725. void mouseMove (const MouseEvent& e);
  44726. /** @internal */
  44727. void mouseDrag (const MouseEvent& e);
  44728. /** @internal */
  44729. void mouseDown (const MouseEvent& e);
  44730. /** @internal */
  44731. void mouseUp (const MouseEvent& e);
  44732. /** @internal */
  44733. void mouseEnter (const MouseEvent& e);
  44734. /** @internal */
  44735. void mouseExit (const MouseEvent& e);
  44736. /** @internal */
  44737. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  44738. /** @internal */
  44739. void timerCallback();
  44740. /** @internal */
  44741. bool keyStateChanged (bool isKeyDown);
  44742. /** @internal */
  44743. void focusLost (FocusChangeType cause);
  44744. /** @internal */
  44745. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  44746. /** @internal */
  44747. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  44748. /** @internal */
  44749. void handleAsyncUpdate();
  44750. /** @internal */
  44751. void colourChanged();
  44752. protected:
  44753. /** Draws a white note in the given rectangle.
  44754. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  44755. currently pressed down.
  44756. When doing this, be sure to note the keyboard's orientation.
  44757. */
  44758. virtual void drawWhiteNote (int midiNoteNumber,
  44759. Graphics& g,
  44760. int x, int y, int w, int h,
  44761. bool isDown, bool isOver,
  44762. const Colour& lineColour,
  44763. const Colour& textColour);
  44764. /** Draws a black note in the given rectangle.
  44765. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  44766. currently pressed down.
  44767. When doing this, be sure to note the keyboard's orientation.
  44768. */
  44769. virtual void drawBlackNote (int midiNoteNumber,
  44770. Graphics& g,
  44771. int x, int y, int w, int h,
  44772. bool isDown, bool isOver,
  44773. const Colour& noteFillColour);
  44774. /** Allows text to be drawn on the white notes.
  44775. By default this is used to label the C in each octave, but could be used for other things.
  44776. @see setOctaveForMiddleC
  44777. */
  44778. virtual const String getWhiteNoteText (const int midiNoteNumber);
  44779. /** Draws the up and down buttons that change the base note. */
  44780. virtual void drawUpDownButton (Graphics& g, int w, int h,
  44781. const bool isMouseOver,
  44782. const bool isButtonPressed,
  44783. const bool movesOctavesUp);
  44784. /** Callback when the mouse is clicked on a key.
  44785. You could use this to do things like handle right-clicks on keys, etc.
  44786. Return true if you want the click to trigger the note, or false if you
  44787. want to handle it yourself and not have the note played.
  44788. @see mouseDraggedToKey
  44789. */
  44790. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  44791. /** Callback when the mouse is dragged from one key onto another.
  44792. @see mouseDownOnKey
  44793. */
  44794. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  44795. /** Calculates the positon of a given midi-note.
  44796. This can be overridden to create layouts with custom key-widths.
  44797. @param midiNoteNumber the note to find
  44798. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  44799. @param x the x position of the left-hand edge of the key (this method
  44800. always works in terms of a horizontal keyboard)
  44801. @param w the width of the key
  44802. */
  44803. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  44804. int& x, int& w) const;
  44805. private:
  44806. friend class MidiKeyboardUpDownButton;
  44807. MidiKeyboardState& state;
  44808. int xOffset, blackNoteLength;
  44809. float keyWidth;
  44810. Orientation orientation;
  44811. int midiChannel, midiInChannelMask;
  44812. float velocity;
  44813. int noteUnderMouse, mouseDownNote;
  44814. BigInteger keysPressed, keysCurrentlyDrawnDown;
  44815. int rangeStart, rangeEnd, firstKey;
  44816. bool canScroll, mouseDragging, useMousePositionForVelocity;
  44817. ScopedPointer<Button> scrollDown, scrollUp;
  44818. Array <KeyPress> keyPresses;
  44819. Array <int> keyPressNotes;
  44820. int keyMappingOctave;
  44821. int octaveNumForMiddleC;
  44822. static const uint8 whiteNotes[];
  44823. static const uint8 blackNotes[];
  44824. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  44825. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  44826. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  44827. void resetAnyKeysInUse();
  44828. void updateNoteUnderMouse (const Point<int>& pos);
  44829. void repaintNote (const int midiNoteNumber);
  44830. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  44831. };
  44832. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  44833. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  44834. #endif
  44835. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  44836. /*** Start of inlined file: juce_NSViewComponent.h ***/
  44837. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  44838. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  44839. #if ! DOXYGEN
  44840. class NSViewComponentInternal;
  44841. #endif
  44842. #if JUCE_MAC || DOXYGEN
  44843. /**
  44844. A Mac-specific class that can create and embed an NSView inside itself.
  44845. To use it, create one of these, put it in place and make sure it's visible in a
  44846. window, then use setView() to assign an NSView to it. The view will then be
  44847. moved and resized to follow the movements of this component.
  44848. Of course, since the view is a native object, it'll obliterate any
  44849. juce components that may overlap this component, but that's life.
  44850. */
  44851. class JUCE_API NSViewComponent : public Component
  44852. {
  44853. public:
  44854. /** Create an initially-empty container. */
  44855. NSViewComponent();
  44856. /** Destructor. */
  44857. ~NSViewComponent();
  44858. /** Assigns an NSView to this peer.
  44859. The view will be retained and released by this component for as long as
  44860. it is needed. To remove the current view, just call setView (0).
  44861. Note: a void* is used here to avoid including the cocoa headers as
  44862. part of the juce.h, but the method expects an NSView*.
  44863. */
  44864. void setView (void* nsView);
  44865. /** Returns the current NSView.
  44866. Note: a void* is returned here to avoid including the cocoa headers as
  44867. a requirement of juce.h, so you should just cast the object to an NSView*.
  44868. */
  44869. void* getView() const;
  44870. /** Resizes this component to fit the view that it contains. */
  44871. void resizeToFitView();
  44872. /** @internal */
  44873. void paint (Graphics& g);
  44874. private:
  44875. friend class NSViewComponentInternal;
  44876. ScopedPointer <NSViewComponentInternal> info;
  44877. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  44878. };
  44879. #endif
  44880. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  44881. /*** End of inlined file: juce_NSViewComponent.h ***/
  44882. #endif
  44883. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  44884. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  44885. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  44886. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  44887. // this is used to disable OpenGL, and is defined in juce_Config.h
  44888. #if JUCE_OPENGL || DOXYGEN
  44889. /**
  44890. Represents the various properties of an OpenGL bitmap format.
  44891. @see OpenGLComponent::setPixelFormat
  44892. */
  44893. class JUCE_API OpenGLPixelFormat
  44894. {
  44895. public:
  44896. /** Creates an OpenGLPixelFormat.
  44897. The default constructor just initialises the object as a simple 8-bit
  44898. RGBA format.
  44899. */
  44900. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  44901. int alphaBits = 8,
  44902. int depthBufferBits = 16,
  44903. int stencilBufferBits = 0);
  44904. OpenGLPixelFormat (const OpenGLPixelFormat&);
  44905. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  44906. bool operator== (const OpenGLPixelFormat&) const;
  44907. int redBits; /**< The number of bits per pixel to use for the red channel. */
  44908. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  44909. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  44910. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  44911. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  44912. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  44913. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  44914. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  44915. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  44916. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  44917. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  44918. /** Returns a list of all the pixel formats that can be used in this system.
  44919. A reference component is needed in case there are multiple screens with different
  44920. capabilities - in which case, the one that the component is on will be used.
  44921. */
  44922. static void getAvailablePixelFormats (Component* component,
  44923. OwnedArray <OpenGLPixelFormat>& results);
  44924. private:
  44925. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  44926. };
  44927. /**
  44928. A base class for types of OpenGL context.
  44929. An OpenGLComponent will supply its own context for drawing in its window.
  44930. */
  44931. class JUCE_API OpenGLContext
  44932. {
  44933. public:
  44934. /** Destructor. */
  44935. virtual ~OpenGLContext();
  44936. /** Makes this context the currently active one. */
  44937. virtual bool makeActive() const throw() = 0;
  44938. /** If this context is currently active, it is disactivated. */
  44939. virtual bool makeInactive() const throw() = 0;
  44940. /** Returns true if this context is currently active. */
  44941. virtual bool isActive() const throw() = 0;
  44942. /** Swaps the buffers (if the context can do this). */
  44943. virtual void swapBuffers() = 0;
  44944. /** Sets whether the context checks the vertical sync before swapping.
  44945. The value is the number of frames to allow between buffer-swapping. This is
  44946. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  44947. and greater numbers indicate that it should swap less often.
  44948. Returns true if it sets the value successfully.
  44949. */
  44950. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  44951. /** Returns the current swap-sync interval.
  44952. See setSwapInterval() for info about the value returned.
  44953. */
  44954. virtual int getSwapInterval() const = 0;
  44955. /** Returns the pixel format being used by this context. */
  44956. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  44957. /** For windowed contexts, this moves the context within the bounds of
  44958. its parent window.
  44959. */
  44960. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  44961. /** For windowed contexts, this triggers a repaint of the window.
  44962. (Not relevent on all platforms).
  44963. */
  44964. virtual void repaint() = 0;
  44965. /** Returns an OS-dependent handle to the raw GL context.
  44966. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  44967. a GLXContext.
  44968. */
  44969. virtual void* getRawContext() const throw() = 0;
  44970. /** Deletes the context.
  44971. This must only be called on the message thread, or will deadlock.
  44972. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  44973. to call any other OpenGL function afterwards.
  44974. This doesn't touch other resources, such as window handles, etc.
  44975. You'll probably never have to call this method directly.
  44976. */
  44977. virtual void deleteContext() = 0;
  44978. /** Returns the context that's currently in active use by the calling thread.
  44979. Returns 0 if there isn't an active context.
  44980. */
  44981. static OpenGLContext* getCurrentContext();
  44982. protected:
  44983. OpenGLContext() throw();
  44984. private:
  44985. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  44986. };
  44987. /**
  44988. A component that contains an OpenGL canvas.
  44989. Override this, add it to whatever component you want to, and use the renderOpenGL()
  44990. method to draw its contents.
  44991. */
  44992. class JUCE_API OpenGLComponent : public Component
  44993. {
  44994. public:
  44995. /** Used to select the type of openGL API to use, if more than one choice is available
  44996. on a particular platform.
  44997. */
  44998. enum OpenGLType
  44999. {
  45000. openGLDefault = 0,
  45001. #if JUCE_IOS
  45002. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  45003. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  45004. #endif
  45005. };
  45006. /** Creates an OpenGLComponent. */
  45007. OpenGLComponent (OpenGLType type = openGLDefault);
  45008. /** Destructor. */
  45009. ~OpenGLComponent();
  45010. /** Changes the pixel format used by this component.
  45011. @see OpenGLPixelFormat::getAvailablePixelFormats()
  45012. */
  45013. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  45014. /** Returns the pixel format that this component is currently using. */
  45015. const OpenGLPixelFormat getPixelFormat() const;
  45016. /** Specifies an OpenGL context which should be shared with the one that this
  45017. component is using.
  45018. This is an OpenGL feature that lets two contexts share their texture data.
  45019. Note that this pointer is stored by the component, and when the component
  45020. needs to recreate its internal context for some reason, the same context
  45021. will be used again to share lists. So if you pass a context in here,
  45022. don't delete the context while this component is still using it! You can
  45023. call shareWith (0) to stop this component from sharing with it.
  45024. */
  45025. void shareWith (OpenGLContext* contextToShareListsWith);
  45026. /** Returns the context that this component is sharing with.
  45027. @see shareWith
  45028. */
  45029. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  45030. /** Flips the openGL buffers over. */
  45031. void swapBuffers();
  45032. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  45033. When this is called, makeCurrentContextActive() will already have been called
  45034. for you, so you just need to draw.
  45035. */
  45036. virtual void renderOpenGL() = 0;
  45037. /** This method is called when the component creates a new OpenGL context.
  45038. A new context may be created when the component is first used, or when it
  45039. is moved to a different window, or when the window is hidden and re-shown,
  45040. etc.
  45041. You can use this callback as an opportunity to set up things like textures
  45042. that your context needs.
  45043. New contexts are created on-demand by the makeCurrentContextActive() method - so
  45044. if the context is deleted, e.g. by changing the pixel format or window, no context
  45045. will be created until the next call to makeCurrentContextActive(), which will
  45046. synchronously create one and call this method. This means that if you're using
  45047. a non-GUI thread for rendering, you can make sure this method is be called by
  45048. your renderer thread.
  45049. When this callback happens, the context will already have been made current
  45050. using the makeCurrentContextActive() method, so there's no need to call it
  45051. again in your code.
  45052. */
  45053. virtual void newOpenGLContextCreated() = 0;
  45054. /** Returns the context that will draw into this component.
  45055. This may return 0 if the component is currently invisible or hasn't currently
  45056. got a context. The context object can be deleted and a new one created during
  45057. the lifetime of this component, and there may be times when it doesn't have one.
  45058. @see newOpenGLContextCreated()
  45059. */
  45060. OpenGLContext* getCurrentContext() const throw() { return context; }
  45061. /** Makes this component the current openGL context.
  45062. You might want to use this in things like your resize() method, before calling
  45063. GL commands.
  45064. If this returns false, then the context isn't active, so you should avoid
  45065. making any calls.
  45066. This call may actually create a context if one isn't currently initialised. If
  45067. it does this, it will also synchronously call the newOpenGLContextCreated()
  45068. method to let you initialise it as necessary.
  45069. @see OpenGLContext::makeActive
  45070. */
  45071. bool makeCurrentContextActive();
  45072. /** Stops the current component being the active OpenGL context.
  45073. This is the opposite of makeCurrentContextActive()
  45074. @see OpenGLContext::makeInactive
  45075. */
  45076. void makeCurrentContextInactive();
  45077. /** Returns true if this component is the active openGL context for the
  45078. current thread.
  45079. @see OpenGLContext::isActive
  45080. */
  45081. bool isActiveContext() const throw();
  45082. /** Calls the rendering callback, and swaps the buffers afterwards.
  45083. This is called automatically by paint() when the component needs to be rendered.
  45084. It can be overridden if you need to decouple the rendering from the paint callback
  45085. and render with a custom thread.
  45086. Returns true if the operation succeeded.
  45087. */
  45088. virtual bool renderAndSwapBuffers();
  45089. /** This returns a critical section that can be used to lock the current context.
  45090. Because the context that is used by this component can change, e.g. when the
  45091. component is shown or hidden, then if you're rendering to it on a background
  45092. thread, this allows you to lock the context for the duration of your rendering
  45093. routine.
  45094. */
  45095. CriticalSection& getContextLock() throw() { return contextLock; }
  45096. /** Returns the native handle of an embedded heavyweight window, if there is one.
  45097. E.g. On windows, this will return the HWND of the sub-window containing
  45098. the opengl context, on the mac it'll be the NSOpenGLView.
  45099. */
  45100. void* getNativeWindowHandle() const;
  45101. /** Delete the context.
  45102. This can be called back on the same thread that created the context. */
  45103. void deleteContext();
  45104. /** @internal */
  45105. void paint (Graphics& g);
  45106. private:
  45107. const OpenGLType type;
  45108. class OpenGLComponentWatcher;
  45109. friend class OpenGLComponentWatcher;
  45110. friend class ScopedPointer <OpenGLComponentWatcher>;
  45111. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  45112. ScopedPointer <OpenGLContext> context;
  45113. OpenGLContext* contextToShareListsWith;
  45114. CriticalSection contextLock;
  45115. OpenGLPixelFormat preferredPixelFormat;
  45116. bool needToUpdateViewport;
  45117. OpenGLContext* createContext();
  45118. void updateContextPosition();
  45119. void internalRepaint (int x, int y, int w, int h);
  45120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  45121. };
  45122. #endif
  45123. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  45124. /*** End of inlined file: juce_OpenGLComponent.h ***/
  45125. #endif
  45126. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  45127. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  45128. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  45129. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  45130. /**
  45131. A component with a set of buttons at the top for changing between pages of
  45132. preferences.
  45133. This is just a handy way of writing a Mac-style preferences panel where you
  45134. have a row of buttons along the top for the different preference categories,
  45135. each button having an icon above its name. Clicking these will show an
  45136. appropriate prefs page below it.
  45137. You can either put one of these inside your own component, or just use the
  45138. showInDialogBox() method to show it in a window and run it modally.
  45139. To use it, just add a set of named pages with the addSettingsPage() method,
  45140. and implement the createComponentForPage() method to create suitable components
  45141. for each of these pages.
  45142. */
  45143. class JUCE_API PreferencesPanel : public Component,
  45144. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  45145. {
  45146. public:
  45147. /** Creates an empty panel.
  45148. Use addSettingsPage() to add some pages to it in your constructor.
  45149. */
  45150. PreferencesPanel();
  45151. /** Destructor. */
  45152. ~PreferencesPanel();
  45153. /** Creates a page using a set of drawables to define the page's icon.
  45154. Note that the other version of this method is much easier if you're using
  45155. an image instead of a custom drawable.
  45156. @param pageTitle the name of this preferences page - you'll need to
  45157. make sure your createComponentForPage() method creates
  45158. a suitable component when it is passed this name
  45159. @param normalIcon the drawable to display in the page's button normally
  45160. @param overIcon the drawable to display in the page's button when the mouse is over
  45161. @param downIcon the drawable to display in the page's button when the button is down
  45162. @see DrawableButton
  45163. */
  45164. void addSettingsPage (const String& pageTitle,
  45165. const Drawable* normalIcon,
  45166. const Drawable* overIcon,
  45167. const Drawable* downIcon);
  45168. /** Creates a page using a set of drawables to define the page's icon.
  45169. The other version of this method gives you more control over the icon, but this
  45170. one is much easier if you're just loading it from a file.
  45171. @param pageTitle the name of this preferences page - you'll need to
  45172. make sure your createComponentForPage() method creates
  45173. a suitable component when it is passed this name
  45174. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  45175. For this to look good, you'll probably want to use a nice
  45176. transparent png file.
  45177. @param imageDataSize the size of the image data, in bytes
  45178. */
  45179. void addSettingsPage (const String& pageTitle,
  45180. const void* imageData,
  45181. int imageDataSize);
  45182. /** Utility method to display this panel in a DialogWindow.
  45183. Calling this will create a DialogWindow containing this panel with the
  45184. given size and title, and will run it modally, returning when the user
  45185. closes the dialog box.
  45186. */
  45187. void showInDialogBox (const String& dialogTitle,
  45188. int dialogWidth,
  45189. int dialogHeight,
  45190. const Colour& backgroundColour = Colours::white);
  45191. /** Subclasses must override this to return a component for each preferences page.
  45192. The subclass should return a pointer to a new component representing the named
  45193. page, which the panel will then display.
  45194. The panel will delete the component later when the user goes to another page
  45195. or deletes the panel.
  45196. */
  45197. virtual Component* createComponentForPage (const String& pageName) = 0;
  45198. /** Changes the current page being displayed. */
  45199. void setCurrentPage (const String& pageName);
  45200. /** @internal */
  45201. void resized();
  45202. /** @internal */
  45203. void paint (Graphics& g);
  45204. /** @internal */
  45205. void buttonClicked (Button* button);
  45206. private:
  45207. String currentPageName;
  45208. ScopedPointer <Component> currentPage;
  45209. OwnedArray<DrawableButton> buttons;
  45210. int buttonSize;
  45211. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  45212. };
  45213. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  45214. /*** End of inlined file: juce_PreferencesPanel.h ***/
  45215. #endif
  45216. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  45217. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  45218. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  45219. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  45220. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  45221. // amalgamated build)
  45222. #ifndef DOXYGEN
  45223. #if JUCE_WINDOWS
  45224. typedef ActiveXControlComponent QTCompBaseClass;
  45225. #elif JUCE_MAC
  45226. typedef NSViewComponent QTCompBaseClass;
  45227. #endif
  45228. #endif
  45229. // this is used to disable QuickTime, and is defined in juce_Config.h
  45230. #if JUCE_QUICKTIME || DOXYGEN
  45231. /**
  45232. A window that can play back a QuickTime movie.
  45233. */
  45234. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  45235. {
  45236. public:
  45237. /** Creates a QuickTimeMovieComponent, initially blank.
  45238. Use the loadMovie() method to load a movie once you've added the
  45239. component to a window, (or put it on the desktop as a heavyweight window).
  45240. Loading a movie when the component isn't visible can cause problems, as
  45241. QuickTime needs a window handle to initialise properly.
  45242. */
  45243. QuickTimeMovieComponent();
  45244. /** Destructor. */
  45245. ~QuickTimeMovieComponent();
  45246. /** Returns true if QT is installed and working on this machine.
  45247. */
  45248. static bool isQuickTimeAvailable() throw();
  45249. /** Tries to load a QuickTime movie from a file into the player.
  45250. It's best to call this function once you've added the component to a window,
  45251. (or put it on the desktop as a heavyweight window). Loading a movie when the
  45252. component isn't visible can cause problems, because QuickTime needs a window
  45253. handle to do its stuff.
  45254. @param movieFile the .mov file to open
  45255. @param isControllerVisible whether to show a controller bar at the bottom
  45256. @returns true if the movie opens successfully
  45257. */
  45258. bool loadMovie (const File& movieFile,
  45259. bool isControllerVisible);
  45260. /** Tries to load a QuickTime movie from a URL into the player.
  45261. It's best to call this function once you've added the component to a window,
  45262. (or put it on the desktop as a heavyweight window). Loading a movie when the
  45263. component isn't visible can cause problems, because QuickTime needs a window
  45264. handle to do its stuff.
  45265. @param movieURL the .mov file to open
  45266. @param isControllerVisible whether to show a controller bar at the bottom
  45267. @returns true if the movie opens successfully
  45268. */
  45269. bool loadMovie (const URL& movieURL,
  45270. bool isControllerVisible);
  45271. /** Tries to load a QuickTime movie from a stream into the player.
  45272. It's best to call this function once you've added the component to a window,
  45273. (or put it on the desktop as a heavyweight window). Loading a movie when the
  45274. component isn't visible can cause problems, because QuickTime needs a window
  45275. handle to do its stuff.
  45276. @param movieStream a stream containing a .mov file. The component may try
  45277. to read the whole stream before playing, rather than
  45278. streaming from it.
  45279. @param isControllerVisible whether to show a controller bar at the bottom
  45280. @returns true if the movie opens successfully
  45281. */
  45282. bool loadMovie (InputStream* movieStream,
  45283. bool isControllerVisible);
  45284. /** Closes the movie, if one is open. */
  45285. void closeMovie();
  45286. /** Returns the movie file that is currently open.
  45287. If there isn't one, this returns File::nonexistent
  45288. */
  45289. const File getCurrentMovieFile() const;
  45290. /** Returns true if there's currently a movie open. */
  45291. bool isMovieOpen() const;
  45292. /** Returns the length of the movie, in seconds. */
  45293. double getMovieDuration() const;
  45294. /** Returns the movie's natural size, in pixels.
  45295. You can use this to resize the component to show the movie at its preferred
  45296. scale.
  45297. If no movie is loaded, the size returned will be 0 x 0.
  45298. */
  45299. void getMovieNormalSize (int& width, int& height) const;
  45300. /** This will position the component within a given area, keeping its aspect
  45301. ratio correct according to the movie's normal size.
  45302. The component will be made as large as it can go within the space, and will
  45303. be aligned according to the justification value if this means there are gaps at
  45304. the top or sides.
  45305. */
  45306. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  45307. const RectanglePlacement& placement);
  45308. /** Starts the movie playing. */
  45309. void play();
  45310. /** Stops the movie playing. */
  45311. void stop();
  45312. /** Returns true if the movie is currently playing. */
  45313. bool isPlaying() const;
  45314. /** Moves the movie's position back to the start. */
  45315. void goToStart();
  45316. /** Sets the movie's position to a given time. */
  45317. void setPosition (double seconds);
  45318. /** Returns the current play position of the movie. */
  45319. double getPosition() const;
  45320. /** Changes the movie playback rate.
  45321. A value of 1 is normal speed, greater values play it proportionately faster,
  45322. smaller values play it slower.
  45323. */
  45324. void setSpeed (float newSpeed);
  45325. /** Changes the movie's playback volume.
  45326. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  45327. */
  45328. void setMovieVolume (float newVolume);
  45329. /** Returns the movie's playback volume.
  45330. @returns the volume in the range 0 (silent) to 1.0 (full)
  45331. */
  45332. float getMovieVolume() const;
  45333. /** Tells the movie whether it should loop. */
  45334. void setLooping (bool shouldLoop);
  45335. /** Returns true if the movie is currently looping.
  45336. @see setLooping
  45337. */
  45338. bool isLooping() const;
  45339. /** True if the native QuickTime controller bar is shown in the window.
  45340. @see loadMovie
  45341. */
  45342. bool isControllerVisible() const;
  45343. /** @internal */
  45344. void paint (Graphics& g);
  45345. private:
  45346. File movieFile;
  45347. bool movieLoaded, controllerVisible, looping;
  45348. #if JUCE_WINDOWS
  45349. void parentHierarchyChanged();
  45350. void visibilityChanged();
  45351. void createControlIfNeeded();
  45352. bool isControlCreated() const;
  45353. class Pimpl;
  45354. friend class ScopedPointer <Pimpl>;
  45355. ScopedPointer <Pimpl> pimpl;
  45356. #else
  45357. void* movie;
  45358. #endif
  45359. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  45360. };
  45361. #endif
  45362. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  45363. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  45364. #endif
  45365. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  45366. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  45367. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  45368. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  45369. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  45370. /**
  45371. On Windows only, this component sits in the taskbar tray as a small icon.
  45372. To use it, just create one of these components, but don't attempt to make it
  45373. visible, add it to a parent, or put it on the desktop.
  45374. You can then call setIconImage() to create an icon for it in the taskbar.
  45375. To change the icon's tooltip, you can use setIconTooltip().
  45376. To respond to mouse-events, you can override the normal mouseDown(),
  45377. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  45378. position will not be valid, you can use this to respond to clicks. Traditionally
  45379. you'd use a left-click to show your application's window, and a right-click
  45380. to show a pop-up menu.
  45381. */
  45382. class JUCE_API SystemTrayIconComponent : public Component
  45383. {
  45384. public:
  45385. SystemTrayIconComponent();
  45386. /** Destructor. */
  45387. ~SystemTrayIconComponent();
  45388. /** Changes the image shown in the taskbar.
  45389. */
  45390. void setIconImage (const Image& newImage);
  45391. /** Changes the tooltip that Windows shows above the icon. */
  45392. void setIconTooltip (const String& tooltip);
  45393. #if JUCE_LINUX
  45394. /** @internal */
  45395. void paint (Graphics& g);
  45396. #endif
  45397. private:
  45398. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  45399. };
  45400. #endif
  45401. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  45402. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  45403. #endif
  45404. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  45405. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  45406. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  45407. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  45408. #if JUCE_WEB_BROWSER || DOXYGEN
  45409. #if ! DOXYGEN
  45410. class WebBrowserComponentInternal;
  45411. #endif
  45412. /**
  45413. A component that displays an embedded web browser.
  45414. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  45415. Windows, probably IE.
  45416. */
  45417. class JUCE_API WebBrowserComponent : public Component
  45418. {
  45419. public:
  45420. /** Creates a WebBrowserComponent.
  45421. Once it's created and visible, send the browser to a URL using goToURL().
  45422. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  45423. component is taken offscreen, it'll clear the current page
  45424. and replace it with a blank page - this can be handy to stop
  45425. the browser using resources in the background when it's not
  45426. actually being used.
  45427. */
  45428. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  45429. /** Destructor. */
  45430. ~WebBrowserComponent();
  45431. /** Sends the browser to a particular URL.
  45432. @param url the URL to go to.
  45433. @param headers an optional set of parameters to put in the HTTP header. If
  45434. you supply this, it should be a set of string in the form
  45435. "HeaderKey: HeaderValue"
  45436. @param postData an optional block of data that will be attached to the HTTP
  45437. POST request
  45438. */
  45439. void goToURL (const String& url,
  45440. const StringArray* headers = 0,
  45441. const MemoryBlock* postData = 0);
  45442. /** Stops the current page loading.
  45443. */
  45444. void stop();
  45445. /** Sends the browser back one page.
  45446. */
  45447. void goBack();
  45448. /** Sends the browser forward one page.
  45449. */
  45450. void goForward();
  45451. /** Refreshes the browser.
  45452. */
  45453. void refresh();
  45454. /** This callback is called when the browser is about to navigate
  45455. to a new location.
  45456. You can override this method to perform some action when the user
  45457. tries to go to a particular URL. To allow the operation to carry on,
  45458. return true, or return false to stop the navigation happening.
  45459. */
  45460. virtual bool pageAboutToLoad (const String& newURL);
  45461. /** @internal */
  45462. void paint (Graphics& g);
  45463. /** @internal */
  45464. void resized();
  45465. /** @internal */
  45466. void parentHierarchyChanged();
  45467. /** @internal */
  45468. void visibilityChanged();
  45469. private:
  45470. WebBrowserComponentInternal* browser;
  45471. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  45472. String lastURL;
  45473. StringArray lastHeaders;
  45474. MemoryBlock lastPostData;
  45475. void reloadLastURL();
  45476. void checkWindowAssociation();
  45477. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  45478. };
  45479. #endif
  45480. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  45481. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  45482. #endif
  45483. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  45484. #endif
  45485. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  45486. /*** Start of inlined file: juce_CallOutBox.h ***/
  45487. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  45488. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  45489. /**
  45490. A box with a small arrow that can be used as a temporary pop-up window to show
  45491. extra controls when a button or other component is clicked.
  45492. Using one of these is similar to having a popup menu attached to a button or
  45493. other component - but it looks fancier, and has an arrow that can indicate the
  45494. object that it applies to.
  45495. Normally, you'd create one of these on the stack and run it modally, e.g.
  45496. @code
  45497. void mouseUp (const MouseEvent& e)
  45498. {
  45499. MyContentComponent content;
  45500. content.setSize (300, 300);
  45501. CallOutBox callOut (content, *this, 0);
  45502. callOut.runModalLoop();
  45503. }
  45504. @endcode
  45505. The call-out will resize and position itself when the content changes size.
  45506. */
  45507. class JUCE_API CallOutBox : public Component
  45508. {
  45509. public:
  45510. /** Creates a CallOutBox.
  45511. @param contentComponent the component to display inside the call-out. This should
  45512. already have a size set (although the call-out will also
  45513. update itself when the component's size is changed later).
  45514. Obviously this component must not be deleted until the
  45515. call-out box has been deleted.
  45516. @param componentToPointTo the component that the call-out's arrow should point towards
  45517. @param parentComponent if non-zero, this is the component to add the call-out to. If
  45518. this is zero, the call-out will be added to the desktop.
  45519. */
  45520. CallOutBox (Component& contentComponent,
  45521. Component& componentToPointTo,
  45522. Component* parentComponent);
  45523. /** Destructor. */
  45524. ~CallOutBox();
  45525. /** Changes the length of the arrow. */
  45526. void setArrowSize (float newSize);
  45527. /** Updates the position and size of the box.
  45528. You shouldn't normally need to call this, unless you need more precise control over the
  45529. layout.
  45530. @param newAreaToPointTo the rectangle to make the box's arrow point to
  45531. @param newAreaToFitIn the area within which the box's position should be constrained
  45532. */
  45533. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  45534. const Rectangle<int>& newAreaToFitIn);
  45535. /** @internal */
  45536. void paint (Graphics& g);
  45537. /** @internal */
  45538. void resized();
  45539. /** @internal */
  45540. void moved();
  45541. /** @internal */
  45542. void childBoundsChanged (Component*);
  45543. /** @internal */
  45544. bool hitTest (int x, int y);
  45545. /** @internal */
  45546. void inputAttemptWhenModal();
  45547. /** @internal */
  45548. bool keyPressed (const KeyPress& key);
  45549. /** @internal */
  45550. void handleCommandMessage (int commandId);
  45551. private:
  45552. int borderSpace;
  45553. float arrowSize;
  45554. Component& content;
  45555. Path outline;
  45556. Point<float> targetPoint;
  45557. Rectangle<int> availableArea, targetArea;
  45558. Image background;
  45559. void refreshPath();
  45560. void drawCallOutBoxBackground (Graphics& g, const Path& outline, int width, int height);
  45561. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  45562. };
  45563. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  45564. /*** End of inlined file: juce_CallOutBox.h ***/
  45565. #endif
  45566. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  45567. /*** Start of inlined file: juce_ComponentPeer.h ***/
  45568. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  45569. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  45570. class ComponentBoundsConstrainer;
  45571. /**
  45572. The base class for window objects that wrap a component as a real operating
  45573. system object.
  45574. This is an abstract base class - the platform specific code contains default
  45575. implementations of it that create and manage windows.
  45576. @see Component::createNewPeer
  45577. */
  45578. class JUCE_API ComponentPeer
  45579. {
  45580. public:
  45581. /** A combination of these flags is passed to the ComponentPeer constructor. */
  45582. enum StyleFlags
  45583. {
  45584. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  45585. entry on the taskbar (ignored on MacOSX) */
  45586. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  45587. tooltip, etc. */
  45588. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  45589. through it (may not be possible on some platforms). */
  45590. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  45591. title bar and frame\. if not specified, the window will be
  45592. borderless. */
  45593. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  45594. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  45595. minimise button on it. */
  45596. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  45597. maximise button on it. */
  45598. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  45599. close button on it. */
  45600. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  45601. not be possible on all platforms). */
  45602. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  45603. do its own repainting, but only to repaint when the
  45604. performAnyPendingRepaintsNow() method is called. */
  45605. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  45606. be used for things like plugin windows, to stop them interfering
  45607. with the host's shortcut keys */
  45608. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  45609. };
  45610. /** Creates a peer.
  45611. The component is the one that we intend to represent, and the style flags are
  45612. a combination of the values in the StyleFlags enum
  45613. */
  45614. ComponentPeer (Component* component, int styleFlags);
  45615. /** Destructor. */
  45616. virtual ~ComponentPeer();
  45617. /** Returns the component being represented by this peer. */
  45618. Component* getComponent() const throw() { return component; }
  45619. /** Returns the set of style flags that were set when the window was created.
  45620. @see Component::addToDesktop
  45621. */
  45622. int getStyleFlags() const throw() { return styleFlags; }
  45623. /** Returns the raw handle to whatever kind of window is being used.
  45624. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  45625. but rememeber there's no guarantees what you'll get back.
  45626. */
  45627. virtual void* getNativeHandle() const = 0;
  45628. /** Shows or hides the window. */
  45629. virtual void setVisible (bool shouldBeVisible) = 0;
  45630. /** Changes the title of the window. */
  45631. virtual void setTitle (const String& title) = 0;
  45632. /** Moves the window without changing its size.
  45633. If the native window is contained in another window, then the co-ordinates are
  45634. relative to the parent window's origin, not the screen origin.
  45635. This should result in a callback to handleMovedOrResized().
  45636. */
  45637. virtual void setPosition (int x, int y) = 0;
  45638. /** Resizes the window without changing its position.
  45639. This should result in a callback to handleMovedOrResized().
  45640. */
  45641. virtual void setSize (int w, int h) = 0;
  45642. /** Moves and resizes the window.
  45643. If the native window is contained in another window, then the co-ordinates are
  45644. relative to the parent window's origin, not the screen origin.
  45645. This should result in a callback to handleMovedOrResized().
  45646. */
  45647. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  45648. /** Returns the current position and size of the window.
  45649. If the native window is contained in another window, then the co-ordinates are
  45650. relative to the parent window's origin, not the screen origin.
  45651. */
  45652. virtual const Rectangle<int> getBounds() const = 0;
  45653. /** Returns the x-position of this window, relative to the screen's origin. */
  45654. virtual const Point<int> getScreenPosition() const = 0;
  45655. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  45656. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  45657. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  45658. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  45659. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  45660. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  45661. /** Converts a screen area to a position relative to the top-left of this component. */
  45662. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  45663. /** Minimises the window. */
  45664. virtual void setMinimised (bool shouldBeMinimised) = 0;
  45665. /** True if the window is currently minimised. */
  45666. virtual bool isMinimised() const = 0;
  45667. /** Enable/disable fullscreen mode for the window. */
  45668. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  45669. /** True if the window is currently full-screen. */
  45670. virtual bool isFullScreen() const = 0;
  45671. /** Sets the size to restore to if fullscreen mode is turned off. */
  45672. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  45673. /** Returns the size to restore to if fullscreen mode is turned off. */
  45674. const Rectangle<int>& getNonFullScreenBounds() const throw();
  45675. /** Attempts to change the icon associated with this window.
  45676. */
  45677. virtual void setIcon (const Image& newIcon) = 0;
  45678. /** Sets a constrainer to use if the peer can resize itself.
  45679. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  45680. */
  45681. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  45682. /** Returns the current constrainer, if one has been set. */
  45683. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  45684. /** Checks if a point is in the window.
  45685. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  45686. is false, then this returns false if the point is actually inside a child of this
  45687. window.
  45688. */
  45689. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  45690. /** Returns the size of the window frame that's around this window.
  45691. Whether or not the window has a normal window frame depends on the flags
  45692. that were set when the window was created by Component::addToDesktop()
  45693. */
  45694. virtual const BorderSize getFrameSize() const = 0;
  45695. /** This is called when the window's bounds change.
  45696. A peer implementation must call this when the window is moved and resized, so that
  45697. this method can pass the message on to the component.
  45698. */
  45699. void handleMovedOrResized();
  45700. /** This is called if the screen resolution changes.
  45701. A peer implementation must call this if the monitor arrangement changes or the available
  45702. screen size changes.
  45703. */
  45704. void handleScreenSizeChange();
  45705. /** This is called to repaint the component into the given context. */
  45706. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  45707. /** Sets this window to either be always-on-top or normal.
  45708. Some kinds of window might not be able to do this, so should return false.
  45709. */
  45710. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  45711. /** Brings the window to the top, optionally also giving it focus. */
  45712. virtual void toFront (bool makeActive) = 0;
  45713. /** Moves the window to be just behind another one. */
  45714. virtual void toBehind (ComponentPeer* other) = 0;
  45715. /** Called when the window is brought to the front, either by the OS or by a call
  45716. to toFront().
  45717. */
  45718. void handleBroughtToFront();
  45719. /** True if the window has the keyboard focus. */
  45720. virtual bool isFocused() const = 0;
  45721. /** Tries to give the window keyboard focus. */
  45722. virtual void grabFocus() = 0;
  45723. /** Tells the window that text input may be required at the given position.
  45724. This may cause things like a virtual on-screen keyboard to appear, depending
  45725. on the OS.
  45726. */
  45727. virtual void textInputRequired (const Point<int>& position) = 0;
  45728. /** Called when the window gains keyboard focus. */
  45729. void handleFocusGain();
  45730. /** Called when the window loses keyboard focus. */
  45731. void handleFocusLoss();
  45732. Component* getLastFocusedSubcomponent() const throw();
  45733. /** Called when a key is pressed.
  45734. For keycode info, see the KeyPress class.
  45735. Returns true if the keystroke was used.
  45736. */
  45737. bool handleKeyPress (int keyCode,
  45738. juce_wchar textCharacter);
  45739. /** Called whenever a key is pressed or released.
  45740. Returns true if the keystroke was used.
  45741. */
  45742. bool handleKeyUpOrDown (bool isKeyDown);
  45743. /** Called whenever a modifier key is pressed or released. */
  45744. void handleModifierKeysChange();
  45745. /** Returns the currently focused TextInputTarget, or null if none is found. */
  45746. TextInputTarget* findCurrentTextInputTarget();
  45747. /** Invalidates a region of the window to be repainted asynchronously. */
  45748. virtual void repaint (const Rectangle<int>& area) = 0;
  45749. /** This can be called (from the message thread) to cause the immediate redrawing
  45750. of any areas of this window that need repainting.
  45751. You shouldn't ever really need to use this, it's mainly for special purposes
  45752. like supporting audio plugins where the host's event loop is out of our control.
  45753. */
  45754. virtual void performAnyPendingRepaintsNow() = 0;
  45755. /** Changes the window's transparency. */
  45756. virtual void setAlpha (float newAlpha) = 0;
  45757. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  45758. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  45759. void handleUserClosingWindow();
  45760. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  45761. void handleFileDragExit (const StringArray& files);
  45762. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  45763. /** Resets the masking region.
  45764. The subclass should call this every time it's about to call the handlePaint
  45765. method.
  45766. @see addMaskedRegion
  45767. */
  45768. void clearMaskedRegion();
  45769. /** Adds a rectangle to the set of areas not to paint over.
  45770. A component can call this on its peer during its paint() method, to signal
  45771. that the painting code should ignore a given region. The reason
  45772. for this is to stop embedded windows (such as OpenGL) getting painted over.
  45773. The masked region is cleared each time before a paint happens, so a component
  45774. will have to make sure it calls this every time it's painted.
  45775. */
  45776. void addMaskedRegion (int x, int y, int w, int h);
  45777. /** Returns the number of currently-active peers.
  45778. @see getPeer
  45779. */
  45780. static int getNumPeers() throw();
  45781. /** Returns one of the currently-active peers.
  45782. @see getNumPeers
  45783. */
  45784. static ComponentPeer* getPeer (int index) throw();
  45785. /** Checks if this peer object is valid.
  45786. @see getNumPeers
  45787. */
  45788. static bool isValidPeer (const ComponentPeer* peer) throw();
  45789. virtual const StringArray getAvailableRenderingEngines();
  45790. virtual int getCurrentRenderingEngine() throw();
  45791. virtual void setCurrentRenderingEngine (int index);
  45792. protected:
  45793. Component* const component;
  45794. const int styleFlags;
  45795. RectangleList maskedRegion;
  45796. Rectangle<int> lastNonFullscreenBounds;
  45797. uint32 lastPaintTime;
  45798. ComponentBoundsConstrainer* constrainer;
  45799. static void updateCurrentModifiers() throw();
  45800. private:
  45801. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  45802. Component* lastDragAndDropCompUnderMouse;
  45803. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  45804. friend class Component;
  45805. friend class Desktop;
  45806. static ComponentPeer* getPeerFor (const Component* component) throw();
  45807. void setLastDragDropTarget (Component* comp);
  45808. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  45809. };
  45810. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  45811. /*** End of inlined file: juce_ComponentPeer.h ***/
  45812. #endif
  45813. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  45814. /*** Start of inlined file: juce_DialogWindow.h ***/
  45815. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  45816. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  45817. /**
  45818. A dialog-box style window.
  45819. This class is a convenient way of creating a DocumentWindow with a close button
  45820. that can be triggered by pressing the escape key.
  45821. Any of the methods available to a DocumentWindow or ResizableWindow are also
  45822. available to this, so it can be made resizable, have a menu bar, etc.
  45823. To add items to the box, see the ResizableWindow::setContentComponent() method.
  45824. Don't add components directly to this class - always put them in a content component!
  45825. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  45826. the user clicking the close button - for more info, see the DocumentWindow
  45827. help.
  45828. @see DocumentWindow, ResizableWindow
  45829. */
  45830. class JUCE_API DialogWindow : public DocumentWindow
  45831. {
  45832. public:
  45833. /** Creates a DialogWindow.
  45834. @param name the name to give the component - this is also
  45835. the title shown at the top of the window. To change
  45836. this later, use setName()
  45837. @param backgroundColour the colour to use for filling the window's background.
  45838. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  45839. close button to be triggered
  45840. @param addToDesktop if true, the window will be automatically added to the
  45841. desktop; if false, you can use it as a child component
  45842. */
  45843. DialogWindow (const String& name,
  45844. const Colour& backgroundColour,
  45845. bool escapeKeyTriggersCloseButton,
  45846. bool addToDesktop = true);
  45847. /** Destructor.
  45848. If a content component has been set with setContentComponent(), it
  45849. will be deleted.
  45850. */
  45851. ~DialogWindow();
  45852. /** Easy way of quickly showing a dialog box containing a given component.
  45853. This will open and display a DialogWindow containing a given component, returning
  45854. when the user clicks its close button.
  45855. It returns the value that was returned by the dialog box's runModalLoop() call.
  45856. To close the dialog programatically, you should call exitModalState (returnValue) on
  45857. the DialogWindow that is created. To find a pointer to this window from your
  45858. contentComponent, you can do something like this:
  45859. @code
  45860. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  45861. if (dw != 0)
  45862. dw->exitModalState (1234);
  45863. @endcode
  45864. @param dialogTitle the dialog box's title
  45865. @param contentComponent the content component for the dialog box. Make sure
  45866. that this has been set to the size you want it to
  45867. be before calling this method. The component won't
  45868. be deleted by this call, so you can re-use it or delete
  45869. it afterwards
  45870. @param componentToCentreAround if this is non-zero, it indicates a component that
  45871. you'd like to show this dialog box in front of. See the
  45872. DocumentWindow::centreAroundComponent() method for more
  45873. info on this parameter
  45874. @param backgroundColour a colour to use for the dialog box's background colour
  45875. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  45876. close button to be triggered
  45877. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  45878. a corner resizer
  45879. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  45880. to use a border or corner resizer component. See ResizableWindow::setResizable()
  45881. */
  45882. static int showModalDialog (const String& dialogTitle,
  45883. Component* contentComponent,
  45884. Component* componentToCentreAround,
  45885. const Colour& backgroundColour,
  45886. bool escapeKeyTriggersCloseButton,
  45887. bool shouldBeResizable = false,
  45888. bool useBottomRightCornerResizer = false);
  45889. protected:
  45890. /** @internal */
  45891. void resized();
  45892. private:
  45893. bool escapeKeyTriggersCloseButton;
  45894. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  45895. };
  45896. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  45897. /*** End of inlined file: juce_DialogWindow.h ***/
  45898. #endif
  45899. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45900. #endif
  45901. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  45902. #endif
  45903. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  45904. /*** Start of inlined file: juce_SplashScreen.h ***/
  45905. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  45906. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  45907. /** A component for showing a splash screen while your app starts up.
  45908. This will automatically position itself, and delete itself when the app has
  45909. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  45910. this).
  45911. To use it, just create one of these in your JUCEApplication::initialise() method,
  45912. call its show() method and let the object delete itself later.
  45913. E.g. @code
  45914. void MyApp::initialise (const String& commandLine)
  45915. {
  45916. SplashScreen* splash = new SplashScreen();
  45917. splash->show ("welcome to my app",
  45918. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  45919. 4000, false);
  45920. .. no need to delete the splash screen - it'll do that itself.
  45921. }
  45922. @endcode
  45923. */
  45924. class JUCE_API SplashScreen : public Component,
  45925. public Timer,
  45926. private DeletedAtShutdown
  45927. {
  45928. public:
  45929. /** Creates a SplashScreen object.
  45930. After creating one of these (or your subclass of it), call one of the show()
  45931. methods to display it.
  45932. */
  45933. SplashScreen();
  45934. /** Destructor. */
  45935. ~SplashScreen();
  45936. /** Creates a SplashScreen object that will display an image.
  45937. As soon as this is called, the SplashScreen will be displayed in the centre of the
  45938. screen. This method will also dispatch any pending messages to make sure that when
  45939. it returns, the splash screen has been completely drawn, and your initialisation
  45940. code can carry on.
  45941. @param title the name to give the component
  45942. @param backgroundImage an image to draw on the component. The component's size
  45943. will be set to the size of this image, and if the image is
  45944. semi-transparent, the component will be made semi-transparent
  45945. too. This image will be deleted (or released from the ImageCache
  45946. if that's how it was created) by the splash screen object when
  45947. it is itself deleted.
  45948. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  45949. should stay visible for. If the initialisation takes longer than
  45950. this time, the splash screen will wait for it to finish before
  45951. disappearing, but if initialisation is very quick, this lets
  45952. you make sure that people get a good look at your splash.
  45953. @param useDropShadow if true, the window will have a drop shadow
  45954. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  45955. the mouse (anywhere)
  45956. */
  45957. void show (const String& title,
  45958. const Image& backgroundImage,
  45959. int minimumTimeToDisplayFor,
  45960. bool useDropShadow,
  45961. bool removeOnMouseClick = true);
  45962. /** Creates a SplashScreen object with a specified size.
  45963. For a custom splash screen, you can use this method to display it at a certain size
  45964. and then override the paint() method yourself to do whatever's necessary.
  45965. As soon as this is called, the SplashScreen will be displayed in the centre of the
  45966. screen. This method will also dispatch any pending messages to make sure that when
  45967. it returns, the splash screen has been completely drawn, and your initialisation
  45968. code can carry on.
  45969. @param title the name to give the component
  45970. @param width the width to use
  45971. @param height the height to use
  45972. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  45973. should stay visible for. If the initialisation takes longer than
  45974. this time, the splash screen will wait for it to finish before
  45975. disappearing, but if initialisation is very quick, this lets
  45976. you make sure that people get a good look at your splash.
  45977. @param useDropShadow if true, the window will have a drop shadow
  45978. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  45979. the mouse (anywhere)
  45980. */
  45981. void show (const String& title,
  45982. int width,
  45983. int height,
  45984. int minimumTimeToDisplayFor,
  45985. bool useDropShadow,
  45986. bool removeOnMouseClick = true);
  45987. /** @internal */
  45988. void paint (Graphics& g);
  45989. /** @internal */
  45990. void timerCallback();
  45991. private:
  45992. Image backgroundImage;
  45993. Time earliestTimeToDelete;
  45994. int originalClickCounter;
  45995. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  45996. };
  45997. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  45998. /*** End of inlined file: juce_SplashScreen.h ***/
  45999. #endif
  46000. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  46001. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  46002. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  46003. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  46004. /**
  46005. A thread that automatically pops up a modal dialog box with a progress bar
  46006. and cancel button while it's busy running.
  46007. These are handy for performing some sort of task while giving the user feedback
  46008. about how long there is to go, etc.
  46009. E.g. @code
  46010. class MyTask : public ThreadWithProgressWindow
  46011. {
  46012. public:
  46013. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  46014. {
  46015. }
  46016. ~MyTask()
  46017. {
  46018. }
  46019. void run()
  46020. {
  46021. for (int i = 0; i < thingsToDo; ++i)
  46022. {
  46023. // must check this as often as possible, because this is
  46024. // how we know if the user's pressed 'cancel'
  46025. if (threadShouldExit())
  46026. break;
  46027. // this will update the progress bar on the dialog box
  46028. setProgress (i / (double) thingsToDo);
  46029. // ... do the business here...
  46030. }
  46031. }
  46032. };
  46033. void doTheTask()
  46034. {
  46035. MyTask m;
  46036. if (m.runThread())
  46037. {
  46038. // thread finished normally..
  46039. }
  46040. else
  46041. {
  46042. // user pressed the cancel button..
  46043. }
  46044. }
  46045. @endcode
  46046. @see Thread, AlertWindow
  46047. */
  46048. class JUCE_API ThreadWithProgressWindow : public Thread,
  46049. private Timer
  46050. {
  46051. public:
  46052. /** Creates the thread.
  46053. Initially, the dialog box won't be visible, it'll only appear when the
  46054. runThread() method is called.
  46055. @param windowTitle the title to go at the top of the dialog box
  46056. @param hasProgressBar whether the dialog box should have a progress bar (see
  46057. setProgress() )
  46058. @param hasCancelButton whether the dialog box should have a cancel button
  46059. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  46060. the thread to stop before killing it forcibly (see
  46061. Thread::stopThread() )
  46062. @param cancelButtonText the text that should be shown in the cancel button
  46063. (if it has one)
  46064. */
  46065. ThreadWithProgressWindow (const String& windowTitle,
  46066. bool hasProgressBar,
  46067. bool hasCancelButton,
  46068. int timeOutMsWhenCancelling = 10000,
  46069. const String& cancelButtonText = "Cancel");
  46070. /** Destructor. */
  46071. ~ThreadWithProgressWindow();
  46072. /** Starts the thread and waits for it to finish.
  46073. This will start the thread, make the dialog box appear, and wait until either
  46074. the thread finishes normally, or until the cancel button is pressed.
  46075. Before returning, the dialog box will be hidden.
  46076. @param threadPriority the priority to use when starting the thread - see
  46077. Thread::startThread() for values
  46078. @returns true if the thread finished normally; false if the user pressed cancel
  46079. */
  46080. bool runThread (int threadPriority = 5);
  46081. /** The thread should call this periodically to update the position of the progress bar.
  46082. @param newProgress the progress, from 0.0 to 1.0
  46083. @see setStatusMessage
  46084. */
  46085. void setProgress (double newProgress);
  46086. /** The thread can call this to change the message that's displayed in the dialog box.
  46087. */
  46088. void setStatusMessage (const String& newStatusMessage);
  46089. /** Returns the AlertWindow that is being used.
  46090. */
  46091. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  46092. private:
  46093. void timerCallback();
  46094. double progress;
  46095. ScopedPointer <AlertWindow> alertWindow;
  46096. String message;
  46097. CriticalSection messageLock;
  46098. const int timeOutMsWhenCancelling;
  46099. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  46100. };
  46101. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  46102. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  46103. #endif
  46104. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  46105. #endif
  46106. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  46107. #endif
  46108. #ifndef __JUCE_COLOUR_JUCEHEADER__
  46109. #endif
  46110. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  46111. #endif
  46112. #ifndef __JUCE_COLOURS_JUCEHEADER__
  46113. #endif
  46114. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  46115. #endif
  46116. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  46117. /*** Start of inlined file: juce_EdgeTable.h ***/
  46118. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  46119. #define __JUCE_EDGETABLE_JUCEHEADER__
  46120. class Path;
  46121. class Image;
  46122. /**
  46123. A table of horizontal scan-line segments - used for rasterising Paths.
  46124. @see Path, Graphics
  46125. */
  46126. class JUCE_API EdgeTable
  46127. {
  46128. public:
  46129. /** Creates an edge table containing a path.
  46130. A table is created with a fixed vertical range, and only sections of the path
  46131. which lie within this range will be added to the table.
  46132. @param clipLimits only the region of the path that lies within this area will be added
  46133. @param pathToAdd the path to add to the table
  46134. @param transform a transform to apply to the path being added
  46135. */
  46136. EdgeTable (const Rectangle<int>& clipLimits,
  46137. const Path& pathToAdd,
  46138. const AffineTransform& transform);
  46139. /** Creates an edge table containing a rectangle.
  46140. */
  46141. EdgeTable (const Rectangle<int>& rectangleToAdd);
  46142. /** Creates an edge table containing a rectangle list.
  46143. */
  46144. EdgeTable (const RectangleList& rectanglesToAdd);
  46145. /** Creates an edge table containing a rectangle.
  46146. */
  46147. EdgeTable (const Rectangle<float>& rectangleToAdd);
  46148. /** Creates a copy of another edge table. */
  46149. EdgeTable (const EdgeTable& other);
  46150. /** Copies from another edge table. */
  46151. EdgeTable& operator= (const EdgeTable& other);
  46152. /** Destructor. */
  46153. ~EdgeTable();
  46154. void clipToRectangle (const Rectangle<int>& r);
  46155. void excludeRectangle (const Rectangle<int>& r);
  46156. void clipToEdgeTable (const EdgeTable& other);
  46157. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  46158. bool isEmpty() throw();
  46159. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  46160. void translate (float dx, int dy) throw();
  46161. /** Reduces the amount of space the table has allocated.
  46162. This will shrink the table down to use as little memory as possible - useful for
  46163. read-only tables that get stored and re-used for rendering.
  46164. */
  46165. void optimiseTable();
  46166. /** Iterates the lines in the table, for rendering.
  46167. This function will iterate each line in the table, and call a user-defined class
  46168. to render each pixel or continuous line of pixels that the table contains.
  46169. @param iterationCallback this templated class must contain the following methods:
  46170. @code
  46171. inline void setEdgeTableYPos (int y);
  46172. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  46173. inline void handleEdgeTablePixelFull (int x) const;
  46174. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  46175. inline void handleEdgeTableLineFull (int x, int width) const;
  46176. @endcode
  46177. (these don't necessarily have to be 'const', but it might help it go faster)
  46178. */
  46179. template <class EdgeTableIterationCallback>
  46180. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  46181. {
  46182. const int* lineStart = table;
  46183. for (int y = 0; y < bounds.getHeight(); ++y)
  46184. {
  46185. const int* line = lineStart;
  46186. lineStart += lineStrideElements;
  46187. int numPoints = line[0];
  46188. if (--numPoints > 0)
  46189. {
  46190. int x = *++line;
  46191. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  46192. int levelAccumulator = 0;
  46193. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  46194. while (--numPoints >= 0)
  46195. {
  46196. const int level = *++line;
  46197. jassert (isPositiveAndBelow (level, (int) 256));
  46198. const int endX = *++line;
  46199. jassert (endX >= x);
  46200. const int endOfRun = (endX >> 8);
  46201. if (endOfRun == (x >> 8))
  46202. {
  46203. // small segment within the same pixel, so just save it for the next
  46204. // time round..
  46205. levelAccumulator += (endX - x) * level;
  46206. }
  46207. else
  46208. {
  46209. // plot the fist pixel of this segment, including any accumulated
  46210. // levels from smaller segments that haven't been drawn yet
  46211. levelAccumulator += (0x100 - (x & 0xff)) * level;
  46212. levelAccumulator >>= 8;
  46213. x >>= 8;
  46214. if (levelAccumulator > 0)
  46215. {
  46216. if (levelAccumulator >= 255)
  46217. iterationCallback.handleEdgeTablePixelFull (x);
  46218. else
  46219. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  46220. }
  46221. // if there's a run of similar pixels, do it all in one go..
  46222. if (level > 0)
  46223. {
  46224. jassert (endOfRun <= bounds.getRight());
  46225. const int numPix = endOfRun - ++x;
  46226. if (numPix > 0)
  46227. iterationCallback.handleEdgeTableLine (x, numPix, level);
  46228. }
  46229. // save the bit at the end to be drawn next time round the loop.
  46230. levelAccumulator = (endX & 0xff) * level;
  46231. }
  46232. x = endX;
  46233. }
  46234. levelAccumulator >>= 8;
  46235. if (levelAccumulator > 0)
  46236. {
  46237. x >>= 8;
  46238. jassert (x >= bounds.getX() && x < bounds.getRight());
  46239. if (levelAccumulator >= 255)
  46240. iterationCallback.handleEdgeTablePixelFull (x);
  46241. else
  46242. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  46243. }
  46244. }
  46245. }
  46246. }
  46247. private:
  46248. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  46249. HeapBlock<int> table;
  46250. Rectangle<int> bounds;
  46251. int maxEdgesPerLine, lineStrideElements;
  46252. bool needToCheckEmptinesss;
  46253. void addEdgePoint (int x, int y, int winding);
  46254. void remapTableForNumEdges (int newNumEdgesPerLine);
  46255. void intersectWithEdgeTableLine (int y, const int* otherLine);
  46256. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  46257. void sanitiseLevels (bool useNonZeroWinding) throw();
  46258. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  46259. JUCE_LEAK_DETECTOR (EdgeTable);
  46260. };
  46261. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  46262. /*** End of inlined file: juce_EdgeTable.h ***/
  46263. #endif
  46264. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  46265. /*** Start of inlined file: juce_FillType.h ***/
  46266. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  46267. #define __JUCE_FILLTYPE_JUCEHEADER__
  46268. /**
  46269. Represents a colour or fill pattern to use for rendering paths.
  46270. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  46271. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  46272. @see Graphics::setFillType, DrawablePath::setFill
  46273. */
  46274. class JUCE_API FillType
  46275. {
  46276. public:
  46277. /** Creates a default fill type, of solid black. */
  46278. FillType() throw();
  46279. /** Creates a fill type of a solid colour.
  46280. @see setColour
  46281. */
  46282. FillType (const Colour& colour) throw();
  46283. /** Creates a gradient fill type.
  46284. @see setGradient
  46285. */
  46286. FillType (const ColourGradient& gradient);
  46287. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  46288. and rotation of the pattern.
  46289. @see setTiledImage
  46290. */
  46291. FillType (const Image& image, const AffineTransform& transform) throw();
  46292. /** Creates a copy of another FillType. */
  46293. FillType (const FillType& other);
  46294. /** Makes a copy of another FillType. */
  46295. FillType& operator= (const FillType& other);
  46296. /** Destructor. */
  46297. ~FillType() throw();
  46298. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  46299. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  46300. /** Returns true if this is a gradient fill. */
  46301. bool isGradient() const throw() { return gradient != 0; }
  46302. /** Returns true if this is a tiled image pattern fill. */
  46303. bool isTiledImage() const throw() { return image.isValid(); }
  46304. /** Turns this object into a solid colour fill.
  46305. If the object was an image or gradient, those fields will no longer be valid. */
  46306. void setColour (const Colour& newColour) throw();
  46307. /** Turns this object into a gradient fill. */
  46308. void setGradient (const ColourGradient& newGradient);
  46309. /** Turns this object into a tiled image fill type. The transform allows you to set
  46310. the scaling, offset and rotation of the pattern.
  46311. */
  46312. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  46313. /** Changes the opacity that should be used.
  46314. If the fill is a solid colour, this just changes the opacity of that colour. For
  46315. gradients and image tiles, it changes the opacity that will be used for them.
  46316. */
  46317. void setOpacity (float newOpacity) throw();
  46318. /** Returns the current opacity to be applied to the colour, gradient, or image.
  46319. @see setOpacity
  46320. */
  46321. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  46322. /** Returns true if this fill type is completely transparent. */
  46323. bool isInvisible() const throw();
  46324. bool operator== (const FillType& other) const;
  46325. bool operator!= (const FillType& other) const;
  46326. /** The solid colour being used.
  46327. If the fill type is not a solid colour, the alpha channel of this colour indicates
  46328. the opacity that should be used for the fill, and the RGB channels are ignored.
  46329. */
  46330. Colour colour;
  46331. /** Returns the gradient that should be used for filling.
  46332. This will be zero if the object is some other type of fill.
  46333. If a gradient is active, the overall opacity with which it should be applied
  46334. is indicated by the alpha channel of the colour variable.
  46335. */
  46336. ScopedPointer <ColourGradient> gradient;
  46337. /** The image that should be used for tiling.
  46338. If an image fill is active, the overall opacity with which it should be applied
  46339. is indicated by the alpha channel of the colour variable.
  46340. */
  46341. Image image;
  46342. /** The transform that should be applied to the image or gradient that's being drawn.
  46343. */
  46344. AffineTransform transform;
  46345. private:
  46346. JUCE_LEAK_DETECTOR (FillType);
  46347. };
  46348. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  46349. /*** End of inlined file: juce_FillType.h ***/
  46350. #endif
  46351. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  46352. #endif
  46353. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  46354. #endif
  46355. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  46356. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  46357. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  46358. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  46359. /**
  46360. Interface class for graphics context objects, used internally by the Graphics class.
  46361. Users are not supposed to create instances of this class directly - do your drawing
  46362. via the Graphics object instead.
  46363. It's a base class for different types of graphics context, that may perform software-based
  46364. or OS-accelerated rendering.
  46365. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  46366. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  46367. context.
  46368. */
  46369. class JUCE_API LowLevelGraphicsContext
  46370. {
  46371. protected:
  46372. LowLevelGraphicsContext();
  46373. public:
  46374. virtual ~LowLevelGraphicsContext();
  46375. /** Returns true if this device is vector-based, e.g. a printer. */
  46376. virtual bool isVectorDevice() const = 0;
  46377. /** Moves the origin to a new position.
  46378. The co-ords are relative to the current origin, and indicate the new position
  46379. of (0, 0).
  46380. */
  46381. virtual void setOrigin (int x, int y) = 0;
  46382. virtual void addTransform (const AffineTransform& transform) = 0;
  46383. virtual float getScaleFactor() = 0;
  46384. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  46385. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  46386. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  46387. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  46388. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  46389. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  46390. virtual const Rectangle<int> getClipBounds() const = 0;
  46391. virtual bool isClipEmpty() const = 0;
  46392. virtual void saveState() = 0;
  46393. virtual void restoreState() = 0;
  46394. virtual void beginTransparencyLayer (float opacity) = 0;
  46395. virtual void endTransparencyLayer() = 0;
  46396. virtual void setFill (const FillType& fillType) = 0;
  46397. virtual void setOpacity (float newOpacity) = 0;
  46398. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  46399. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  46400. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  46401. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  46402. virtual void drawLine (const Line <float>& line) = 0;
  46403. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  46404. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  46405. virtual void setFont (const Font& newFont) = 0;
  46406. virtual const Font getFont() = 0;
  46407. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  46408. };
  46409. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  46410. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  46411. #endif
  46412. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  46413. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  46414. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  46415. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  46416. /**
  46417. An implementation of LowLevelGraphicsContext that turns the drawing operations
  46418. into a PostScript document.
  46419. */
  46420. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  46421. {
  46422. public:
  46423. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  46424. const String& documentTitle,
  46425. int totalWidth,
  46426. int totalHeight);
  46427. ~LowLevelGraphicsPostScriptRenderer();
  46428. bool isVectorDevice() const;
  46429. void setOrigin (int x, int y);
  46430. void addTransform (const AffineTransform& transform);
  46431. float getScaleFactor();
  46432. bool clipToRectangle (const Rectangle<int>& r);
  46433. bool clipToRectangleList (const RectangleList& clipRegion);
  46434. void excludeClipRectangle (const Rectangle<int>& r);
  46435. void clipToPath (const Path& path, const AffineTransform& transform);
  46436. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  46437. void saveState();
  46438. void restoreState();
  46439. void beginTransparencyLayer (float opacity);
  46440. void endTransparencyLayer();
  46441. bool clipRegionIntersects (const Rectangle<int>& r);
  46442. const Rectangle<int> getClipBounds() const;
  46443. bool isClipEmpty() const;
  46444. void setFill (const FillType& fillType);
  46445. void setOpacity (float opacity);
  46446. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  46447. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  46448. void fillPath (const Path& path, const AffineTransform& transform);
  46449. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  46450. void drawLine (const Line <float>& line);
  46451. void drawVerticalLine (int x, float top, float bottom);
  46452. void drawHorizontalLine (int x, float top, float bottom);
  46453. const Font getFont();
  46454. void setFont (const Font& newFont);
  46455. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  46456. protected:
  46457. OutputStream& out;
  46458. int totalWidth, totalHeight;
  46459. bool needToClip;
  46460. Colour lastColour;
  46461. struct SavedState
  46462. {
  46463. SavedState();
  46464. ~SavedState();
  46465. RectangleList clip;
  46466. int xOffset, yOffset;
  46467. FillType fillType;
  46468. Font font;
  46469. private:
  46470. SavedState& operator= (const SavedState&);
  46471. };
  46472. OwnedArray <SavedState> stateStack;
  46473. void writeClip();
  46474. void writeColour (const Colour& colour);
  46475. void writePath (const Path& path) const;
  46476. void writeXY (float x, float y) const;
  46477. void writeTransform (const AffineTransform& trans) const;
  46478. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  46479. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  46480. };
  46481. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  46482. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  46483. #endif
  46484. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  46485. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  46486. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  46487. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  46488. /**
  46489. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  46490. its rendering in memory.
  46491. User code is not supposed to create instances of this class directly - do all your
  46492. rendering via the Graphics class instead.
  46493. */
  46494. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  46495. {
  46496. public:
  46497. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  46498. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  46499. ~LowLevelGraphicsSoftwareRenderer();
  46500. bool isVectorDevice() const;
  46501. void setOrigin (int x, int y);
  46502. void addTransform (const AffineTransform& transform);
  46503. float getScaleFactor();
  46504. bool clipToRectangle (const Rectangle<int>& r);
  46505. bool clipToRectangleList (const RectangleList& clipRegion);
  46506. void excludeClipRectangle (const Rectangle<int>& r);
  46507. void clipToPath (const Path& path, const AffineTransform& transform);
  46508. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  46509. bool clipRegionIntersects (const Rectangle<int>& r);
  46510. const Rectangle<int> getClipBounds() const;
  46511. bool isClipEmpty() const;
  46512. void saveState();
  46513. void restoreState();
  46514. void beginTransparencyLayer (float opacity);
  46515. void endTransparencyLayer();
  46516. void setFill (const FillType& fillType);
  46517. void setOpacity (float opacity);
  46518. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  46519. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  46520. void fillPath (const Path& path, const AffineTransform& transform);
  46521. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  46522. void drawLine (const Line <float>& line);
  46523. void drawVerticalLine (int x, float top, float bottom);
  46524. void drawHorizontalLine (int x, float top, float bottom);
  46525. void setFont (const Font& newFont);
  46526. const Font getFont();
  46527. void drawGlyph (int glyphNumber, float x, float y);
  46528. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  46529. protected:
  46530. Image image;
  46531. class GlyphCache;
  46532. class CachedGlyph;
  46533. class SavedState;
  46534. friend class ScopedPointer <SavedState>;
  46535. friend class OwnedArray <SavedState>;
  46536. friend class OwnedArray <CachedGlyph>;
  46537. ScopedPointer <SavedState> currentState;
  46538. OwnedArray <SavedState> stateStack;
  46539. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  46540. };
  46541. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  46542. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  46543. #endif
  46544. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  46545. #endif
  46546. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  46547. #endif
  46548. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  46549. /*** Start of inlined file: juce_DrawableComposite.h ***/
  46550. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  46551. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  46552. /**
  46553. A drawable object which acts as a container for a set of other Drawables.
  46554. @see Drawable
  46555. */
  46556. class JUCE_API DrawableComposite : public Drawable
  46557. {
  46558. public:
  46559. /** Creates a composite Drawable. */
  46560. DrawableComposite();
  46561. /** Creates a copy of a DrawableComposite. */
  46562. DrawableComposite (const DrawableComposite& other);
  46563. /** Destructor. */
  46564. ~DrawableComposite();
  46565. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  46566. @see setContentArea
  46567. */
  46568. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  46569. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  46570. @see setBoundingBox
  46571. */
  46572. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  46573. /** Changes the bounding box transform to match the content area, so that any sub-items will
  46574. be drawn at their untransformed positions.
  46575. */
  46576. void resetBoundingBoxToContentArea();
  46577. /** Returns the main content rectangle.
  46578. The content area is actually defined by the markers named "left", "right", "top" and
  46579. "bottom", but this method is a shortcut that returns them all at once.
  46580. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  46581. */
  46582. const RelativeRectangle getContentArea() const;
  46583. /** Changes the main content area.
  46584. The content area is actually defined by the markers named "left", "right", "top" and
  46585. "bottom", but this method is a shortcut that sets them all at once.
  46586. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  46587. */
  46588. void setContentArea (const RelativeRectangle& newArea);
  46589. /** Resets the content area and the bounding transform to fit around the area occupied
  46590. by the child components (ignoring any markers).
  46591. */
  46592. void resetContentAreaAndBoundingBoxToFitChildren();
  46593. /** The name of the marker that defines the left edge of the content area. */
  46594. static const char* const contentLeftMarkerName;
  46595. /** The name of the marker that defines the right edge of the content area. */
  46596. static const char* const contentRightMarkerName;
  46597. /** The name of the marker that defines the top edge of the content area. */
  46598. static const char* const contentTopMarkerName;
  46599. /** The name of the marker that defines the bottom edge of the content area. */
  46600. static const char* const contentBottomMarkerName;
  46601. /** @internal */
  46602. Drawable* createCopy() const;
  46603. /** @internal */
  46604. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  46605. /** @internal */
  46606. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  46607. /** @internal */
  46608. static const Identifier valueTreeType;
  46609. /** @internal */
  46610. const Rectangle<float> getDrawableBounds() const;
  46611. /** @internal */
  46612. void childBoundsChanged (Component*);
  46613. /** @internal */
  46614. void childrenChanged();
  46615. /** @internal */
  46616. void parentHierarchyChanged();
  46617. /** @internal */
  46618. MarkerList* getMarkers (bool xAxis);
  46619. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  46620. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  46621. {
  46622. public:
  46623. ValueTreeWrapper (const ValueTree& state);
  46624. ValueTree getChildList() const;
  46625. ValueTree getChildListCreating (UndoManager* undoManager);
  46626. const RelativeParallelogram getBoundingBox() const;
  46627. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  46628. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  46629. const RelativeRectangle getContentArea() const;
  46630. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  46631. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  46632. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  46633. static const Identifier topLeft, topRight, bottomLeft;
  46634. private:
  46635. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  46636. };
  46637. private:
  46638. RelativeParallelogram bounds;
  46639. MarkerList markersX, markersY;
  46640. bool updateBoundsReentrant;
  46641. friend class Drawable::Positioner<DrawableComposite>;
  46642. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  46643. void recalculateCoordinates (Expression::EvaluationContext*);
  46644. void updateBoundsToFitChildren();
  46645. DrawableComposite& operator= (const DrawableComposite&);
  46646. JUCE_LEAK_DETECTOR (DrawableComposite);
  46647. };
  46648. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  46649. /*** End of inlined file: juce_DrawableComposite.h ***/
  46650. #endif
  46651. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  46652. /*** Start of inlined file: juce_DrawableImage.h ***/
  46653. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  46654. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  46655. /**
  46656. A drawable object which is a bitmap image.
  46657. @see Drawable
  46658. */
  46659. class JUCE_API DrawableImage : public Drawable
  46660. {
  46661. public:
  46662. DrawableImage();
  46663. DrawableImage (const DrawableImage& other);
  46664. /** Destructor. */
  46665. ~DrawableImage();
  46666. /** Sets the image that this drawable will render. */
  46667. void setImage (const Image& imageToUse);
  46668. /** Returns the current image. */
  46669. const Image getImage() const { return image; }
  46670. /** Sets the opacity to use when drawing the image. */
  46671. void setOpacity (float newOpacity);
  46672. /** Returns the image's opacity. */
  46673. float getOpacity() const throw() { return opacity; }
  46674. /** Sets a colour to draw over the image's alpha channel.
  46675. By default this is transparent so isn't drawn, but if you set a non-transparent
  46676. colour here, then it will be overlaid on the image, using the image's alpha
  46677. channel as a mask.
  46678. This is handy for doing things like darkening or lightening an image by overlaying
  46679. it with semi-transparent black or white.
  46680. */
  46681. void setOverlayColour (const Colour& newOverlayColour);
  46682. /** Returns the overlay colour. */
  46683. const Colour& getOverlayColour() const throw() { return overlayColour; }
  46684. /** Sets the bounding box within which the image should be displayed. */
  46685. void setBoundingBox (const RelativeParallelogram& newBounds);
  46686. /** Returns the position to which the image's top-left corner should be remapped in the target
  46687. coordinate space when rendering this object.
  46688. @see setTransform
  46689. */
  46690. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  46691. /** @internal */
  46692. void paint (Graphics& g);
  46693. /** @internal */
  46694. bool hitTest (int x, int y) const;
  46695. /** @internal */
  46696. Drawable* createCopy() const;
  46697. /** @internal */
  46698. const Rectangle<float> getDrawableBounds() const;
  46699. /** @internal */
  46700. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  46701. /** @internal */
  46702. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  46703. /** @internal */
  46704. static const Identifier valueTreeType;
  46705. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  46706. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  46707. {
  46708. public:
  46709. ValueTreeWrapper (const ValueTree& state);
  46710. const var getImageIdentifier() const;
  46711. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  46712. Value getImageIdentifierValue (UndoManager* undoManager);
  46713. float getOpacity() const;
  46714. void setOpacity (float newOpacity, UndoManager* undoManager);
  46715. Value getOpacityValue (UndoManager* undoManager);
  46716. const Colour getOverlayColour() const;
  46717. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  46718. Value getOverlayColourValue (UndoManager* undoManager);
  46719. const RelativeParallelogram getBoundingBox() const;
  46720. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  46721. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  46722. };
  46723. private:
  46724. Image image;
  46725. float opacity;
  46726. Colour overlayColour;
  46727. RelativeParallelogram bounds;
  46728. friend class Drawable::Positioner<DrawableImage>;
  46729. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  46730. void recalculateCoordinates (Expression::EvaluationContext*);
  46731. DrawableImage& operator= (const DrawableImage&);
  46732. JUCE_LEAK_DETECTOR (DrawableImage);
  46733. };
  46734. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  46735. /*** End of inlined file: juce_DrawableImage.h ***/
  46736. #endif
  46737. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  46738. /*** Start of inlined file: juce_DrawablePath.h ***/
  46739. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  46740. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  46741. /*** Start of inlined file: juce_DrawableShape.h ***/
  46742. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  46743. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  46744. /**
  46745. A base class implementing common functionality for Drawable classes which
  46746. consist of some kind of filled and stroked outline.
  46747. @see DrawablePath, DrawableRectangle
  46748. */
  46749. class JUCE_API DrawableShape : public Drawable
  46750. {
  46751. protected:
  46752. DrawableShape();
  46753. DrawableShape (const DrawableShape&);
  46754. public:
  46755. /** Destructor. */
  46756. ~DrawableShape();
  46757. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  46758. */
  46759. class RelativeFillType
  46760. {
  46761. public:
  46762. RelativeFillType();
  46763. RelativeFillType (const FillType& fill);
  46764. RelativeFillType (const RelativeFillType&);
  46765. RelativeFillType& operator= (const RelativeFillType&);
  46766. bool operator== (const RelativeFillType&) const;
  46767. bool operator!= (const RelativeFillType&) const;
  46768. bool isDynamic() const;
  46769. bool recalculateCoords (Expression::EvaluationContext* context);
  46770. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  46771. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  46772. FillType fill;
  46773. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  46774. };
  46775. /** Sets a fill type for the path.
  46776. This colour is used to fill the path - if you don't want the path to be
  46777. filled (e.g. if you're just drawing an outline), set this to a transparent
  46778. colour.
  46779. @see setPath, setStrokeFill
  46780. */
  46781. void setFill (const FillType& newFill);
  46782. /** Sets a fill type for the path.
  46783. This colour is used to fill the path - if you don't want the path to be
  46784. filled (e.g. if you're just drawing an outline), set this to a transparent
  46785. colour.
  46786. @see setPath, setStrokeFill
  46787. */
  46788. void setFill (const RelativeFillType& newFill);
  46789. /** Returns the current fill type.
  46790. @see setFill
  46791. */
  46792. const RelativeFillType& getFill() const throw() { return mainFill; }
  46793. /** Sets the fill type with which the outline will be drawn.
  46794. @see setFill
  46795. */
  46796. void setStrokeFill (const FillType& newStrokeFill);
  46797. /** Sets the fill type with which the outline will be drawn.
  46798. @see setFill
  46799. */
  46800. void setStrokeFill (const RelativeFillType& newStrokeFill);
  46801. /** Returns the current stroke fill.
  46802. @see setStrokeFill
  46803. */
  46804. const RelativeFillType& getStrokeFill() const throw() { return strokeFill; }
  46805. /** Changes the properties of the outline that will be drawn around the path.
  46806. If the stroke has 0 thickness, no stroke will be drawn.
  46807. @see setStrokeThickness, setStrokeColour
  46808. */
  46809. void setStrokeType (const PathStrokeType& newStrokeType);
  46810. /** Changes the stroke thickness.
  46811. This is a shortcut for calling setStrokeType.
  46812. */
  46813. void setStrokeThickness (float newThickness);
  46814. /** Returns the current outline style. */
  46815. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  46816. /** @internal */
  46817. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  46818. {
  46819. public:
  46820. FillAndStrokeState (const ValueTree& state);
  46821. ValueTree getFillState (const Identifier& fillOrStrokeType);
  46822. const RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  46823. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  46824. ComponentBuilder::ImageProvider*, UndoManager*);
  46825. const PathStrokeType getStrokeType() const;
  46826. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  46827. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  46828. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  46829. };
  46830. /** @internal */
  46831. const Rectangle<float> getDrawableBounds() const;
  46832. /** @internal */
  46833. void paint (Graphics& g);
  46834. /** @internal */
  46835. bool hitTest (int x, int y) const;
  46836. protected:
  46837. /** Called when the cached path should be updated. */
  46838. void pathChanged();
  46839. /** Called when the cached stroke should be updated. */
  46840. void strokeChanged();
  46841. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  46842. bool isStrokeVisible() const throw();
  46843. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  46844. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  46845. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  46846. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  46847. PathStrokeType strokeType;
  46848. Path path, strokePath;
  46849. private:
  46850. class RelativePositioner;
  46851. RelativeFillType mainFill, strokeFill;
  46852. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  46853. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  46854. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  46855. DrawableShape& operator= (const DrawableShape&);
  46856. };
  46857. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  46858. /*** End of inlined file: juce_DrawableShape.h ***/
  46859. /**
  46860. A drawable object which renders a filled or outlined shape.
  46861. For details on how to change the fill and stroke, see the DrawableShape class.
  46862. @see Drawable, DrawableShape
  46863. */
  46864. class JUCE_API DrawablePath : public DrawableShape
  46865. {
  46866. public:
  46867. /** Creates a DrawablePath. */
  46868. DrawablePath();
  46869. DrawablePath (const DrawablePath& other);
  46870. /** Destructor. */
  46871. ~DrawablePath();
  46872. /** Changes the path that will be drawn.
  46873. @see setFillColour, setStrokeType
  46874. */
  46875. void setPath (const Path& newPath);
  46876. /** Sets the path using a RelativePointPath.
  46877. Calling this will set up a Component::Positioner to automatically update the path
  46878. if any of the points in the source path are dynamic.
  46879. */
  46880. void setPath (const RelativePointPath& newPath);
  46881. /** Returns the current path. */
  46882. const Path& getPath() const;
  46883. /** Returns the current path for the outline. */
  46884. const Path& getStrokePath() const;
  46885. /** @internal */
  46886. Drawable* createCopy() const;
  46887. /** @internal */
  46888. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  46889. /** @internal */
  46890. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  46891. /** @internal */
  46892. static const Identifier valueTreeType;
  46893. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  46894. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  46895. {
  46896. public:
  46897. ValueTreeWrapper (const ValueTree& state);
  46898. bool usesNonZeroWinding() const;
  46899. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  46900. class Element
  46901. {
  46902. public:
  46903. explicit Element (const ValueTree& state);
  46904. ~Element();
  46905. const Identifier getType() const throw() { return state.getType(); }
  46906. int getNumControlPoints() const throw();
  46907. const RelativePoint getControlPoint (int index) const;
  46908. Value getControlPointValue (int index, UndoManager*) const;
  46909. const RelativePoint getStartPoint() const;
  46910. const RelativePoint getEndPoint() const;
  46911. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  46912. float getLength (Expression::EvaluationContext*) const;
  46913. ValueTreeWrapper getParent() const;
  46914. Element getPreviousElement() const;
  46915. const String getModeOfEndPoint() const;
  46916. void setModeOfEndPoint (const String& newMode, UndoManager*);
  46917. void convertToLine (UndoManager*);
  46918. void convertToCubic (Expression::EvaluationContext*, UndoManager*);
  46919. void convertToPathBreak (UndoManager* undoManager);
  46920. ValueTree insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext*, UndoManager*);
  46921. void removePoint (UndoManager* undoManager);
  46922. float findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext*) const;
  46923. static const Identifier mode, startSubPathElement, closeSubPathElement,
  46924. lineToElement, quadraticToElement, cubicToElement;
  46925. static const char* cornerMode;
  46926. static const char* roundedMode;
  46927. static const char* symmetricMode;
  46928. ValueTree state;
  46929. };
  46930. ValueTree getPathState();
  46931. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  46932. void writeTo (RelativePointPath& path) const;
  46933. static const Identifier nonZeroWinding, point1, point2, point3;
  46934. };
  46935. private:
  46936. ScopedPointer<RelativePointPath> relativePath;
  46937. class RelativePositioner;
  46938. friend class RelativePositioner;
  46939. void applyRelativePath (const RelativePointPath&, Expression::EvaluationContext*);
  46940. DrawablePath& operator= (const DrawablePath&);
  46941. JUCE_LEAK_DETECTOR (DrawablePath);
  46942. };
  46943. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  46944. /*** End of inlined file: juce_DrawablePath.h ***/
  46945. #endif
  46946. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  46947. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  46948. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  46949. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  46950. /**
  46951. A Drawable object which draws a rectangle.
  46952. For details on how to change the fill and stroke, see the DrawableShape class.
  46953. @see Drawable, DrawableShape
  46954. */
  46955. class JUCE_API DrawableRectangle : public DrawableShape
  46956. {
  46957. public:
  46958. DrawableRectangle();
  46959. DrawableRectangle (const DrawableRectangle& other);
  46960. /** Destructor. */
  46961. ~DrawableRectangle();
  46962. /** Sets the rectangle's bounds. */
  46963. void setRectangle (const RelativeParallelogram& newBounds);
  46964. /** Returns the rectangle's bounds. */
  46965. const RelativeParallelogram& getRectangle() const throw() { return bounds; }
  46966. /** Returns the corner size to be used. */
  46967. const RelativePoint getCornerSize() const { return cornerSize; }
  46968. /** Sets a new corner size for the rectangle */
  46969. void setCornerSize (const RelativePoint& newSize);
  46970. /** @internal */
  46971. Drawable* createCopy() const;
  46972. /** @internal */
  46973. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  46974. /** @internal */
  46975. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  46976. /** @internal */
  46977. static const Identifier valueTreeType;
  46978. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  46979. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  46980. {
  46981. public:
  46982. ValueTreeWrapper (const ValueTree& state);
  46983. const RelativeParallelogram getRectangle() const;
  46984. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  46985. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  46986. const RelativePoint getCornerSize() const;
  46987. Value getCornerSizeValue (UndoManager*) const;
  46988. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  46989. };
  46990. private:
  46991. friend class Drawable::Positioner<DrawableRectangle>;
  46992. RelativeParallelogram bounds;
  46993. RelativePoint cornerSize;
  46994. void rebuildPath();
  46995. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  46996. void recalculateCoordinates (Expression::EvaluationContext*);
  46997. DrawableRectangle& operator= (const DrawableRectangle&);
  46998. JUCE_LEAK_DETECTOR (DrawableRectangle);
  46999. };
  47000. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  47001. /*** End of inlined file: juce_DrawableRectangle.h ***/
  47002. #endif
  47003. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  47004. #endif
  47005. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  47006. /*** Start of inlined file: juce_DrawableText.h ***/
  47007. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  47008. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  47009. /**
  47010. A drawable object which renders a line of text.
  47011. @see Drawable
  47012. */
  47013. class JUCE_API DrawableText : public Drawable
  47014. {
  47015. public:
  47016. /** Creates a DrawableText object. */
  47017. DrawableText();
  47018. DrawableText (const DrawableText& other);
  47019. /** Destructor. */
  47020. ~DrawableText();
  47021. /** Sets the text to display.*/
  47022. void setText (const String& newText);
  47023. /** Sets the colour of the text. */
  47024. void setColour (const Colour& newColour);
  47025. /** Returns the current text colour. */
  47026. const Colour& getColour() const throw() { return colour; }
  47027. /** Sets the font to use.
  47028. Note that the font height and horizontal scale are actually based upon the position
  47029. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  47030. the height and scale control point will be moved to match the dimensions of the font supplied;
  47031. if it is false, then the new font's height and scale are ignored.
  47032. */
  47033. void setFont (const Font& newFont, bool applySizeAndScale);
  47034. /** Changes the justification of the text within the bounding box. */
  47035. void setJustification (const Justification& newJustification);
  47036. /** Returns the parallelogram that defines the text bounding box. */
  47037. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  47038. /** Sets the bounding box that contains the text. */
  47039. void setBoundingBox (const RelativeParallelogram& newBounds);
  47040. /** Returns the point within the bounds that defines the font's size and scale. */
  47041. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  47042. /** Sets the control point that defines the font's height and horizontal scale.
  47043. This position is a point within the bounding box parallelogram, whose Y position (relative
  47044. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  47045. and its X defines the font's horizontal scale.
  47046. */
  47047. void setFontSizeControlPoint (const RelativePoint& newPoint);
  47048. /** @internal */
  47049. void paint (Graphics& g);
  47050. /** @internal */
  47051. Drawable* createCopy() const;
  47052. /** @internal */
  47053. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  47054. /** @internal */
  47055. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  47056. /** @internal */
  47057. static const Identifier valueTreeType;
  47058. /** @internal */
  47059. const Rectangle<float> getDrawableBounds() const;
  47060. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  47061. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  47062. {
  47063. public:
  47064. ValueTreeWrapper (const ValueTree& state);
  47065. const String getText() const;
  47066. void setText (const String& newText, UndoManager* undoManager);
  47067. Value getTextValue (UndoManager* undoManager);
  47068. const Colour getColour() const;
  47069. void setColour (const Colour& newColour, UndoManager* undoManager);
  47070. const Justification getJustification() const;
  47071. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  47072. const Font getFont() const;
  47073. void setFont (const Font& newFont, UndoManager* undoManager);
  47074. Value getFontValue (UndoManager* undoManager);
  47075. const RelativeParallelogram getBoundingBox() const;
  47076. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  47077. const RelativePoint getFontSizeControlPoint() const;
  47078. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  47079. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  47080. };
  47081. private:
  47082. RelativeParallelogram bounds;
  47083. RelativePoint fontSizeControlPoint;
  47084. Point<float> resolvedPoints[3];
  47085. Font font, scaledFont;
  47086. String text;
  47087. Colour colour;
  47088. Justification justification;
  47089. friend class Drawable::Positioner<DrawableText>;
  47090. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  47091. void recalculateCoordinates (Expression::EvaluationContext*);
  47092. void refreshBounds();
  47093. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  47094. DrawableText& operator= (const DrawableText&);
  47095. JUCE_LEAK_DETECTOR (DrawableText);
  47096. };
  47097. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  47098. /*** End of inlined file: juce_DrawableText.h ***/
  47099. #endif
  47100. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  47101. #endif
  47102. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  47103. /*** Start of inlined file: juce_GlowEffect.h ***/
  47104. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  47105. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  47106. /**
  47107. A component effect that adds a coloured blur around the component's contents.
  47108. (This will only work on non-opaque components).
  47109. @see Component::setComponentEffect, DropShadowEffect
  47110. */
  47111. class JUCE_API GlowEffect : public ImageEffectFilter
  47112. {
  47113. public:
  47114. /** Creates a default 'glow' effect.
  47115. To customise its appearance, use the setGlowProperties() method.
  47116. */
  47117. GlowEffect();
  47118. /** Destructor. */
  47119. ~GlowEffect();
  47120. /** Sets the glow's radius and colour.
  47121. The radius is how large the blur should be, and the colour is
  47122. used to render it (for a less intense glow, lower the colour's
  47123. opacity).
  47124. */
  47125. void setGlowProperties (float newRadius,
  47126. const Colour& newColour);
  47127. /** @internal */
  47128. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  47129. private:
  47130. float radius;
  47131. Colour colour;
  47132. JUCE_LEAK_DETECTOR (GlowEffect);
  47133. };
  47134. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  47135. /*** End of inlined file: juce_GlowEffect.h ***/
  47136. #endif
  47137. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  47138. #endif
  47139. #ifndef __JUCE_FONT_JUCEHEADER__
  47140. #endif
  47141. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  47142. #endif
  47143. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  47144. #endif
  47145. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  47146. #endif
  47147. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  47148. #endif
  47149. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  47150. #endif
  47151. #ifndef __JUCE_LINE_JUCEHEADER__
  47152. #endif
  47153. #ifndef __JUCE_PATH_JUCEHEADER__
  47154. #endif
  47155. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  47156. /*** Start of inlined file: juce_PathIterator.h ***/
  47157. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  47158. #define __JUCE_PATHITERATOR_JUCEHEADER__
  47159. /**
  47160. Flattens a Path object into a series of straight-line sections.
  47161. Use one of these to iterate through a Path object, and it will convert
  47162. all the curves into line sections so it's easy to render or perform
  47163. geometric operations on.
  47164. @see Path
  47165. */
  47166. class JUCE_API PathFlatteningIterator
  47167. {
  47168. public:
  47169. /** Creates a PathFlatteningIterator.
  47170. After creation, use the next() method to initialise the fields in the
  47171. object with the first line's position.
  47172. @param path the path to iterate along
  47173. @param transform a transform to apply to each point in the path being iterated
  47174. @param tolerance the amount by which the curves are allowed to deviate from the lines
  47175. into which they are being broken down - a higher tolerance contains
  47176. less lines, so can be generated faster, but will be less smooth.
  47177. */
  47178. PathFlatteningIterator (const Path& path,
  47179. const AffineTransform& transform = AffineTransform::identity,
  47180. float tolerance = defaultTolerance);
  47181. /** Destructor. */
  47182. ~PathFlatteningIterator();
  47183. /** Fetches the next line segment from the path.
  47184. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  47185. so that they describe the new line segment.
  47186. @returns false when there are no more lines to fetch.
  47187. */
  47188. bool next();
  47189. float x1; /**< The x position of the start of the current line segment. */
  47190. float y1; /**< The y position of the start of the current line segment. */
  47191. float x2; /**< The x position of the end of the current line segment. */
  47192. float y2; /**< The y position of the end of the current line segment. */
  47193. /** Indicates whether the current line segment is closing a sub-path.
  47194. If the current line is the one that connects the end of a sub-path
  47195. back to the start again, this will be true.
  47196. */
  47197. bool closesSubPath;
  47198. /** The index of the current line within the current sub-path.
  47199. E.g. you can use this to see whether the line is the first one in the
  47200. subpath by seeing if it's 0.
  47201. */
  47202. int subPathIndex;
  47203. /** Returns true if the current segment is the last in the current sub-path. */
  47204. bool isLastInSubpath() const throw() { return stackPos == stackBase.getData()
  47205. && (index >= path.numElements || points [index] == Path::moveMarker); }
  47206. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  47207. static const float defaultTolerance;
  47208. private:
  47209. const Path& path;
  47210. const AffineTransform transform;
  47211. float* points;
  47212. const float toleranceSquared;
  47213. float subPathCloseX, subPathCloseY;
  47214. const bool isIdentityTransform;
  47215. HeapBlock <float> stackBase;
  47216. float* stackPos;
  47217. size_t index, stackSize;
  47218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  47219. };
  47220. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  47221. /*** End of inlined file: juce_PathIterator.h ***/
  47222. #endif
  47223. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  47224. #endif
  47225. #ifndef __JUCE_POINT_JUCEHEADER__
  47226. #endif
  47227. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  47228. /*** Start of inlined file: juce_PositionedRectangle.h ***/
  47229. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  47230. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  47231. /**
  47232. A rectangle whose co-ordinates can be defined in terms of absolute or
  47233. proportional distances.
  47234. Designed mainly for storing component positions, this gives you a lot of
  47235. control over how each co-ordinate is stored, either as an absolute position,
  47236. or as a proportion of the size of a parent rectangle.
  47237. It also allows you to define the anchor points by which the rectangle is
  47238. positioned, so for example you could specify that the top right of the
  47239. rectangle should be an absolute distance from its parent's bottom-right corner.
  47240. This object can be stored as a string, which takes the form "x y w h", including
  47241. symbols like '%' and letters to indicate the anchor point. See its toString()
  47242. method for more info.
  47243. Example usage:
  47244. @code
  47245. class MyComponent
  47246. {
  47247. void resized()
  47248. {
  47249. // this will set the child component's x to be 20% of our width, its y
  47250. // to be 30, its width to be 150, and its height to be 50% of our
  47251. // height..
  47252. const PositionedRectangle pos1 ("20% 30 150 50%");
  47253. pos1.applyToComponent (*myChildComponent1);
  47254. // this will inset the child component with a gap of 10 pixels
  47255. // around each of its edges..
  47256. const PositionedRectangle pos2 ("10 10 20M 20M");
  47257. pos2.applyToComponent (*myChildComponent2);
  47258. }
  47259. };
  47260. @endcode
  47261. */
  47262. class JUCE_API PositionedRectangle
  47263. {
  47264. public:
  47265. /** Creates an empty rectangle with all co-ordinates set to zero.
  47266. The default anchor point is top-left; the default
  47267. */
  47268. PositionedRectangle() throw();
  47269. /** Initialises a PositionedRectangle from a saved string version.
  47270. The string must be in the format generated by toString().
  47271. */
  47272. PositionedRectangle (const String& stringVersion) throw();
  47273. /** Creates a copy of another PositionedRectangle. */
  47274. PositionedRectangle (const PositionedRectangle& other) throw();
  47275. /** Copies another PositionedRectangle. */
  47276. PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  47277. /** Destructor. */
  47278. ~PositionedRectangle() throw();
  47279. /** Returns a string version of this position, from which it can later be
  47280. re-generated.
  47281. The format is four co-ordinates, "x y w h".
  47282. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  47283. - If a co-ordinate is proportional to its parent's width or height, it is stored
  47284. as a percentage, e.g. "80%".
  47285. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  47286. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  47287. the parent's right-hand edge.
  47288. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  47289. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  47290. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  47291. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  47292. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  47293. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  47294. has "c" appended to it. So "-50Rc" would mean that this component's
  47295. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  47296. this component's centre should be placed 40% across the parent's width.
  47297. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  47298. the number has "M" appended to it.
  47299. To reload a stored string, use the constructor that takes a string parameter.
  47300. */
  47301. const String toString() const throw();
  47302. /** Calculates the absolute position, given the size of the space that
  47303. it should go in.
  47304. This will work out any proportional distances and sizes relative to the
  47305. target rectangle, and will return the absolute position.
  47306. @see applyToComponent
  47307. */
  47308. const Rectangle<int> getRectangle (const Rectangle<int>& targetSpaceToBeRelativeTo) const throw();
  47309. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  47310. */
  47311. void getRectangleDouble (const Rectangle<int>& targetSpaceToBeRelativeTo,
  47312. double& x,
  47313. double& y,
  47314. double& width,
  47315. double& height) const throw();
  47316. /** This sets the bounds of the given component to this position.
  47317. This is equivalent to writing:
  47318. @code
  47319. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  47320. @endcode
  47321. @see getRectangle, updateFromComponent
  47322. */
  47323. void applyToComponent (Component& comp) const throw();
  47324. /** Updates this object's co-ordinates to match the given rectangle.
  47325. This will set all co-ordinates based on the given rectangle, re-calculating
  47326. any proportional distances, and using the current anchor points.
  47327. So for example if the x co-ordinate mode is currently proportional, this will
  47328. re-calculate x based on the rectangle's relative position within the target
  47329. rectangle's width.
  47330. If the target rectangle's width or height are zero then it may not be possible
  47331. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  47332. will not be changed.
  47333. */
  47334. void updateFrom (const Rectangle<int>& newPosition,
  47335. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  47336. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  47337. */
  47338. void updateFromDouble (double x, double y, double width, double height,
  47339. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  47340. /** Updates this object's co-ordinates to match the bounds of this component.
  47341. This is equivalent to calling updateFrom() with the component's bounds and
  47342. it parent size.
  47343. If the component doesn't currently have a parent, then proportional co-ordinates
  47344. might not be updated because it would need to know the parent's size to do the
  47345. maths for this.
  47346. */
  47347. void updateFromComponent (const Component& comp) throw();
  47348. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  47349. enum AnchorPoint
  47350. {
  47351. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  47352. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  47353. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  47354. };
  47355. /** Specifies how an x or y co-ordinate should be interpreted. */
  47356. enum PositionMode
  47357. {
  47358. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  47359. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  47360. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  47361. 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. */
  47362. };
  47363. /** Specifies how the width or height should be interpreted. */
  47364. enum SizeMode
  47365. {
  47366. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  47367. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  47368. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  47369. };
  47370. /** Sets all options for all co-ordinates.
  47371. This requires a reference rectangle to be specified, because if you're changing any
  47372. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  47373. the co-ordinates, and will need to know the parent size so it can calculate this.
  47374. */
  47375. void setModes (const AnchorPoint xAnchorMode,
  47376. const PositionMode xPositionMode,
  47377. const AnchorPoint yAnchorMode,
  47378. const PositionMode yPositionMode,
  47379. const SizeMode widthMode,
  47380. const SizeMode heightMode,
  47381. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  47382. /** Returns the anchoring mode for the x co-ordinate.
  47383. To change any of the modes, use setModes().
  47384. */
  47385. AnchorPoint getAnchorPointX() const throw();
  47386. /** Returns the positioning mode for the x co-ordinate.
  47387. To change any of the modes, use setModes().
  47388. */
  47389. PositionMode getPositionModeX() const throw();
  47390. /** Returns the raw x co-ordinate.
  47391. If the x position mode is absolute, then this will be the absolute value. If it's
  47392. proportional, then this will be a fractional proportion, where 1.0 means the full
  47393. width of the parent space.
  47394. */
  47395. double getX() const throw() { return x; }
  47396. /** Sets the raw value of the x co-ordinate.
  47397. See getX() for the meaning of this value.
  47398. */
  47399. void setX (const double newX) throw() { x = newX; }
  47400. /** Returns the anchoring mode for the y co-ordinate.
  47401. To change any of the modes, use setModes().
  47402. */
  47403. AnchorPoint getAnchorPointY() const throw();
  47404. /** Returns the positioning mode for the y co-ordinate.
  47405. To change any of the modes, use setModes().
  47406. */
  47407. PositionMode getPositionModeY() const throw();
  47408. /** Returns the raw y co-ordinate.
  47409. If the y position mode is absolute, then this will be the absolute value. If it's
  47410. proportional, then this will be a fractional proportion, where 1.0 means the full
  47411. height of the parent space.
  47412. */
  47413. double getY() const throw() { return y; }
  47414. /** Sets the raw value of the y co-ordinate.
  47415. See getY() for the meaning of this value.
  47416. */
  47417. void setY (const double newY) throw() { y = newY; }
  47418. /** Returns the mode used to calculate the width.
  47419. To change any of the modes, use setModes().
  47420. */
  47421. SizeMode getWidthMode() const throw();
  47422. /** Returns the raw width value.
  47423. If the width mode is absolute, then this will be the absolute value. If the mode is
  47424. proportional, then this will be a fractional proportion, where 1.0 means the full
  47425. width of the parent space.
  47426. */
  47427. double getWidth() const throw() { return w; }
  47428. /** Sets the raw width value.
  47429. See getWidth() for the details about what this value means.
  47430. */
  47431. void setWidth (const double newWidth) throw() { w = newWidth; }
  47432. /** Returns the mode used to calculate the height.
  47433. To change any of the modes, use setModes().
  47434. */
  47435. SizeMode getHeightMode() const throw();
  47436. /** Returns the raw height value.
  47437. If the height mode is absolute, then this will be the absolute value. If the mode is
  47438. proportional, then this will be a fractional proportion, where 1.0 means the full
  47439. height of the parent space.
  47440. */
  47441. double getHeight() const throw() { return h; }
  47442. /** Sets the raw height value.
  47443. See getHeight() for the details about what this value means.
  47444. */
  47445. void setHeight (const double newHeight) throw() { h = newHeight; }
  47446. /** If the size and position are constance, and wouldn't be affected by changes
  47447. in the parent's size, then this will return true.
  47448. */
  47449. bool isPositionAbsolute() const throw();
  47450. /** Compares two objects. */
  47451. bool operator== (const PositionedRectangle& other) const throw();
  47452. /** Compares two objects. */
  47453. bool operator!= (const PositionedRectangle& other) const throw();
  47454. private:
  47455. double x, y, w, h;
  47456. uint8 xMode, yMode, wMode, hMode;
  47457. void addPosDescription (String& result, uint8 mode, double value) const throw();
  47458. void addSizeDescription (String& result, uint8 mode, double value) const throw();
  47459. void decodePosString (const String& s, uint8& mode, double& value) throw();
  47460. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  47461. void applyPosAndSize (double& xOut, double& wOut, double x, double w,
  47462. uint8 xMode, uint8 wMode,
  47463. int parentPos, int parentSize) const throw();
  47464. void updatePosAndSize (double& xOut, double& wOut, double x, double w,
  47465. uint8 xMode, uint8 wMode,
  47466. int parentPos, int parentSize) const throw();
  47467. JUCE_LEAK_DETECTOR (PositionedRectangle);
  47468. };
  47469. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  47470. /*** End of inlined file: juce_PositionedRectangle.h ***/
  47471. #endif
  47472. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  47473. #endif
  47474. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  47475. #endif
  47476. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  47477. /*** Start of inlined file: juce_CameraDevice.h ***/
  47478. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  47479. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  47480. #if JUCE_USE_CAMERA || DOXYGEN
  47481. /**
  47482. Controls any video capture devices that might be available.
  47483. Use getAvailableDevices() to list the devices that are attached to the
  47484. system, then call openDevice to open one for use. Once you have a CameraDevice
  47485. object, you can get a viewer component from it, and use its methods to
  47486. stream to a file or capture still-frames.
  47487. */
  47488. class JUCE_API CameraDevice
  47489. {
  47490. public:
  47491. /** Destructor. */
  47492. virtual ~CameraDevice();
  47493. /** Returns a list of the available cameras on this machine.
  47494. You can open one of these devices by calling openDevice().
  47495. */
  47496. static const StringArray getAvailableDevices();
  47497. /** Opens a camera device.
  47498. The index parameter indicates which of the items returned by getAvailableDevices()
  47499. to open.
  47500. The size constraints allow the method to choose between different resolutions if
  47501. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  47502. then these will be ignored.
  47503. */
  47504. static CameraDevice* openDevice (int deviceIndex,
  47505. int minWidth = 128, int minHeight = 64,
  47506. int maxWidth = 1024, int maxHeight = 768);
  47507. /** Returns the name of this device */
  47508. const String getName() const { return name; }
  47509. /** Creates a component that can be used to display a preview of the
  47510. video from this camera.
  47511. */
  47512. Component* createViewerComponent();
  47513. /** Starts recording video to the specified file.
  47514. You should use getFileExtension() to find out the correct extension to
  47515. use for your filename.
  47516. If the file exists, it will be deleted before the recording starts.
  47517. This method may not start recording instantly, so if you need to know the
  47518. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  47519. after the recording has finished.
  47520. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  47521. or may not be used, depending on the driver.
  47522. */
  47523. void startRecordingToFile (const File& file, int quality = 2);
  47524. /** Stops recording, after a call to startRecordingToFile().
  47525. */
  47526. void stopRecording();
  47527. /** Returns the file extension that should be used for the files
  47528. that you pass to startRecordingToFile().
  47529. This may be platform-specific, e.g. ".mov" or ".avi".
  47530. */
  47531. static const String getFileExtension();
  47532. /** After calling stopRecording(), this method can be called to return the timestamp
  47533. of the first frame that was written to the file.
  47534. */
  47535. const Time getTimeOfFirstRecordedFrame() const;
  47536. /**
  47537. Receives callbacks with images from a CameraDevice.
  47538. @see CameraDevice::addListener
  47539. */
  47540. class JUCE_API Listener
  47541. {
  47542. public:
  47543. Listener() {}
  47544. virtual ~Listener() {}
  47545. /** This method is called when a new image arrives.
  47546. This may be called by any thread, so be careful about thread-safety,
  47547. and make sure that you process the data as quickly as possible to
  47548. avoid glitching!
  47549. */
  47550. virtual void imageReceived (const Image& image) = 0;
  47551. };
  47552. /** Adds a listener to receive images from the camera.
  47553. Be very careful not to delete the listener without first removing it by calling
  47554. removeListener().
  47555. */
  47556. void addListener (Listener* listenerToAdd);
  47557. /** Removes a listener that was previously added with addListener().
  47558. */
  47559. void removeListener (Listener* listenerToRemove);
  47560. protected:
  47561. /** @internal */
  47562. CameraDevice (const String& name, int index);
  47563. private:
  47564. void* internal;
  47565. bool isRecording;
  47566. String name;
  47567. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  47568. };
  47569. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  47570. typedef CameraDevice::Listener CameraImageListener;
  47571. #endif
  47572. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  47573. /*** End of inlined file: juce_CameraDevice.h ***/
  47574. #endif
  47575. #ifndef __JUCE_IMAGE_JUCEHEADER__
  47576. #endif
  47577. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  47578. /*** Start of inlined file: juce_ImageCache.h ***/
  47579. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  47580. #define __JUCE_IMAGECACHE_JUCEHEADER__
  47581. /**
  47582. A global cache of images that have been loaded from files or memory.
  47583. If you're loading an image and may need to use the image in more than one
  47584. place, this is used to allow the same image to be shared rather than loading
  47585. multiple copies into memory.
  47586. Another advantage is that after images are released, they will be kept in
  47587. memory for a few seconds before it is actually deleted, so if you're repeatedly
  47588. loading/deleting the same image, it'll reduce the chances of having to reload it
  47589. each time.
  47590. @see Image, ImageFileFormat
  47591. */
  47592. class JUCE_API ImageCache
  47593. {
  47594. public:
  47595. /** Loads an image from a file, (or just returns the image if it's already cached).
  47596. If the cache already contains an image that was loaded from this file,
  47597. that image will be returned. Otherwise, this method will try to load the
  47598. file, add it to the cache, and return it.
  47599. Remember that the image returned is shared, so drawing into it might
  47600. affect other things that are using it! If you want to draw on it, first
  47601. call Image::duplicateIfShared()
  47602. @param file the file to try to load
  47603. @returns the image, or null if it there was an error loading it
  47604. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  47605. */
  47606. static const Image getFromFile (const File& file);
  47607. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  47608. If the cache already contains an image that was loaded from this block of memory,
  47609. that image will be returned. Otherwise, this method will try to load the
  47610. file, add it to the cache, and return it.
  47611. Remember that the image returned is shared, so drawing into it might
  47612. affect other things that are using it! If you want to draw on it, first
  47613. call Image::duplicateIfShared()
  47614. @param imageData the block of memory containing the image data
  47615. @param dataSize the data size in bytes
  47616. @returns the image, or an invalid image if it there was an error loading it
  47617. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  47618. */
  47619. static const Image getFromMemory (const void* imageData, int dataSize);
  47620. /** Checks the cache for an image with a particular hashcode.
  47621. If there's an image in the cache with this hashcode, it will be returned,
  47622. otherwise it will return an invalid image.
  47623. @param hashCode the hash code that was associated with the image by addImageToCache()
  47624. @see addImageToCache
  47625. */
  47626. static const Image getFromHashCode (int64 hashCode);
  47627. /** Adds an image to the cache with a user-defined hash-code.
  47628. The image passed-in will be referenced (not copied) by the cache, so it's probably
  47629. a good idea not to draw into it after adding it, otherwise this will affect all
  47630. instances of it that may be in use.
  47631. @param image the image to add
  47632. @param hashCode the hash-code to associate with it
  47633. @see getFromHashCode
  47634. */
  47635. static void addImageToCache (const Image& image, int64 hashCode);
  47636. /** Changes the amount of time before an unused image will be removed from the cache.
  47637. By default this is about 5 seconds.
  47638. */
  47639. static void setCacheTimeout (int millisecs);
  47640. private:
  47641. class Pimpl;
  47642. friend class Pimpl;
  47643. ImageCache();
  47644. ~ImageCache();
  47645. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  47646. };
  47647. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  47648. /*** End of inlined file: juce_ImageCache.h ***/
  47649. #endif
  47650. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  47651. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  47652. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  47653. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  47654. /**
  47655. Represents a filter kernel to use in convoluting an image.
  47656. @see Image::applyConvolution
  47657. */
  47658. class JUCE_API ImageConvolutionKernel
  47659. {
  47660. public:
  47661. /** Creates an empty convulution kernel.
  47662. @param size the length of each dimension of the kernel, so e.g. if the size
  47663. is 5, it will create a 5x5 kernel
  47664. */
  47665. ImageConvolutionKernel (int size);
  47666. /** Destructor. */
  47667. ~ImageConvolutionKernel();
  47668. /** Resets all values in the kernel to zero. */
  47669. void clear();
  47670. /** Returns one of the kernel values. */
  47671. float getKernelValue (int x, int y) const throw();
  47672. /** Sets the value of a specific cell in the kernel.
  47673. The x and y parameters must be in the range 0 < x < getKernelSize().
  47674. @see setOverallSum
  47675. */
  47676. void setKernelValue (int x, int y, float value) throw();
  47677. /** Rescales all values in the kernel to make the total add up to a fixed value.
  47678. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  47679. */
  47680. void setOverallSum (float desiredTotalSum);
  47681. /** Multiplies all values in the kernel by a value. */
  47682. void rescaleAllValues (float multiplier);
  47683. /** Intialises the kernel for a gaussian blur.
  47684. @param blurRadius this may be larger or smaller than the kernel's actual
  47685. size but this will obviously be wasteful or clip at the
  47686. edges. Ideally the kernel should be just larger than
  47687. (blurRadius * 2).
  47688. */
  47689. void createGaussianBlur (float blurRadius);
  47690. /** Returns the size of the kernel.
  47691. E.g. if it's a 3x3 kernel, this returns 3.
  47692. */
  47693. int getKernelSize() const { return size; }
  47694. /** Applies the kernel to an image.
  47695. @param destImage the image that will receive the resultant convoluted pixels.
  47696. @param sourceImage the source image to read from - this can be the same image as
  47697. the destination, but if different, it must be exactly the same
  47698. size and format.
  47699. @param destinationArea the region of the image to apply the filter to
  47700. */
  47701. void applyToImage (Image& destImage,
  47702. const Image& sourceImage,
  47703. const Rectangle<int>& destinationArea) const;
  47704. private:
  47705. HeapBlock <float> values;
  47706. const int size;
  47707. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  47708. };
  47709. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  47710. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  47711. #endif
  47712. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  47713. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  47714. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  47715. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  47716. /**
  47717. Base-class for codecs that can read and write image file formats such
  47718. as PNG, JPEG, etc.
  47719. This class also contains static methods to make it easy to load images
  47720. from files, streams or from memory.
  47721. @see Image, ImageCache
  47722. */
  47723. class JUCE_API ImageFileFormat
  47724. {
  47725. protected:
  47726. /** Creates an ImageFormat. */
  47727. ImageFileFormat() {}
  47728. public:
  47729. /** Destructor. */
  47730. virtual ~ImageFileFormat() {}
  47731. /** Returns a description of this file format.
  47732. E.g. "JPEG", "PNG"
  47733. */
  47734. virtual const String getFormatName() = 0;
  47735. /** Returns true if the given stream seems to contain data that this format
  47736. understands.
  47737. The format class should only read the first few bytes of the stream and sniff
  47738. for header bytes that it understands.
  47739. @see decodeImage
  47740. */
  47741. virtual bool canUnderstand (InputStream& input) = 0;
  47742. /** Tries to decode and return an image from the given stream.
  47743. This will be called for an image format after calling its canUnderStand() method
  47744. to see if it can handle the stream.
  47745. @param input the stream to read the data from. The stream will be positioned
  47746. at the start of the image data (but this may not necessarily
  47747. be position 0)
  47748. @returns the image that was decoded, or an invalid image if it fails.
  47749. @see loadFrom
  47750. */
  47751. virtual const Image decodeImage (InputStream& input) = 0;
  47752. /** Attempts to write an image to a stream.
  47753. To specify extra information like encoding quality, there will be appropriate parameters
  47754. in the subclasses of the specific file types.
  47755. @returns true if it nothing went wrong.
  47756. */
  47757. virtual bool writeImageToStream (const Image& sourceImage,
  47758. OutputStream& destStream) = 0;
  47759. /** Tries the built-in decoders to see if it can find one to read this stream.
  47760. There are currently built-in decoders for PNG, JPEG and GIF formats.
  47761. The object that is returned should not be deleted by the caller.
  47762. @see canUnderstand, decodeImage, loadFrom
  47763. */
  47764. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  47765. /** Tries to load an image from a stream.
  47766. This will use the findImageFormatForStream() method to locate a suitable
  47767. codec, and use that to load the image.
  47768. @returns the image that was decoded, or an invalid image if it fails.
  47769. */
  47770. static const Image loadFrom (InputStream& input);
  47771. /** Tries to load an image from a file.
  47772. This will use the findImageFormatForStream() method to locate a suitable
  47773. codec, and use that to load the image.
  47774. @returns the image that was decoded, or an invalid image if it fails.
  47775. */
  47776. static const Image loadFrom (const File& file);
  47777. /** Tries to load an image from a block of raw image data.
  47778. This will use the findImageFormatForStream() method to locate a suitable
  47779. codec, and use that to load the image.
  47780. @returns the image that was decoded, or an invalid image if it fails.
  47781. */
  47782. static const Image loadFrom (const void* rawData,
  47783. const int numBytesOfData);
  47784. };
  47785. /**
  47786. A subclass of ImageFileFormat for reading and writing PNG files.
  47787. @see ImageFileFormat, JPEGImageFormat
  47788. */
  47789. class JUCE_API PNGImageFormat : public ImageFileFormat
  47790. {
  47791. public:
  47792. PNGImageFormat();
  47793. ~PNGImageFormat();
  47794. const String getFormatName();
  47795. bool canUnderstand (InputStream& input);
  47796. const Image decodeImage (InputStream& input);
  47797. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  47798. };
  47799. /**
  47800. A subclass of ImageFileFormat for reading and writing JPEG files.
  47801. @see ImageFileFormat, PNGImageFormat
  47802. */
  47803. class JUCE_API JPEGImageFormat : public ImageFileFormat
  47804. {
  47805. public:
  47806. JPEGImageFormat();
  47807. ~JPEGImageFormat();
  47808. /** Specifies the quality to be used when writing a JPEG file.
  47809. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  47810. any negative value is "default" quality
  47811. */
  47812. void setQuality (float newQuality);
  47813. const String getFormatName();
  47814. bool canUnderstand (InputStream& input);
  47815. const Image decodeImage (InputStream& input);
  47816. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  47817. private:
  47818. float quality;
  47819. };
  47820. /**
  47821. A subclass of ImageFileFormat for reading GIF files.
  47822. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  47823. */
  47824. class JUCE_API GIFImageFormat : public ImageFileFormat
  47825. {
  47826. public:
  47827. GIFImageFormat();
  47828. ~GIFImageFormat();
  47829. const String getFormatName();
  47830. bool canUnderstand (InputStream& input);
  47831. const Image decodeImage (InputStream& input);
  47832. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  47833. };
  47834. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  47835. /*** End of inlined file: juce_ImageFileFormat.h ***/
  47836. #endif
  47837. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  47838. #endif
  47839. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  47840. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  47841. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  47842. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  47843. /**
  47844. A class to take care of the logic involved with the loading/saving of some kind
  47845. of document.
  47846. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  47847. functions you need for documents that get saved to a file, so this class attempts
  47848. to abstract most of the boring stuff.
  47849. Your subclass should just implement all the pure virtual methods, and you can
  47850. then use the higher-level public methods to do the load/save dialogs, to warn the user
  47851. about overwriting files, etc.
  47852. The document object keeps track of whether it has changed since it was last saved or
  47853. loaded, so when you change something, call its changed() method. This will set a
  47854. flag so it knows it needs saving, and will also broadcast a change message using the
  47855. ChangeBroadcaster base class.
  47856. @see ChangeBroadcaster
  47857. */
  47858. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  47859. {
  47860. public:
  47861. /** Creates a FileBasedDocument.
  47862. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  47863. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  47864. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  47865. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  47866. */
  47867. FileBasedDocument (const String& fileExtension,
  47868. const String& fileWildCard,
  47869. const String& openFileDialogTitle,
  47870. const String& saveFileDialogTitle);
  47871. /** Destructor. */
  47872. virtual ~FileBasedDocument();
  47873. /** Returns true if the changed() method has been called since the file was
  47874. last saved or loaded.
  47875. @see resetChangedFlag, changed
  47876. */
  47877. bool hasChangedSinceSaved() const { return changedSinceSave; }
  47878. /** Called to indicate that the document has changed and needs saving.
  47879. This method will also trigger a change message to be sent out using the
  47880. ChangeBroadcaster base class.
  47881. After calling the method, the hasChangedSinceSaved() method will return true, until
  47882. it is reset either by saving to a file or using the resetChangedFlag() method.
  47883. @see hasChangedSinceSaved, resetChangedFlag
  47884. */
  47885. virtual void changed();
  47886. /** Sets the state of the 'changed' flag.
  47887. The 'changed' flag is set to true when the changed() method is called - use this method
  47888. to reset it or to set it without also broadcasting a change message.
  47889. @see changed, hasChangedSinceSaved
  47890. */
  47891. void setChangedFlag (bool hasChanged);
  47892. /** Tries to open a file.
  47893. If the file opens correctly, the document's file (see the getFile() method) is set
  47894. to this new one; if it fails, the document's file is left unchanged, and optionally
  47895. a message box is shown telling the user there was an error.
  47896. @returns true if the new file loaded successfully
  47897. @see loadDocument, loadFromUserSpecifiedFile
  47898. */
  47899. bool loadFrom (const File& fileToLoadFrom,
  47900. bool showMessageOnFailure);
  47901. /** Asks the user for a file and tries to load it.
  47902. This will pop up a dialog box using the title, file extension and
  47903. wildcard specified in the document's constructor, and asks the user
  47904. for a file. If they pick one, the loadFrom() method is used to
  47905. try to load it, optionally showing a message if it fails.
  47906. @returns true if a file was loaded; false if the user cancelled or if they
  47907. picked a file which failed to load correctly
  47908. @see loadFrom
  47909. */
  47910. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  47911. /** A set of possible outcomes of one of the save() methods
  47912. */
  47913. enum SaveResult
  47914. {
  47915. savedOk = 0, /**< indicates that a file was saved successfully. */
  47916. userCancelledSave, /**< indicates that the user aborted the save operation. */
  47917. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  47918. };
  47919. /** Tries to save the document to the last file it was saved or loaded from.
  47920. This will always try to write to the file, even if the document isn't flagged as
  47921. having changed.
  47922. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  47923. true, it will prompt the user to pick a file, as if
  47924. saveAsInteractive() was called.
  47925. @param showMessageOnFailure if true it will show a warning message when if the
  47926. save operation fails
  47927. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  47928. */
  47929. SaveResult save (bool askUserForFileIfNotSpecified,
  47930. bool showMessageOnFailure);
  47931. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  47932. it if they say yes.
  47933. If you've got a document open and want to close it (e.g. to quit the app), this is the
  47934. method to call.
  47935. If the document doesn't need saving it'll return the value savedOk so
  47936. you can go ahead and delete the document.
  47937. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  47938. return savedOk, so again, you can safely delete the document.
  47939. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  47940. close-document operation.
  47941. And if they click "save changes", it'll try to save and either return savedOk, or
  47942. failedToWriteToFile if there was a problem.
  47943. @see save, saveAs, saveAsInteractive
  47944. */
  47945. SaveResult saveIfNeededAndUserAgrees();
  47946. /** Tries to save the document to a specified file.
  47947. If this succeeds, it'll also change the document's internal file (as returned by
  47948. the getFile() method). If it fails, the file will be left unchanged.
  47949. @param newFile the file to try to write to
  47950. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  47951. the user first if they want to overwrite it
  47952. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  47953. use the saveAsInteractive() method to ask the user for a
  47954. filename
  47955. @param showMessageOnFailure if true and the write operation fails, it'll show
  47956. a message box to warn the user
  47957. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  47958. */
  47959. SaveResult saveAs (const File& newFile,
  47960. bool warnAboutOverwritingExistingFiles,
  47961. bool askUserForFileIfNotSpecified,
  47962. bool showMessageOnFailure);
  47963. /** Prompts the user for a filename and tries to save to it.
  47964. This will pop up a dialog box using the title, file extension and
  47965. wildcard specified in the document's constructor, and asks the user
  47966. for a file. If they pick one, the saveAs() method is used to try to save
  47967. to this file.
  47968. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  47969. the user first if they want to overwrite it
  47970. @see saveIfNeededAndUserAgrees, save, saveAs
  47971. */
  47972. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  47973. /** Returns the file that this document was last successfully saved or loaded from.
  47974. When the document object is created, this will be set to File::nonexistent.
  47975. It is changed when one of the load or save methods is used, or when setFile()
  47976. is used to explicitly set it.
  47977. */
  47978. const File getFile() const { return documentFile; }
  47979. /** Sets the file that this document thinks it was loaded from.
  47980. This won't actually load anything - it just changes the file stored internally.
  47981. @see getFile
  47982. */
  47983. void setFile (const File& newFile);
  47984. protected:
  47985. /** Overload this to return the title of the document.
  47986. This is used in message boxes, filenames and file choosers, so it should be
  47987. something sensible.
  47988. */
  47989. virtual const String getDocumentTitle() = 0;
  47990. /** This method should try to load your document from the given file.
  47991. If it fails, it should return an error message. If it succeeds, it should return
  47992. an empty string.
  47993. */
  47994. virtual const String loadDocument (const File& file) = 0;
  47995. /** This method should try to write your document to the given file.
  47996. If it fails, it should return an error message. If it succeeds, it should return
  47997. an empty string.
  47998. */
  47999. virtual const String saveDocument (const File& file) = 0;
  48000. /** This is used for dialog boxes to make them open at the last folder you
  48001. were using.
  48002. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  48003. the last document that was used - you might want to store this value
  48004. in a static variable, or even in your application's properties. It should
  48005. be a global setting rather than a property of this object.
  48006. This method works very well in conjunction with a RecentlyOpenedFilesList
  48007. object to manage your recent-files list.
  48008. As a default value, it's ok to return File::nonexistent, and the document
  48009. object will use a sensible one instead.
  48010. @see RecentlyOpenedFilesList
  48011. */
  48012. virtual const File getLastDocumentOpened() = 0;
  48013. /** This is used for dialog boxes to make them open at the last folder you
  48014. were using.
  48015. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  48016. the last document that was used - you might want to store this value
  48017. in a static variable, or even in your application's properties. It should
  48018. be a global setting rather than a property of this object.
  48019. This method works very well in conjunction with a RecentlyOpenedFilesList
  48020. object to manage your recent-files list.
  48021. @see RecentlyOpenedFilesList
  48022. */
  48023. virtual void setLastDocumentOpened (const File& file) = 0;
  48024. private:
  48025. File documentFile;
  48026. bool changedSinceSave;
  48027. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  48028. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  48029. };
  48030. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  48031. /*** End of inlined file: juce_FileBasedDocument.h ***/
  48032. #endif
  48033. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  48034. #endif
  48035. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  48036. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  48037. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  48038. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  48039. /**
  48040. Manages a set of files for use as a list of recently-opened documents.
  48041. This is a handy class for holding your list of recently-opened documents, with
  48042. helpful methods for things like purging any non-existent files, automatically
  48043. adding them to a menu, and making persistence easy.
  48044. @see File, FileBasedDocument
  48045. */
  48046. class JUCE_API RecentlyOpenedFilesList
  48047. {
  48048. public:
  48049. /** Creates an empty list.
  48050. */
  48051. RecentlyOpenedFilesList();
  48052. /** Destructor. */
  48053. ~RecentlyOpenedFilesList();
  48054. /** Sets a limit for the number of files that will be stored in the list.
  48055. When addFile() is called, then if there is no more space in the list, the
  48056. least-recently added file will be dropped.
  48057. @see getMaxNumberOfItems
  48058. */
  48059. void setMaxNumberOfItems (int newMaxNumber);
  48060. /** Returns the number of items that this list will store.
  48061. @see setMaxNumberOfItems
  48062. */
  48063. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  48064. /** Returns the number of files in the list.
  48065. The most recently added file is always at index 0.
  48066. */
  48067. int getNumFiles() const;
  48068. /** Returns one of the files in the list.
  48069. The most recently added file is always at index 0.
  48070. */
  48071. const File getFile (int index) const;
  48072. /** Returns an array of all the absolute pathnames in the list.
  48073. */
  48074. const StringArray& getAllFilenames() const throw() { return files; }
  48075. /** Clears all the files from the list. */
  48076. void clear();
  48077. /** Adds a file to the list.
  48078. The file will be added at index 0. If this file is already in the list, it will
  48079. be moved up to index 0, but a file can only appear once in the list.
  48080. If the list already contains the maximum number of items that is permitted, the
  48081. least-recently added file will be dropped from the end.
  48082. */
  48083. void addFile (const File& file);
  48084. /** Checks each of the files in the list, removing any that don't exist.
  48085. You might want to call this after reloading a list of files, or before putting them
  48086. on a menu.
  48087. */
  48088. void removeNonExistentFiles();
  48089. /** Adds entries to a menu, representing each of the files in the list.
  48090. This is handy for creating an "open recent file..." menu in your app. The
  48091. menu items are numbered consecutively starting with the baseItemId value,
  48092. and can either be added as complete pathnames, or just the last part of the
  48093. filename.
  48094. If dontAddNonExistentFiles is true, then each file will be checked and only those
  48095. that exist will be added.
  48096. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  48097. pointers to file objects. Any files that appear in this list will not be added to the
  48098. menu - the reason for this is that you might have a number of files already open, so
  48099. might not want these to be shown in the menu.
  48100. It returns the number of items that were added.
  48101. */
  48102. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  48103. int baseItemId,
  48104. bool showFullPaths,
  48105. bool dontAddNonExistentFiles,
  48106. const File** filesToAvoid = 0);
  48107. /** Returns a string that encapsulates all the files in the list.
  48108. The string that is returned can later be passed into restoreFromString() in
  48109. order to recreate the list. This is handy for persisting your list, e.g. in
  48110. a PropertiesFile object.
  48111. @see restoreFromString
  48112. */
  48113. const String toString() const;
  48114. /** Restores the list from a previously stringified version of the list.
  48115. Pass in a stringified version created with toString() in order to persist/restore
  48116. your list.
  48117. @see toString
  48118. */
  48119. void restoreFromString (const String& stringifiedVersion);
  48120. private:
  48121. StringArray files;
  48122. int maxNumberOfItems;
  48123. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  48124. };
  48125. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  48126. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  48127. #endif
  48128. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  48129. #endif
  48130. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  48131. /*** Start of inlined file: juce_SystemClipboard.h ***/
  48132. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  48133. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  48134. /**
  48135. Handles reading/writing to the system's clipboard.
  48136. */
  48137. class JUCE_API SystemClipboard
  48138. {
  48139. public:
  48140. /** Copies a string of text onto the clipboard */
  48141. static void copyTextToClipboard (const String& text);
  48142. /** Gets the current clipboard's contents.
  48143. Obviously this might have come from another app, so could contain
  48144. anything..
  48145. */
  48146. static const String getTextFromClipboard();
  48147. };
  48148. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  48149. /*** End of inlined file: juce_SystemClipboard.h ***/
  48150. #endif
  48151. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  48152. #endif
  48153. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  48154. #endif
  48155. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  48156. /*** Start of inlined file: juce_UnitTest.h ***/
  48157. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  48158. #define __JUCE_UNITTEST_JUCEHEADER__
  48159. class UnitTestRunner;
  48160. /**
  48161. This is a base class for classes that perform a unit test.
  48162. To write a test using this class, your code should look something like this:
  48163. @code
  48164. class MyTest : public UnitTest
  48165. {
  48166. public:
  48167. MyTest() : UnitTest ("Foobar testing") {}
  48168. void runTest()
  48169. {
  48170. beginTest ("Part 1");
  48171. expect (myFoobar.doesSomething());
  48172. expect (myFoobar.doesSomethingElse());
  48173. beginTest ("Part 2");
  48174. expect (myOtherFoobar.doesSomething());
  48175. expect (myOtherFoobar.doesSomethingElse());
  48176. ...etc..
  48177. }
  48178. };
  48179. // Creating a static instance will automatically add the instance to the array
  48180. // returned by UnitTest::getAllTests(), so the test will be included when you call
  48181. // UnitTestRunner::runAllTests()
  48182. static MyTest test;
  48183. @endcode
  48184. To run a test, use the UnitTestRunner class.
  48185. @see UnitTestRunner
  48186. */
  48187. class JUCE_API UnitTest
  48188. {
  48189. public:
  48190. /** Creates a test with the given name. */
  48191. explicit UnitTest (const String& name);
  48192. /** Destructor. */
  48193. virtual ~UnitTest();
  48194. /** Returns the name of the test. */
  48195. const String getName() const throw() { return name; }
  48196. /** Runs the test, using the specified UnitTestRunner.
  48197. You shouldn't need to call this method directly - use
  48198. UnitTestRunner::runTests() instead.
  48199. */
  48200. void performTest (UnitTestRunner* runner);
  48201. /** Returns the set of all UnitTest objects that currently exist. */
  48202. static Array<UnitTest*>& getAllTests();
  48203. /** You can optionally implement this method to set up your test.
  48204. This method will be called before runTest().
  48205. */
  48206. virtual void initialise();
  48207. /** You can optionally implement this method to clear up after your test has been run.
  48208. This method will be called after runTest() has returned.
  48209. */
  48210. virtual void shutdown();
  48211. /** Implement this method in your subclass to actually run your tests.
  48212. The content of your implementation should call beginTest() and expect()
  48213. to perform the tests.
  48214. */
  48215. virtual void runTest() = 0;
  48216. /** Tells the system that a new subsection of tests is beginning.
  48217. This should be called from your runTest() method, and may be called
  48218. as many times as you like, to demarcate different sets of tests.
  48219. */
  48220. void beginTest (const String& testName);
  48221. /** Checks that the result of a test is true, and logs this result.
  48222. In your runTest() method, you should call this method for each condition that
  48223. you want to check, e.g.
  48224. @code
  48225. void runTest()
  48226. {
  48227. beginTest ("basic tests");
  48228. expect (x + y == 2);
  48229. expect (getThing() == someThing);
  48230. ...etc...
  48231. }
  48232. @endcode
  48233. If testResult is true, a pass is logged; if it's false, a failure is logged.
  48234. If the failure message is specified, it will be written to the log if the test fails.
  48235. */
  48236. void expect (bool testResult, const String& failureMessage = String::empty);
  48237. /** Compares two values, and if they don't match, prints out a message containing the
  48238. expected and actual result values.
  48239. */
  48240. template <class ValueType>
  48241. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  48242. {
  48243. const bool result = (actual == expected);
  48244. if (! result)
  48245. {
  48246. if (failureMessage.isNotEmpty())
  48247. failureMessage << " -- ";
  48248. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  48249. }
  48250. expect (result, failureMessage);
  48251. }
  48252. /** Writes a message to the test log.
  48253. This can only be called from within your runTest() method.
  48254. */
  48255. void logMessage (const String& message);
  48256. private:
  48257. const String name;
  48258. UnitTestRunner* runner;
  48259. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  48260. };
  48261. /**
  48262. Runs a set of unit tests.
  48263. You can instantiate one of these objects and use it to invoke tests on a set of
  48264. UnitTest objects.
  48265. By using a subclass of UnitTestRunner, you can intercept logging messages and
  48266. perform custom behaviour when each test completes.
  48267. @see UnitTest
  48268. */
  48269. class JUCE_API UnitTestRunner
  48270. {
  48271. public:
  48272. /** */
  48273. UnitTestRunner();
  48274. /** Destructor. */
  48275. virtual ~UnitTestRunner();
  48276. /** Runs a set of tests.
  48277. The tests are performed in order, and the results are logged. To run all the
  48278. registered UnitTest objects that exist, use runAllTests().
  48279. */
  48280. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  48281. /** Runs all the UnitTest objects that currently exist.
  48282. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  48283. */
  48284. void runAllTests (bool assertOnFailure);
  48285. /** Contains the results of a test.
  48286. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  48287. it contains details of the number of subsequent UnitTest::expect() calls that are
  48288. made.
  48289. */
  48290. struct TestResult
  48291. {
  48292. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  48293. String unitTestName;
  48294. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  48295. String subcategoryName;
  48296. /** The number of UnitTest::expect() calls that succeeded. */
  48297. int passes;
  48298. /** The number of UnitTest::expect() calls that failed. */
  48299. int failures;
  48300. /** A list of messages describing the failed tests. */
  48301. StringArray messages;
  48302. };
  48303. /** Returns the number of TestResult objects that have been performed.
  48304. @see getResult
  48305. */
  48306. int getNumResults() const throw();
  48307. /** Returns one of the TestResult objects that describes a test that has been run.
  48308. @see getNumResults
  48309. */
  48310. const TestResult* getResult (int index) const throw();
  48311. protected:
  48312. /** Called when the list of results changes.
  48313. You can override this to perform some sort of behaviour when results are added.
  48314. */
  48315. virtual void resultsUpdated();
  48316. /** Logs a message about the current test progress.
  48317. By default this just writes the message to the Logger class, but you could override
  48318. this to do something else with the data.
  48319. */
  48320. virtual void logMessage (const String& message);
  48321. private:
  48322. friend class UnitTest;
  48323. UnitTest* currentTest;
  48324. String currentSubCategory;
  48325. OwnedArray <TestResult, CriticalSection> results;
  48326. bool assertOnFailure;
  48327. void beginNewTest (UnitTest* test, const String& subCategory);
  48328. void endTest();
  48329. void addPass();
  48330. void addFail (const String& failureMessage);
  48331. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  48332. };
  48333. #endif // __JUCE_UNITTEST_JUCEHEADER__
  48334. /*** End of inlined file: juce_UnitTest.h ***/
  48335. #endif
  48336. #endif
  48337. /*** End of inlined file: juce_app_includes.h ***/
  48338. #endif
  48339. #if JUCE_MSVC
  48340. #pragma warning (pop)
  48341. #pragma pack (pop)
  48342. #endif
  48343. #ifdef JUCE_DLL
  48344. #undef JUCE_LEAK_DETECTOR(OwnerClass)
  48345. #define JUCE_LEAK_DETECTOR(OwnerClass)
  48346. #endif
  48347. END_JUCE_NAMESPACE
  48348. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  48349. #ifdef JUCE_NAMESPACE
  48350. // this will obviously save a lot of typing, but can be disabled by
  48351. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  48352. using namespace JUCE_NAMESPACE;
  48353. /* On the Mac, these symbols are defined in the Mac libraries, so
  48354. these macros make it easier to reference them without writing out
  48355. the namespace every time.
  48356. If you run into difficulties where these macros interfere with the contents
  48357. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  48358. the comments in that file for more information.
  48359. */
  48360. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  48361. #define Component JUCE_NAMESPACE::Component
  48362. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  48363. #define Point JUCE_NAMESPACE::Point
  48364. #define Button JUCE_NAMESPACE::Button
  48365. #endif
  48366. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  48367. it easier to use the juce version explicitly.
  48368. If you run into difficulties where this macro interferes with other 3rd party header
  48369. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  48370. file for more information.
  48371. */
  48372. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  48373. #define Rectangle JUCE_NAMESPACE::Rectangle
  48374. #endif
  48375. #endif
  48376. #endif
  48377. /* Easy autolinking to the right JUCE libraries under win32.
  48378. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  48379. including this header file.
  48380. */
  48381. #if JUCE_MSVC
  48382. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  48383. /** If you want your application to link to Juce as a DLL instead of
  48384. a static library (on win32), just define the JUCE_DLL macro before
  48385. including juce.h
  48386. */
  48387. #ifdef JUCE_DLL
  48388. #if JUCE_DEBUG
  48389. #define AUTOLINKEDLIB "JUCE_debug.lib"
  48390. #else
  48391. #define AUTOLINKEDLIB "JUCE.lib"
  48392. #endif
  48393. #else
  48394. #if JUCE_DEBUG
  48395. #ifdef _WIN64
  48396. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  48397. #else
  48398. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  48399. #endif
  48400. #else
  48401. #ifdef _WIN64
  48402. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  48403. #else
  48404. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  48405. #endif
  48406. #endif
  48407. #endif
  48408. #pragma comment(lib, AUTOLINKEDLIB)
  48409. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  48410. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  48411. #endif
  48412. // Auto-link the other win32 libs that are needed by library calls..
  48413. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  48414. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  48415. // Auto-links to various win32 libs that are needed by library calls..
  48416. #pragma comment(lib, "kernel32.lib")
  48417. #pragma comment(lib, "user32.lib")
  48418. #pragma comment(lib, "shell32.lib")
  48419. #pragma comment(lib, "gdi32.lib")
  48420. #pragma comment(lib, "vfw32.lib")
  48421. #pragma comment(lib, "comdlg32.lib")
  48422. #pragma comment(lib, "winmm.lib")
  48423. #pragma comment(lib, "wininet.lib")
  48424. #pragma comment(lib, "ole32.lib")
  48425. #pragma comment(lib, "oleaut32.lib")
  48426. #pragma comment(lib, "advapi32.lib")
  48427. #pragma comment(lib, "ws2_32.lib")
  48428. #pragma comment(lib, "version.lib")
  48429. #ifdef _NATIVE_WCHAR_T_DEFINED
  48430. #ifdef _DEBUG
  48431. #pragma comment(lib, "comsuppwd.lib")
  48432. #else
  48433. #pragma comment(lib, "comsuppw.lib")
  48434. #endif
  48435. #else
  48436. #ifdef _DEBUG
  48437. #pragma comment(lib, "comsuppd.lib")
  48438. #else
  48439. #pragma comment(lib, "comsupp.lib")
  48440. #endif
  48441. #endif
  48442. #if JUCE_OPENGL
  48443. #pragma comment(lib, "OpenGL32.Lib")
  48444. #pragma comment(lib, "GlU32.Lib")
  48445. #endif
  48446. #if JUCE_QUICKTIME
  48447. #pragma comment (lib, "QTMLClient.lib")
  48448. #endif
  48449. #if JUCE_USE_CAMERA
  48450. #pragma comment (lib, "Strmiids.lib")
  48451. #pragma comment (lib, "wmvcore.lib")
  48452. #endif
  48453. #if JUCE_DIRECT2D
  48454. #pragma comment (lib, "Dwrite.lib")
  48455. #pragma comment (lib, "D2d1.lib")
  48456. #endif
  48457. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  48458. #endif
  48459. #endif
  48460. #endif
  48461. #endif // __JUCE_JUCEHEADER__
  48462. /*** End of inlined file: juce.h ***/
  48463. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__