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.

68010 lines
2.2MB

  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 64
  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 JUCE_LINUX, JUCE_IOS, JUCE_ANDROID, etc.
  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 (JUCE_ANDROID)
  76. #undef JUCE_ANDROID
  77. #define JUCE_ANDROID 1
  78. #elif defined (LINUX) || defined (__linux__)
  79. #define JUCE_LINUX 1
  80. #elif defined (__APPLE_CPP__) || defined(__APPLE_CC__)
  81. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  82. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  83. #define JUCE_IPHONE 1
  84. #define JUCE_IOS 1
  85. #else
  86. #define JUCE_MAC 1
  87. #endif
  88. #else
  89. #error "Unknown platform!"
  90. #endif
  91. #if JUCE_WINDOWS
  92. #ifdef _MSC_VER
  93. #ifdef _WIN64
  94. #define JUCE_64BIT 1
  95. #else
  96. #define JUCE_32BIT 1
  97. #endif
  98. #endif
  99. #ifdef _DEBUG
  100. #define JUCE_DEBUG 1
  101. #endif
  102. #ifdef __MINGW32__
  103. #define JUCE_MINGW 1
  104. #endif
  105. /** If defined, this indicates that the processor is little-endian. */
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #define JUCE_INTEL 1
  108. #endif
  109. #if JUCE_MAC || JUCE_IOS
  110. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  111. #define JUCE_DEBUG 1
  112. #endif
  113. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  114. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  115. #endif
  116. #ifdef __LITTLE_ENDIAN__
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #else
  119. #define JUCE_BIG_ENDIAN 1
  120. #endif
  121. #endif
  122. #if JUCE_MAC
  123. #if defined (__ppc__) || defined (__ppc64__)
  124. #define JUCE_PPC 1
  125. #else
  126. #define JUCE_INTEL 1
  127. #endif
  128. #ifdef __LP64__
  129. #define JUCE_64BIT 1
  130. #else
  131. #define JUCE_32BIT 1
  132. #endif
  133. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  134. #error "Building for OSX 10.3 is no longer supported!"
  135. #endif
  136. #ifndef MAC_OS_X_VERSION_10_5
  137. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  138. #endif
  139. #endif
  140. #if JUCE_LINUX || JUCE_ANDROID
  141. #ifdef _DEBUG
  142. #define JUCE_DEBUG 1
  143. #endif
  144. // Allow override for big-endian Linux platforms
  145. #if defined (__LITTLE_ENDIAN__) || ! defined (JUCE_BIG_ENDIAN)
  146. #define JUCE_LITTLE_ENDIAN 1
  147. #undef JUCE_BIG_ENDIAN
  148. #else
  149. #undef JUCE_LITTLE_ENDIAN
  150. #define JUCE_BIG_ENDIAN 1
  151. #endif
  152. #if defined (__LP64__) || defined (_LP64)
  153. #define JUCE_64BIT 1
  154. #else
  155. #define JUCE_32BIT 1
  156. #endif
  157. #if __MMX__ || __SSE__ || __amd64__
  158. #define JUCE_INTEL 1
  159. #endif
  160. #endif
  161. // Compiler type macros.
  162. #ifdef __GNUC__
  163. #define JUCE_GCC 1
  164. #elif defined (_MSC_VER)
  165. #define JUCE_MSVC 1
  166. #if _MSC_VER < 1500
  167. #define JUCE_VC8_OR_EARLIER 1
  168. #if _MSC_VER < 1400
  169. #define JUCE_VC7_OR_EARLIER 1
  170. #if _MSC_VER < 1300
  171. #define JUCE_VC6 1
  172. #endif
  173. #endif
  174. #endif
  175. #if ! JUCE_VC7_OR_EARLIER
  176. #define JUCE_USE_INTRINSICS 1
  177. #endif
  178. #else
  179. #error unknown compiler
  180. #endif
  181. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  182. /*** End of inlined file: juce_TargetPlatform.h ***/
  183. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  184. /*** Start of inlined file: juce_Config.h ***/
  185. #ifndef __JUCE_CONFIG_JUCEHEADER__
  186. #define __JUCE_CONFIG_JUCEHEADER__
  187. /*
  188. This file contains macros that enable/disable various JUCE features.
  189. */
  190. /** The name of the namespace that all Juce classes and functions will be
  191. put inside. If this is not defined, no namespace will be used.
  192. */
  193. #ifndef JUCE_NAMESPACE
  194. #define JUCE_NAMESPACE juce
  195. #endif
  196. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  197. project settings, but if you define this value, you can override this to force
  198. it to be true or false.
  199. */
  200. #ifndef JUCE_FORCE_DEBUG
  201. //#define JUCE_FORCE_DEBUG 0
  202. #endif
  203. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  204. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  205. Enabling it will also leave this turned on in release builds. When it's disabled,
  206. however, the jassert and jassertfalse macros will not be compiled in a
  207. release build.
  208. @see jassert, jassertfalse, Logger
  209. */
  210. #ifndef JUCE_LOG_ASSERTIONS
  211. #define JUCE_LOG_ASSERTIONS 0
  212. #endif
  213. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  214. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  215. on your Windows build machine.
  216. See the comments in the ASIOAudioIODevice class's header file for more
  217. info about this.
  218. */
  219. #ifndef JUCE_ASIO
  220. #define JUCE_ASIO 0
  221. #endif
  222. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  223. */
  224. #ifndef JUCE_WASAPI
  225. #define JUCE_WASAPI 0
  226. #endif
  227. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  228. */
  229. #ifndef JUCE_DIRECTSOUND
  230. #define JUCE_DIRECTSOUND 1
  231. #endif
  232. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  233. #ifndef JUCE_ALSA
  234. #define JUCE_ALSA 1
  235. #endif
  236. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  237. #ifndef JUCE_JACK
  238. #define JUCE_JACK 0
  239. #endif
  240. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  241. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  242. installed, and its header files will need to be on your include path.
  243. */
  244. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || JUCE_ANDROID || (JUCE_WINDOWS && ! JUCE_MSVC))
  245. #define JUCE_QUICKTIME 0
  246. #endif
  247. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  248. #undef JUCE_QUICKTIME
  249. #endif
  250. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  251. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  252. */
  253. #if ! (defined (JUCE_OPENGL) || JUCE_ANDROID)
  254. #define JUCE_OPENGL 1
  255. #endif
  256. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  257. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  258. */
  259. #ifndef JUCE_DIRECT2D
  260. #define JUCE_DIRECT2D 0
  261. #endif
  262. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  263. If your app doesn't need to read FLAC files, you might want to disable this to
  264. reduce the size of your codebase and build time.
  265. */
  266. #ifndef JUCE_USE_FLAC
  267. #define JUCE_USE_FLAC 1
  268. #endif
  269. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  270. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  271. reduce the size of your codebase and build time.
  272. */
  273. #ifndef JUCE_USE_OGGVORBIS
  274. #define JUCE_USE_OGGVORBIS 1
  275. #endif
  276. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  277. Unless you're using CD-burning, you should probably turn this flag off to
  278. reduce code size.
  279. */
  280. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  281. #define JUCE_USE_CDBURNER 1
  282. #endif
  283. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  284. Unless you're using CD-reading, you should probably turn this flag off to
  285. reduce code size.
  286. */
  287. #ifndef JUCE_USE_CDREADER
  288. #define JUCE_USE_CDREADER 1
  289. #endif
  290. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  291. */
  292. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  293. #define JUCE_USE_CAMERA 0
  294. #endif
  295. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  296. gets repainted will flash in a random colour, so that you can check exactly how much and how
  297. often your components are being drawn.
  298. */
  299. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  300. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  301. #endif
  302. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  303. Unless you specifically want to disable this, it's best to leave this option turned on.
  304. */
  305. #ifndef JUCE_USE_XINERAMA
  306. #define JUCE_USE_XINERAMA 1
  307. #endif
  308. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  309. turned on unless you have a good reason to disable it.
  310. */
  311. #ifndef JUCE_USE_XSHM
  312. #define JUCE_USE_XSHM 1
  313. #endif
  314. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  315. */
  316. #ifndef JUCE_USE_XRENDER
  317. #define JUCE_USE_XRENDER 0
  318. #endif
  319. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  320. unless you have a good reason to disable it.
  321. */
  322. #ifndef JUCE_USE_XCURSOR
  323. #define JUCE_USE_XCURSOR 1
  324. #endif
  325. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  326. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  327. you're building a plugin hosting app.
  328. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  329. */
  330. #ifndef JUCE_PLUGINHOST_VST
  331. #define JUCE_PLUGINHOST_VST 0
  332. #endif
  333. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  334. of course, and should only be enabled if you're building a plugin hosting app.
  335. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  336. */
  337. #ifndef JUCE_PLUGINHOST_AU
  338. #define JUCE_PLUGINHOST_AU 0
  339. #endif
  340. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  341. This should be enabled if you're writing a console application.
  342. */
  343. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  344. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  345. #endif
  346. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  347. If you're not using any embedded web-pages, turning this off may reduce your code size.
  348. */
  349. #ifndef JUCE_WEB_BROWSER
  350. #define JUCE_WEB_BROWSER 1
  351. #endif
  352. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  353. Carbon isn't required for a normal app, but may be needed by specialised classes like
  354. plugin-hosts, which support older APIs.
  355. */
  356. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  357. #define JUCE_SUPPORT_CARBON 1
  358. #endif
  359. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  360. You might need to tweak this if you're linking to an external zlib library in your app,
  361. but for normal apps, this option should be left alone.
  362. */
  363. #ifndef JUCE_INCLUDE_ZLIB_CODE
  364. #define JUCE_INCLUDE_ZLIB_CODE 1
  365. #endif
  366. #ifndef JUCE_INCLUDE_FLAC_CODE
  367. #define JUCE_INCLUDE_FLAC_CODE 1
  368. #endif
  369. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  370. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  371. #endif
  372. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  373. #define JUCE_INCLUDE_PNGLIB_CODE 1
  374. #endif
  375. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  376. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  377. #endif
  378. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  379. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  380. macro for more details about enabling leak checking for specific classes.
  381. */
  382. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  383. #define JUCE_CHECK_MEMORY_LEAKS 1
  384. #endif
  385. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  386. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  387. are passed to the JUCEApplication::unhandledException() callback for logging.
  388. */
  389. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  390. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  391. #endif
  392. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  393. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  394. #undef JUCE_QUICKTIME
  395. #define JUCE_QUICKTIME 0
  396. #undef JUCE_OPENGL
  397. #define JUCE_OPENGL 0
  398. #undef JUCE_USE_CDBURNER
  399. #define JUCE_USE_CDBURNER 0
  400. #undef JUCE_USE_CDREADER
  401. #define JUCE_USE_CDREADER 0
  402. #undef JUCE_WEB_BROWSER
  403. #define JUCE_WEB_BROWSER 0
  404. #undef JUCE_PLUGINHOST_AU
  405. #define JUCE_PLUGINHOST_AU 0
  406. #undef JUCE_PLUGINHOST_VST
  407. #define JUCE_PLUGINHOST_VST 0
  408. #endif
  409. #endif
  410. /*** End of inlined file: juce_Config.h ***/
  411. #ifdef JUCE_NAMESPACE
  412. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  413. #define END_JUCE_NAMESPACE }
  414. #else
  415. #define BEGIN_JUCE_NAMESPACE
  416. #define END_JUCE_NAMESPACE
  417. #endif
  418. /*** Start of inlined file: juce_PlatformDefs.h ***/
  419. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  420. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  421. /* This file defines miscellaneous macros for debugging, assertions, etc.
  422. */
  423. #ifdef JUCE_FORCE_DEBUG
  424. #undef JUCE_DEBUG
  425. #if JUCE_FORCE_DEBUG
  426. #define JUCE_DEBUG 1
  427. #endif
  428. #endif
  429. /** This macro defines the C calling convention used as the standard for Juce calls. */
  430. #if JUCE_MSVC
  431. #define JUCE_CALLTYPE __stdcall
  432. #define JUCE_CDECL __cdecl
  433. #else
  434. #define JUCE_CALLTYPE
  435. #define JUCE_CDECL
  436. #endif
  437. // Debugging and assertion macros
  438. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  439. #if JUCE_LOG_ASSERTIONS
  440. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  441. #elif JUCE_DEBUG
  442. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  443. #else
  444. #define juce_LogCurrentAssertion
  445. #endif
  446. #if JUCE_MAC || DOXYGEN
  447. /** This will try to break into the debugger if the app is currently being debugged.
  448. If called by an app that's not being debugged, the behaiour isn't defined - it may crash or not, depending
  449. on the platform.
  450. @see jassert()
  451. */
  452. #define juce_breakDebugger { Debugger(); }
  453. #elif JUCE_IOS || JUCE_LINUX || JUCE_ANDROID
  454. #define juce_breakDebugger { kill (0, SIGTRAP); }
  455. #elif JUCE_USE_INTRINSICS
  456. #pragma intrinsic (__debugbreak)
  457. #define juce_breakDebugger { __debugbreak(); }
  458. #elif JUCE_GCC
  459. #define juce_breakDebugger { asm("int $3"); }
  460. #else
  461. #define juce_breakDebugger { __asm int 3 }
  462. #endif
  463. #if JUCE_DEBUG || DOXYGEN
  464. /** Writes a string to the standard error stream.
  465. This is only compiled in a debug build.
  466. @see Logger::outputDebugString
  467. */
  468. #define DBG(dbgtext) { JUCE_NAMESPACE::String tempDbgBuf; tempDbgBuf << dbgtext; JUCE_NAMESPACE::Logger::outputDebugString (tempDbgBuf); }
  469. /** This will always cause an assertion failure.
  470. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled for your build).
  471. @see jassert
  472. */
  473. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  474. /** Platform-independent assertion macro.
  475. This macro gets turned into a no-op when you're building with debugging turned off, so be
  476. careful that the expression you pass to it doesn't perform any actions that are vital for the
  477. correct behaviour of your program!
  478. @see jassertfalse
  479. */
  480. #define jassert(expression) { if (! (expression)) jassertfalse; }
  481. #else
  482. // If debugging is disabled, these dummy debug and assertion macros are used..
  483. #define DBG(dbgtext)
  484. #define jassertfalse { juce_LogCurrentAssertion }
  485. #if JUCE_LOG_ASSERTIONS
  486. #define jassert(expression) { if (! (expression)) jassertfalse; }
  487. #else
  488. #define jassert(a) {}
  489. #endif
  490. #endif
  491. #ifndef DOXYGEN
  492. BEGIN_JUCE_NAMESPACE
  493. template <bool b> struct JuceStaticAssert;
  494. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  495. END_JUCE_NAMESPACE
  496. #endif
  497. /** A compile-time assertion macro.
  498. If the expression parameter is false, the macro will cause a compile error. (The actual error
  499. message that the compiler generates may be completely bizarre and seem to have no relation to
  500. the place where you put the static_assert though!)
  501. */
  502. #define static_jassert(expression) JUCE_NAMESPACE::JuceStaticAssert<expression>::dummy();
  503. /** This is a shorthand macro for declaring stubs for a class's copy constructor and operator=.
  504. For example, instead of
  505. @code
  506. class MyClass
  507. {
  508. etc..
  509. private:
  510. MyClass (const MyClass&);
  511. MyClass& operator= (const MyClass&);
  512. };@endcode
  513. ..you can just write:
  514. @code
  515. class MyClass
  516. {
  517. etc..
  518. private:
  519. JUCE_DECLARE_NON_COPYABLE (MyClass);
  520. };@endcode
  521. */
  522. #define JUCE_DECLARE_NON_COPYABLE(className) \
  523. className (const className&);\
  524. className& operator= (const className&)
  525. /** This is a shorthand way of writing both a JUCE_DECLARE_NON_COPYABLE and
  526. JUCE_LEAK_DETECTOR macro for a class.
  527. */
  528. #define JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className) \
  529. JUCE_DECLARE_NON_COPYABLE(className);\
  530. JUCE_LEAK_DETECTOR(className)
  531. #if ! DOXYGEN
  532. #define JUCE_JOIN_MACRO_HELPER(a, b) a ## b
  533. #endif
  534. /** A good old-fashioned C macro concatenation helper.
  535. This combines two items (which may themselves be macros) into a single string,
  536. avoiding the pitfalls of the ## macro operator.
  537. */
  538. #define JUCE_JOIN_MACRO(a, b) JUCE_JOIN_MACRO_HELPER (a, b)
  539. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  540. #define JUCE_TRY try
  541. #define JUCE_CATCH_ALL catch (...) {}
  542. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  543. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  544. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  545. #else
  546. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  547. object so they can be logged by the application if it wants to.
  548. */
  549. #define JUCE_CATCH_EXCEPTION \
  550. catch (const std::exception& e) \
  551. { \
  552. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  553. } \
  554. catch (...) \
  555. { \
  556. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  557. }
  558. #endif
  559. #else
  560. #define JUCE_TRY
  561. #define JUCE_CATCH_EXCEPTION
  562. #define JUCE_CATCH_ALL
  563. #define JUCE_CATCH_ALL_ASSERT
  564. #endif
  565. #if JUCE_DEBUG || DOXYGEN
  566. /** A platform-independent way of forcing an inline function.
  567. Use the syntax: @code
  568. forcedinline void myfunction (int x)
  569. @endcode
  570. */
  571. #define forcedinline inline
  572. #else
  573. #if JUCE_MSVC
  574. #define forcedinline __forceinline
  575. #else
  576. #define forcedinline inline __attribute__((always_inline))
  577. #endif
  578. #endif
  579. #if JUCE_MSVC || DOXYGEN
  580. /** This can be placed before a stack or member variable declaration to tell the compiler
  581. to align it to the specified number of bytes. */
  582. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  583. #else
  584. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  585. #endif
  586. // Cross-compiler deprecation macros..
  587. #if DOXYGEN || (JUCE_MSVC && ! JUCE_NO_DEPRECATION_WARNINGS)
  588. /** This can be used to wrap a function which has been deprecated. */
  589. #define JUCE_DEPRECATED(functionDef) __declspec(deprecated) functionDef
  590. #elif JUCE_GCC && ! JUCE_NO_DEPRECATION_WARNINGS
  591. #define JUCE_DEPRECATED(functionDef) functionDef __attribute__ ((deprecated))
  592. #else
  593. #define JUCE_DEPRECATED(functionDef) functionDef
  594. #endif
  595. #if JUCE_ANDROID && ! DOXYGEN
  596. #define JUCE_MODAL_LOOPS_PERMITTED 0
  597. #else
  598. /** Some operating environments don't provide a modal loop mechanism, so this flag can be
  599. used to disable any functions that try to run a modal loop. */
  600. #define JUCE_MODAL_LOOPS_PERMITTED 1
  601. #endif
  602. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  603. /*** End of inlined file: juce_PlatformDefs.h ***/
  604. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  605. #if JUCE_MSVC
  606. #if JUCE_VC6
  607. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  608. namespace std // VC6 doesn't have sqrt/sin/cos/tan/abs in std, so declare them here:
  609. {
  610. template <typename Type> Type abs (Type a) { if (a < 0) return -a; return a; }
  611. template <typename Type> Type tan (Type a) { return static_cast<Type> (::tan (static_cast<double> (a))); }
  612. template <typename Type> Type sin (Type a) { return static_cast<Type> (::sin (static_cast<double> (a))); }
  613. template <typename Type> Type cos (Type a) { return static_cast<Type> (::cos (static_cast<double> (a))); }
  614. template <typename Type> Type sqrt (Type a) { return static_cast<Type> (::sqrt (static_cast<double> (a))); }
  615. template <typename Type> Type floor (Type a) { return static_cast<Type> (::floor (static_cast<double> (a))); }
  616. template <typename Type> Type ceil (Type a) { return static_cast<Type> (::ceil (static_cast<double> (a))); }
  617. template <typename Type> Type atan2 (Type a, Type b) { return static_cast<Type> (::atan2 (static_cast<double> (a), static_cast<double> (b))); }
  618. }
  619. #endif
  620. #pragma warning (push)
  621. #pragma warning (disable: 4514 4245 4100)
  622. #endif
  623. #include <cstdlib>
  624. #include <cstdarg>
  625. #include <climits>
  626. #include <limits>
  627. #include <cmath>
  628. #include <cwchar>
  629. #include <stdexcept>
  630. #include <typeinfo>
  631. #include <cstring>
  632. #include <cstdio>
  633. #include <iostream>
  634. #if JUCE_USE_INTRINSICS
  635. #include <intrin.h>
  636. #endif
  637. #if JUCE_MAC || JUCE_IOS
  638. #include <libkern/OSAtomic.h>
  639. #endif
  640. #if JUCE_LINUX
  641. #include <signal.h>
  642. #if __INTEL_COMPILER
  643. #if __ia64__
  644. #include <ia64intrin.h>
  645. #else
  646. #include <ia32intrin.h>
  647. #endif
  648. #endif
  649. #endif
  650. #if JUCE_MSVC && JUCE_DEBUG
  651. #include <crtdbg.h>
  652. #endif
  653. #if JUCE_MSVC
  654. #include <malloc.h>
  655. #pragma warning (pop)
  656. #if ! JUCE_PUBLIC_INCLUDES
  657. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  658. #endif
  659. #endif
  660. #if JUCE_ANDROID
  661. #include <sys/atomics.h>
  662. #include <byteswap.h>
  663. #endif
  664. // DLL building settings on Win32
  665. #if JUCE_MSVC
  666. #ifdef JUCE_DLL_BUILD
  667. #define JUCE_API __declspec (dllexport)
  668. #pragma warning (disable: 4251)
  669. #elif defined (JUCE_DLL)
  670. #define JUCE_API __declspec (dllimport)
  671. #pragma warning (disable: 4251)
  672. #endif
  673. #ifdef __INTEL_COMPILER
  674. #pragma warning (disable: 1125) // (virtual override warning)
  675. #endif
  676. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  677. #ifdef JUCE_DLL_BUILD
  678. #define JUCE_API __attribute__ ((visibility("default")))
  679. #endif
  680. #endif
  681. #ifndef JUCE_API
  682. /** This macro is added to all juce public class declarations. */
  683. #define JUCE_API
  684. #endif
  685. /** This macro is added to all juce public function declarations. */
  686. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  687. /** This turns on some non-essential bits of code that should prevent old code from compiling
  688. in cases where method signatures have changed, etc.
  689. */
  690. #if (! defined (JUCE_CATCH_DEPRECATED_CODE_MISUSE)) && JUCE_DEBUG && ! DOXYGEN
  691. #define JUCE_CATCH_DEPRECATED_CODE_MISUSE 1
  692. #endif
  693. // Now include some basics that are needed by most of the Juce classes...
  694. BEGIN_JUCE_NAMESPACE
  695. extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
  696. #if JUCE_LOG_ASSERTIONS
  697. extern JUCE_API void juce_LogAssertion (const char* filename, int lineNum) throw();
  698. #endif
  699. /*** Start of inlined file: juce_Memory.h ***/
  700. #ifndef __JUCE_MEMORY_JUCEHEADER__
  701. #define __JUCE_MEMORY_JUCEHEADER__
  702. /*
  703. This file defines the various juce_malloc(), juce_free() macros that can be used in
  704. preference to the standard calls.
  705. None of this stuff is actually used in the library itself, and will probably be
  706. deprecated at some point in the future, to force everyone to use HeapBlock and other
  707. safer allocation methods.
  708. */
  709. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS && ! DOXYGEN
  710. #ifndef JUCE_DLL
  711. // Win32 debug non-DLL versions..
  712. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  713. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  714. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  715. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  716. #else
  717. // Win32 debug DLL versions..
  718. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  719. // way all juce calls in the DLL and in the host API will all use the same allocator.
  720. extern JUCE_API void* juce_DebugMalloc (int size, const char* file, int line);
  721. extern JUCE_API void* juce_DebugCalloc (int size, const char* file, int line);
  722. extern JUCE_API void* juce_DebugRealloc (void* block, int size, const char* file, int line);
  723. extern JUCE_API void juce_DebugFree (void* block);
  724. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  725. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  726. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  727. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  728. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  729. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  730. static void* operator new (size_t, void* p) { return p; } \
  731. static void operator delete (void* p) { juce_free (p); } \
  732. static void operator delete (void*, void*) {}
  733. #endif
  734. #elif defined (JUCE_DLL) && ! DOXYGEN
  735. // Win32 DLL (release) versions..
  736. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  737. // way all juce calls in the DLL and in the host API will all use the same allocator.
  738. extern JUCE_API void* juce_Malloc (int size);
  739. extern JUCE_API void* juce_Calloc (int size);
  740. extern JUCE_API void* juce_Realloc (void* block, int size);
  741. extern JUCE_API void juce_Free (void* block);
  742. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  743. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  744. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  745. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  746. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  747. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  748. static void* operator new (size_t, void* p) { return p; } \
  749. static void operator delete (void* p) { juce_free (p); } \
  750. static void operator delete (void*, void*) {}
  751. #else
  752. // Mac, Linux and Win32 (release) versions..
  753. /** This can be used instead of calling malloc directly.
  754. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  755. */
  756. #define juce_malloc(numBytes) malloc (numBytes)
  757. /** This can be used instead of calling calloc directly.
  758. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  759. */
  760. #define juce_calloc(numBytes) calloc (1, numBytes)
  761. /** This can be used instead of calling realloc directly.
  762. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  763. */
  764. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  765. /** This can be used instead of calling free directly.
  766. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  767. */
  768. #define juce_free(location) free (location)
  769. #endif
  770. /** (Deprecated) This was a win32-specific way of checking for object leaks - now please
  771. use the JUCE_LEAK_DETECTOR instead.
  772. */
  773. #ifndef juce_UseDebuggingNewOperator
  774. #define juce_UseDebuggingNewOperator
  775. #endif
  776. #if JUCE_MSVC || DOXYGEN
  777. /** This is a compiler-independent way of declaring a variable as being thread-local.
  778. E.g.
  779. @code
  780. juce_ThreadLocal int myVariable;
  781. @endcode
  782. */
  783. #define juce_ThreadLocal __declspec(thread)
  784. #else
  785. #define juce_ThreadLocal __thread
  786. #endif
  787. #if JUCE_MINGW
  788. /** This allocator is not defined in mingw gcc. */
  789. #define alloca __builtin_alloca
  790. #endif
  791. /** Fills a block of memory with zeros. */
  792. inline void zeromem (void* memory, size_t numBytes) throw() { memset (memory, 0, numBytes); }
  793. /** Overwrites a structure or object with zeros. */
  794. template <typename Type>
  795. inline void zerostruct (Type& structure) throw() { memset (&structure, 0, sizeof (structure)); }
  796. /** Delete an object pointer, and sets the pointer to null.
  797. Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
  798. or other automatic lieftime-management system rather than resorting to deleting raw pointers!
  799. */
  800. template <typename Type>
  801. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  802. /** A handy function which adds a number of bytes to any type of pointer and returns the result.
  803. This can be useful to avoid casting pointers to a char* and back when you want to move them by
  804. a specific number of bytes,
  805. */
  806. template <typename Type>
  807. inline Type* addBytesToPointer (Type* pointer, int bytes) throw() { return (Type*) (((char*) pointer) + bytes); }
  808. #endif // __JUCE_MEMORY_JUCEHEADER__
  809. /*** End of inlined file: juce_Memory.h ***/
  810. /*** Start of inlined file: juce_MathsFunctions.h ***/
  811. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  812. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  813. /*
  814. This file sets up some handy mathematical typdefs and functions.
  815. */
  816. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  817. /** A platform-independent 8-bit signed integer type. */
  818. typedef signed char int8;
  819. /** A platform-independent 8-bit unsigned integer type. */
  820. typedef unsigned char uint8;
  821. /** A platform-independent 16-bit signed integer type. */
  822. typedef signed short int16;
  823. /** A platform-independent 16-bit unsigned integer type. */
  824. typedef unsigned short uint16;
  825. /** A platform-independent 32-bit signed integer type. */
  826. typedef signed int int32;
  827. /** A platform-independent 32-bit unsigned integer type. */
  828. typedef unsigned int uint32;
  829. #if JUCE_MSVC
  830. /** A platform-independent 64-bit integer type. */
  831. typedef __int64 int64;
  832. /** A platform-independent 64-bit unsigned integer type. */
  833. typedef unsigned __int64 uint64;
  834. /** A platform-independent macro for writing 64-bit literals, needed because
  835. different compilers have different syntaxes for this.
  836. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  837. GCC, or 0x1000000000 for MSVC.
  838. */
  839. #define literal64bit(longLiteral) ((__int64) longLiteral)
  840. #else
  841. /** A platform-independent 64-bit integer type. */
  842. typedef long long int64;
  843. /** A platform-independent 64-bit unsigned integer type. */
  844. typedef unsigned long long uint64;
  845. /** A platform-independent macro for writing 64-bit literals, needed because
  846. different compilers have different syntaxes for this.
  847. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  848. GCC, or 0x1000000000 for MSVC.
  849. */
  850. #define literal64bit(longLiteral) (longLiteral##LL)
  851. #endif
  852. #if JUCE_64BIT
  853. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  854. typedef int64 pointer_sized_int;
  855. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  856. typedef uint64 pointer_sized_uint;
  857. #elif JUCE_MSVC && ! JUCE_VC6
  858. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  859. typedef _W64 int pointer_sized_int;
  860. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  861. typedef _W64 unsigned int pointer_sized_uint;
  862. #else
  863. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  864. typedef int pointer_sized_int;
  865. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  866. typedef unsigned int pointer_sized_uint;
  867. #endif
  868. // Some indispensible min/max functions
  869. /** Returns the larger of two values. */
  870. template <typename Type>
  871. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  872. /** Returns the larger of three values. */
  873. template <typename Type>
  874. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  875. /** Returns the larger of four values. */
  876. template <typename Type>
  877. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  878. /** Returns the smaller of two values. */
  879. template <typename Type>
  880. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  881. /** Returns the smaller of three values. */
  882. template <typename Type>
  883. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  884. /** Returns the smaller of four values. */
  885. template <typename Type>
  886. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  887. /** Scans an array of values, returning the minimum value that it contains. */
  888. template <typename Type>
  889. const Type findMinimum (const Type* data, int numValues)
  890. {
  891. if (numValues <= 0)
  892. return Type();
  893. Type result (*data++);
  894. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  895. {
  896. const Type& v = *data++;
  897. if (v < result) result = v;
  898. }
  899. return result;
  900. }
  901. /** Scans an array of values, returning the minimum value that it contains. */
  902. template <typename Type>
  903. const Type findMaximum (const Type* values, int numValues)
  904. {
  905. if (numValues <= 0)
  906. return Type();
  907. Type result (*values++);
  908. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  909. {
  910. const Type& v = *values++;
  911. if (result > v) result = v;
  912. }
  913. return result;
  914. }
  915. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  916. template <typename Type>
  917. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  918. {
  919. if (numValues <= 0)
  920. {
  921. lowest = Type();
  922. highest = Type();
  923. }
  924. else
  925. {
  926. Type mn (*values++);
  927. Type mx (mn);
  928. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  929. {
  930. const Type& v = *values++;
  931. if (mx < v) mx = v;
  932. if (v < mn) mn = v;
  933. }
  934. lowest = mn;
  935. highest = mx;
  936. }
  937. }
  938. /** Constrains a value to keep it within a given range.
  939. This will check that the specified value lies between the lower and upper bounds
  940. specified, and if not, will return the nearest value that would be in-range. Effectively,
  941. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  942. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  943. the results will be unpredictable.
  944. @param lowerLimit the minimum value to return
  945. @param upperLimit the maximum value to return
  946. @param valueToConstrain the value to try to return
  947. @returns the closest value to valueToConstrain which lies between lowerLimit
  948. and upperLimit (inclusive)
  949. @see jlimit0To, jmin, jmax
  950. */
  951. template <typename Type>
  952. inline Type jlimit (const Type lowerLimit,
  953. const Type upperLimit,
  954. const Type valueToConstrain) throw()
  955. {
  956. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  957. return (valueToConstrain < lowerLimit) ? lowerLimit
  958. : ((upperLimit < valueToConstrain) ? upperLimit
  959. : valueToConstrain);
  960. }
  961. /** Returns true if a value is at least zero, and also below a specified upper limit.
  962. This is basically a quicker way to write:
  963. @code valueToTest >= 0 && valueToTest < upperLimit
  964. @endcode
  965. */
  966. template <typename Type>
  967. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) throw()
  968. {
  969. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  970. return Type() <= valueToTest && valueToTest < upperLimit;
  971. }
  972. #if ! JUCE_VC6
  973. template <>
  974. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) throw()
  975. {
  976. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  977. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  978. }
  979. #endif
  980. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  981. This is basically a quicker way to write:
  982. @code valueToTest >= 0 && valueToTest <= upperLimit
  983. @endcode
  984. */
  985. template <typename Type>
  986. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) throw()
  987. {
  988. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  989. return Type() <= valueToTest && valueToTest <= upperLimit;
  990. }
  991. #if ! JUCE_VC6
  992. template <>
  993. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) throw()
  994. {
  995. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  996. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  997. }
  998. #endif
  999. /** Handy function to swap two values over.
  1000. */
  1001. template <typename Type>
  1002. inline void swapVariables (Type& variable1, Type& variable2)
  1003. {
  1004. const Type tempVal = variable1;
  1005. variable1 = variable2;
  1006. variable2 = tempVal;
  1007. }
  1008. #if JUCE_VC6
  1009. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  1010. #else
  1011. /** Handy function for getting the number of elements in a simple const C array.
  1012. E.g.
  1013. @code
  1014. static int myArray[] = { 1, 2, 3 };
  1015. int numElements = numElementsInArray (myArray) // returns 3
  1016. @endcode
  1017. */
  1018. template <typename Type, int N>
  1019. inline int numElementsInArray (Type (&array)[N])
  1020. {
  1021. (void) array; // (required to avoid a spurious warning in MS compilers)
  1022. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  1023. return N;
  1024. }
  1025. #endif
  1026. // Some useful maths functions that aren't always present with all compilers and build settings.
  1027. /** Using juce_hypot is easier than dealing with the different types of hypot function
  1028. that are provided by the various platforms and compilers. */
  1029. template <typename Type>
  1030. inline Type juce_hypot (Type a, Type b) throw()
  1031. {
  1032. #if JUCE_WINDOWS
  1033. return static_cast <Type> (_hypot (a, b));
  1034. #else
  1035. return static_cast <Type> (hypot (a, b));
  1036. #endif
  1037. }
  1038. /** 64-bit abs function. */
  1039. inline int64 abs64 (const int64 n) throw()
  1040. {
  1041. return (n >= 0) ? n : -n;
  1042. }
  1043. /** This templated negate function will negate pointers as well as integers */
  1044. template <typename Type>
  1045. inline Type juce_negate (Type n) throw()
  1046. {
  1047. return sizeof (Type) == 1 ? (Type) -(signed char) n
  1048. : (sizeof (Type) == 2 ? (Type) -(short) n
  1049. : (sizeof (Type) == 4 ? (Type) -(int) n
  1050. : ((Type) -(int64) n)));
  1051. }
  1052. /** This templated negate function will negate pointers as well as integers */
  1053. template <typename Type>
  1054. inline Type* juce_negate (Type* n) throw()
  1055. {
  1056. return (Type*) -(pointer_sized_int) n;
  1057. }
  1058. /** A predefined value for Pi, at double-precision.
  1059. @see float_Pi
  1060. */
  1061. const double double_Pi = 3.1415926535897932384626433832795;
  1062. /** A predefined value for Pi, at sngle-precision.
  1063. @see double_Pi
  1064. */
  1065. const float float_Pi = 3.14159265358979323846f;
  1066. /** The isfinite() method seems to vary between platforms, so this is a
  1067. platform-independent function for it.
  1068. */
  1069. template <typename FloatingPointType>
  1070. inline bool juce_isfinite (FloatingPointType value)
  1071. {
  1072. #if JUCE_WINDOWS
  1073. return _finite (value);
  1074. #elif JUCE_ANDROID
  1075. return isfinite (value);
  1076. #else
  1077. return std::isfinite (value);
  1078. #endif
  1079. }
  1080. /** Fast floating-point-to-integer conversion.
  1081. This is faster than using the normal c++ cast to convert a float to an int, and
  1082. it will round the value to the nearest integer, rather than rounding it down
  1083. like the normal cast does.
  1084. Note that this routine gets its speed at the expense of some accuracy, and when
  1085. rounding values whose floating point component is exactly 0.5, odd numbers and
  1086. even numbers will be rounded up or down differently.
  1087. */
  1088. template <typename FloatType>
  1089. inline int roundToInt (const FloatType value) throw()
  1090. {
  1091. union { int asInt[2]; double asDouble; } n;
  1092. n.asDouble = ((double) value) + 6755399441055744.0;
  1093. #if JUCE_BIG_ENDIAN
  1094. return n.asInt [1];
  1095. #else
  1096. return n.asInt [0];
  1097. #endif
  1098. }
  1099. /** Fast floating-point-to-integer conversion.
  1100. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1101. fine for values above zero, but negative numbers are rounded the wrong way.
  1102. */
  1103. inline int roundToIntAccurate (const double value) throw()
  1104. {
  1105. return roundToInt (value + 1.5e-8);
  1106. }
  1107. /** Fast floating-point-to-integer conversion.
  1108. This is faster than using the normal c++ cast to convert a double to an int, and
  1109. it will round the value to the nearest integer, rather than rounding it down
  1110. like the normal cast does.
  1111. Note that this routine gets its speed at the expense of some accuracy, and when
  1112. rounding values whose floating point component is exactly 0.5, odd numbers and
  1113. even numbers will be rounded up or down differently. For a more accurate conversion,
  1114. see roundDoubleToIntAccurate().
  1115. */
  1116. inline int roundDoubleToInt (const double value) throw()
  1117. {
  1118. return roundToInt (value);
  1119. }
  1120. /** Fast floating-point-to-integer conversion.
  1121. This is faster than using the normal c++ cast to convert a float to an int, and
  1122. it will round the value to the nearest integer, rather than rounding it down
  1123. like the normal cast does.
  1124. Note that this routine gets its speed at the expense of some accuracy, and when
  1125. rounding values whose floating point component is exactly 0.5, odd numbers and
  1126. even numbers will be rounded up or down differently.
  1127. */
  1128. inline int roundFloatToInt (const float value) throw()
  1129. {
  1130. return roundToInt (value);
  1131. }
  1132. /** This namespace contains a few template classes for helping work out class type variations.
  1133. */
  1134. namespace TypeHelpers
  1135. {
  1136. #if JUCE_VC8_OR_EARLIER
  1137. #define PARAMETER_TYPE(type) const type&
  1138. #else
  1139. /** The ParameterType struct is used to find the best type to use when passing some kind
  1140. of object as a parameter.
  1141. Of course, this is only likely to be useful in certain esoteric template situations.
  1142. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1143. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1144. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1145. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1146. pass-by-value, but passing objects as a const reference, to avoid copying.
  1147. */
  1148. template <typename Type> struct ParameterType { typedef const Type& type; };
  1149. #if ! DOXYGEN
  1150. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1151. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1152. template <> struct ParameterType <char> { typedef char type; };
  1153. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1154. template <> struct ParameterType <short> { typedef short type; };
  1155. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1156. template <> struct ParameterType <int> { typedef int type; };
  1157. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1158. template <> struct ParameterType <long> { typedef long type; };
  1159. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1160. template <> struct ParameterType <int64> { typedef int64 type; };
  1161. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1162. template <> struct ParameterType <bool> { typedef bool type; };
  1163. template <> struct ParameterType <float> { typedef float type; };
  1164. template <> struct ParameterType <double> { typedef double type; };
  1165. #endif
  1166. /** A helpful macro to simplify the use of the ParameterType template.
  1167. @see ParameterType
  1168. */
  1169. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1170. #endif
  1171. }
  1172. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1173. /*** End of inlined file: juce_MathsFunctions.h ***/
  1174. /*** Start of inlined file: juce_ByteOrder.h ***/
  1175. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1176. #define __JUCE_BYTEORDER_JUCEHEADER__
  1177. /** Contains static methods for converting the byte order between different
  1178. endiannesses.
  1179. */
  1180. class JUCE_API ByteOrder
  1181. {
  1182. public:
  1183. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1184. static uint16 swap (uint16 value);
  1185. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1186. static uint32 swap (uint32 value);
  1187. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1188. static uint64 swap (uint64 value);
  1189. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1190. static uint16 swapIfBigEndian (uint16 value);
  1191. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1192. static uint32 swapIfBigEndian (uint32 value);
  1193. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1194. static uint64 swapIfBigEndian (uint64 value);
  1195. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1196. static uint16 swapIfLittleEndian (uint16 value);
  1197. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1198. static uint32 swapIfLittleEndian (uint32 value);
  1199. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1200. static uint64 swapIfLittleEndian (uint64 value);
  1201. /** Turns 4 bytes into a little-endian integer. */
  1202. static uint32 littleEndianInt (const void* bytes);
  1203. /** Turns 2 bytes into a little-endian integer. */
  1204. static uint16 littleEndianShort (const void* bytes);
  1205. /** Turns 4 bytes into a big-endian integer. */
  1206. static uint32 bigEndianInt (const void* bytes);
  1207. /** Turns 2 bytes into a big-endian integer. */
  1208. static uint16 bigEndianShort (const void* bytes);
  1209. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1210. static int littleEndian24Bit (const char* bytes);
  1211. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1212. static int bigEndian24Bit (const char* bytes);
  1213. /** Copies a 24-bit number to 3 little-endian bytes. */
  1214. static void littleEndian24BitToChars (int value, char* destBytes);
  1215. /** Copies a 24-bit number to 3 big-endian bytes. */
  1216. static void bigEndian24BitToChars (int value, char* destBytes);
  1217. /** Returns true if the current CPU is big-endian. */
  1218. static bool isBigEndian();
  1219. private:
  1220. ByteOrder();
  1221. JUCE_DECLARE_NON_COPYABLE (ByteOrder);
  1222. };
  1223. #if JUCE_USE_INTRINSICS
  1224. #pragma intrinsic (_byteswap_ulong)
  1225. #endif
  1226. inline uint16 ByteOrder::swap (uint16 n)
  1227. {
  1228. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1229. return static_cast <uint16> (_byteswap_ushort (n));
  1230. #else
  1231. return static_cast <uint16> ((n << 8) | (n >> 8));
  1232. #endif
  1233. }
  1234. inline uint32 ByteOrder::swap (uint32 n)
  1235. {
  1236. #if JUCE_MAC || JUCE_IOS
  1237. return OSSwapInt32 (n);
  1238. #elif JUCE_GCC && JUCE_INTEL
  1239. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1240. return n;
  1241. #elif JUCE_USE_INTRINSICS
  1242. return _byteswap_ulong (n);
  1243. #elif JUCE_MSVC
  1244. __asm {
  1245. mov eax, n
  1246. bswap eax
  1247. mov n, eax
  1248. }
  1249. return n;
  1250. #elif JUCE_ANDROID
  1251. return bswap_32 (n);
  1252. #else
  1253. return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8);
  1254. #endif
  1255. }
  1256. inline uint64 ByteOrder::swap (uint64 value)
  1257. {
  1258. #if JUCE_MAC || JUCE_IOS
  1259. return OSSwapInt64 (value);
  1260. #elif JUCE_USE_INTRINSICS
  1261. return _byteswap_uint64 (value);
  1262. #else
  1263. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1264. #endif
  1265. }
  1266. #if JUCE_LITTLE_ENDIAN
  1267. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1268. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1269. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1270. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1271. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1272. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1273. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1274. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1275. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1276. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1277. inline bool ByteOrder::isBigEndian() { return false; }
  1278. #else
  1279. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1280. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1281. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1282. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1283. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1284. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1285. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1286. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1287. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1288. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1289. inline bool ByteOrder::isBigEndian() { return true; }
  1290. #endif
  1291. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1292. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1293. 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); }
  1294. 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); }
  1295. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1296. /*** End of inlined file: juce_ByteOrder.h ***/
  1297. /*** Start of inlined file: juce_Logger.h ***/
  1298. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1299. #define __JUCE_LOGGER_JUCEHEADER__
  1300. /*** Start of inlined file: juce_String.h ***/
  1301. #ifndef __JUCE_STRING_JUCEHEADER__
  1302. #define __JUCE_STRING_JUCEHEADER__
  1303. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1304. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1305. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1306. #if JUCE_WINDOWS && ! DOXYGEN
  1307. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1308. #define JUCE_NATIVE_WCHAR_IS_UTF16 1
  1309. #define JUCE_NATIVE_WCHAR_IS_UTF32 0
  1310. #else
  1311. /** This macro will be set to 1 if the compiler's native wchar_t is an 8-bit type. */
  1312. #define JUCE_NATIVE_WCHAR_IS_UTF8 0
  1313. /** This macro will be set to 1 if the compiler's native wchar_t is a 16-bit type. */
  1314. #define JUCE_NATIVE_WCHAR_IS_UTF16 0
  1315. /** This macro will be set to 1 if the compiler's native wchar_t is a 32-bit type. */
  1316. #define JUCE_NATIVE_WCHAR_IS_UTF32 1
  1317. #endif
  1318. #if JUCE_NATIVE_WCHAR_IS_UTF32 || DOXYGEN
  1319. /** A platform-independent 32-bit unicode character type. */
  1320. typedef wchar_t juce_wchar;
  1321. #else
  1322. typedef uint32 juce_wchar;
  1323. #endif
  1324. /** This macro is deprecated, but preserved for compatibility with old code.*/
  1325. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1326. #if ! JUCE_DONT_DEFINE_MACROS
  1327. /** The 'T' macro is an alternative for using the "L" prefix in front of a string literal.
  1328. This macro is deprectated, but kept here for compatibility with old code. The best (i.e.
  1329. most portable) way to encode your string literals is just as standard 8-bit strings, but
  1330. using escaped utf-8 character codes for extended characters.
  1331. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1332. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1333. the juce/src directory) to avoid defining this macro. See the comments in
  1334. juce_withoutMacros.h for more info.
  1335. */
  1336. #define T(stringLiteral) JUCE_T(stringLiteral)
  1337. #endif
  1338. #undef max
  1339. #undef min
  1340. /**
  1341. A set of methods for manipulating characters and character strings.
  1342. These are defined as wrappers around the basic C string handlers, to provide
  1343. a clean, cross-platform layer, (because various platforms differ in the
  1344. range of C library calls that they provide).
  1345. @see String
  1346. */
  1347. class JUCE_API CharacterFunctions
  1348. {
  1349. public:
  1350. static juce_wchar toUpperCase (juce_wchar character) throw();
  1351. static juce_wchar toLowerCase (juce_wchar character) throw();
  1352. static bool isUpperCase (juce_wchar character) throw();
  1353. static bool isLowerCase (juce_wchar character) throw();
  1354. static bool isWhitespace (char character) throw();
  1355. static bool isWhitespace (juce_wchar character) throw();
  1356. static bool isDigit (char character) throw();
  1357. static bool isDigit (juce_wchar character) throw();
  1358. static bool isLetter (char character) throw();
  1359. static bool isLetter (juce_wchar character) throw();
  1360. static bool isLetterOrDigit (char character) throw();
  1361. static bool isLetterOrDigit (juce_wchar character) throw();
  1362. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legal hex digit. */
  1363. static int getHexDigitValue (juce_wchar digit) throw();
  1364. template <typename CharPointerType>
  1365. static double readDoubleValue (CharPointerType& text) throw()
  1366. {
  1367. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  1368. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  1369. int exponent = 0, decPointIndex = 0, digit = 0;
  1370. int lastDigit = 0, numSignificantDigits = 0;
  1371. bool isNegative = false, digitsFound = false;
  1372. const int maxSignificantDigits = 15 + 2;
  1373. text = text.findEndOfWhitespace();
  1374. juce_wchar c = *text;
  1375. switch (c)
  1376. {
  1377. case '-': isNegative = true; // fall-through..
  1378. case '+': c = *++text;
  1379. }
  1380. switch (c)
  1381. {
  1382. case 'n':
  1383. case 'N':
  1384. if ((text[1] == 'a' || text[1] == 'A') && (text[2] == 'n' || text[2] == 'N'))
  1385. return std::numeric_limits<double>::quiet_NaN();
  1386. break;
  1387. case 'i':
  1388. case 'I':
  1389. if ((text[1] == 'n' || text[1] == 'N') && (text[2] == 'f' || text[2] == 'F'))
  1390. return std::numeric_limits<double>::infinity();
  1391. break;
  1392. }
  1393. for (;;)
  1394. {
  1395. if (text.isDigit())
  1396. {
  1397. lastDigit = digit;
  1398. digit = text.getAndAdvance() - '0';
  1399. digitsFound = true;
  1400. if (decPointIndex != 0)
  1401. exponentAdjustment[1]++;
  1402. if (numSignificantDigits == 0 && digit == 0)
  1403. continue;
  1404. if (++numSignificantDigits > maxSignificantDigits)
  1405. {
  1406. if (digit > 5)
  1407. ++accumulator [decPointIndex];
  1408. else if (digit == 5 && (lastDigit & 1) != 0)
  1409. ++accumulator [decPointIndex];
  1410. if (decPointIndex > 0)
  1411. exponentAdjustment[1]--;
  1412. else
  1413. exponentAdjustment[0]++;
  1414. while (text.isDigit())
  1415. {
  1416. ++text;
  1417. if (decPointIndex == 0)
  1418. exponentAdjustment[0]++;
  1419. }
  1420. }
  1421. else
  1422. {
  1423. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  1424. if (accumulator [decPointIndex] > maxAccumulatorValue)
  1425. {
  1426. result [decPointIndex] = mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  1427. + accumulator [decPointIndex];
  1428. accumulator [decPointIndex] = 0;
  1429. exponentAccumulator [decPointIndex] = 0;
  1430. }
  1431. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  1432. exponentAccumulator [decPointIndex]++;
  1433. }
  1434. }
  1435. else if (decPointIndex == 0 && *text == '.')
  1436. {
  1437. ++text;
  1438. decPointIndex = 1;
  1439. if (numSignificantDigits > maxSignificantDigits)
  1440. {
  1441. while (text.isDigit())
  1442. ++text;
  1443. break;
  1444. }
  1445. }
  1446. else
  1447. {
  1448. break;
  1449. }
  1450. }
  1451. result[0] = mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  1452. if (decPointIndex != 0)
  1453. result[1] = mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  1454. c = *text;
  1455. if ((c == 'e' || c == 'E') && digitsFound)
  1456. {
  1457. bool negativeExponent = false;
  1458. switch (*++text)
  1459. {
  1460. case '-': negativeExponent = true; // fall-through..
  1461. case '+': ++text;
  1462. }
  1463. while (text.isDigit())
  1464. exponent = (exponent * 10) + (text.getAndAdvance() - '0');
  1465. if (negativeExponent)
  1466. exponent = -exponent;
  1467. }
  1468. double r = mulexp10 (result[0], exponent + exponentAdjustment[0]);
  1469. if (decPointIndex != 0)
  1470. r += mulexp10 (result[1], exponent - exponentAdjustment[1]);
  1471. return isNegative ? -r : r;
  1472. }
  1473. template <typename CharPointerType>
  1474. static double getDoubleValue (const CharPointerType& text) throw()
  1475. {
  1476. CharPointerType t (text);
  1477. return readDoubleValue (t);
  1478. }
  1479. template <typename IntType, typename CharPointerType>
  1480. static IntType getIntValue (const CharPointerType& text) throw()
  1481. {
  1482. IntType v = 0;
  1483. CharPointerType s (text.findEndOfWhitespace());
  1484. const bool isNeg = *s == '-';
  1485. if (isNeg)
  1486. ++s;
  1487. for (;;)
  1488. {
  1489. const juce_wchar c = s.getAndAdvance();
  1490. if (c >= '0' && c <= '9')
  1491. v = v * 10 + (IntType) (c - '0');
  1492. else
  1493. break;
  1494. }
  1495. return isNeg ? -v : v;
  1496. }
  1497. template <typename CharPointerType>
  1498. static size_t lengthUpTo (CharPointerType text, const size_t maxCharsToCount) throw()
  1499. {
  1500. size_t len = 0;
  1501. while (len < maxCharsToCount && text.getAndAdvance() != 0)
  1502. ++len;
  1503. return len;
  1504. }
  1505. template <typename CharPointerType>
  1506. static size_t lengthUpTo (CharPointerType start, const CharPointerType& end) throw()
  1507. {
  1508. size_t len = 0;
  1509. while (start < end && start.getAndAdvance() != 0)
  1510. ++len;
  1511. return len;
  1512. }
  1513. template <typename DestCharPointerType, typename SrcCharPointerType>
  1514. static void copyAll (DestCharPointerType& dest, SrcCharPointerType src) throw()
  1515. {
  1516. for (;;)
  1517. {
  1518. const juce_wchar c = src.getAndAdvance();
  1519. if (c == 0)
  1520. break;
  1521. dest.write (c);
  1522. }
  1523. dest.writeNull();
  1524. }
  1525. template <typename DestCharPointerType, typename SrcCharPointerType>
  1526. static int copyWithDestByteLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxBytes) throw()
  1527. {
  1528. int numBytesDone = 0;
  1529. maxBytes -= sizeof (typename DestCharPointerType::CharType); // (allow for a terminating null)
  1530. for (;;)
  1531. {
  1532. const juce_wchar c = src.getAndAdvance();
  1533. const int bytesNeeded = (int) DestCharPointerType::getBytesRequiredFor (c);
  1534. maxBytes -= bytesNeeded;
  1535. if (c == 0 || maxBytes < 0)
  1536. break;
  1537. numBytesDone += bytesNeeded;
  1538. dest.write (c);
  1539. }
  1540. dest.writeNull();
  1541. return numBytesDone;
  1542. }
  1543. template <typename DestCharPointerType, typename SrcCharPointerType>
  1544. static void copyWithCharLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxChars) throw()
  1545. {
  1546. while (--maxChars > 0)
  1547. {
  1548. const juce_wchar c = src.getAndAdvance();
  1549. if (c == 0)
  1550. break;
  1551. dest.write (c);
  1552. }
  1553. dest.writeNull();
  1554. }
  1555. template <typename CharPointerType1, typename CharPointerType2>
  1556. static int compare (CharPointerType1 s1, CharPointerType2 s2) throw()
  1557. {
  1558. for (;;)
  1559. {
  1560. const int c1 = (int) s1.getAndAdvance();
  1561. const int c2 = (int) s2.getAndAdvance();
  1562. const int diff = c1 - c2;
  1563. if (diff != 0)
  1564. return diff < 0 ? -1 : 1;
  1565. else if (c1 == 0)
  1566. break;
  1567. }
  1568. return 0;
  1569. }
  1570. template <typename CharPointerType1, typename CharPointerType2>
  1571. static int compareUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) throw()
  1572. {
  1573. while (--maxChars >= 0)
  1574. {
  1575. const int c1 = (int) s1.getAndAdvance();
  1576. const int c2 = (int) s2.getAndAdvance();
  1577. const int diff = c1 - c2;
  1578. if (diff != 0)
  1579. return diff < 0 ? -1 : 1;
  1580. else if (c1 == 0)
  1581. break;
  1582. }
  1583. return 0;
  1584. }
  1585. template <typename CharPointerType1, typename CharPointerType2>
  1586. static int compareIgnoreCase (CharPointerType1 s1, CharPointerType2 s2) throw()
  1587. {
  1588. for (;;)
  1589. {
  1590. int c1 = s1.toUpperCase();
  1591. int c2 = s2.toUpperCase();
  1592. ++s1;
  1593. ++s2;
  1594. const int diff = c1 - c2;
  1595. if (diff != 0)
  1596. return diff < 0 ? -1 : 1;
  1597. else if (c1 == 0)
  1598. break;
  1599. }
  1600. return 0;
  1601. }
  1602. template <typename CharPointerType1, typename CharPointerType2>
  1603. static int compareIgnoreCaseUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) throw()
  1604. {
  1605. while (--maxChars >= 0)
  1606. {
  1607. int c1 = s1.toUpperCase();
  1608. int c2 = s2.toUpperCase();
  1609. ++s1;
  1610. ++s2;
  1611. const int diff = c1 - c2;
  1612. if (diff != 0)
  1613. return diff < 0 ? -1 : 1;
  1614. else if (c1 == 0)
  1615. break;
  1616. }
  1617. return 0;
  1618. }
  1619. template <typename CharPointerType1, typename CharPointerType2>
  1620. static int indexOf (CharPointerType1 haystack, const CharPointerType2& needle) throw()
  1621. {
  1622. int index = 0;
  1623. const int needleLength = (int) needle.length();
  1624. for (;;)
  1625. {
  1626. if (haystack.compareUpTo (needle, needleLength) == 0)
  1627. return index;
  1628. if (haystack.getAndAdvance() == 0)
  1629. return -1;
  1630. ++index;
  1631. }
  1632. }
  1633. template <typename CharPointerType1, typename CharPointerType2>
  1634. static int indexOfIgnoreCase (CharPointerType1 haystack, const CharPointerType2& needle) throw()
  1635. {
  1636. int index = 0;
  1637. const int needleLength = (int) needle.length();
  1638. for (;;)
  1639. {
  1640. if (haystack.compareIgnoreCaseUpTo (needle, needleLength) == 0)
  1641. return index;
  1642. if (haystack.getAndAdvance() == 0)
  1643. return -1;
  1644. ++index;
  1645. }
  1646. }
  1647. template <typename Type>
  1648. static int indexOfChar (Type text, const juce_wchar charToFind) throw()
  1649. {
  1650. int i = 0;
  1651. while (! text.isEmpty())
  1652. {
  1653. if (text.getAndAdvance() == charToFind)
  1654. return i;
  1655. ++i;
  1656. }
  1657. return -1;
  1658. }
  1659. template <typename Type>
  1660. static int indexOfCharIgnoreCase (Type text, juce_wchar charToFind) throw()
  1661. {
  1662. charToFind = CharacterFunctions::toLowerCase (charToFind);
  1663. int i = 0;
  1664. while (! text.isEmpty())
  1665. {
  1666. if (text.toLowerCase() == charToFind)
  1667. return i;
  1668. ++text;
  1669. ++i;
  1670. }
  1671. return -1;
  1672. }
  1673. template <typename Type>
  1674. static Type findEndOfWhitespace (const Type& text) throw()
  1675. {
  1676. Type p (text);
  1677. while (p.isWhitespace())
  1678. ++p;
  1679. return p;
  1680. }
  1681. template <typename Type>
  1682. static Type findEndOfToken (const Type& text, const Type& breakCharacters, const Type& quoteCharacters)
  1683. {
  1684. Type t (text);
  1685. juce_wchar currentQuoteChar = 0;
  1686. while (! t.isEmpty())
  1687. {
  1688. const juce_wchar c = t.getAndAdvance();
  1689. if (currentQuoteChar == 0 && breakCharacters.indexOf (c) >= 0)
  1690. {
  1691. --t;
  1692. break;
  1693. }
  1694. if (quoteCharacters.indexOf (c) >= 0)
  1695. {
  1696. if (currentQuoteChar == 0)
  1697. currentQuoteChar = c;
  1698. else if (currentQuoteChar == c)
  1699. currentQuoteChar = 0;
  1700. }
  1701. }
  1702. return t;
  1703. }
  1704. private:
  1705. static double mulexp10 (const double value, int exponent) throw();
  1706. };
  1707. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1708. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1709. #ifndef JUCE_STRING_UTF_TYPE
  1710. #define JUCE_STRING_UTF_TYPE 8
  1711. #endif
  1712. #if JUCE_MSVC
  1713. #pragma warning (push)
  1714. #pragma warning (disable: 4514 4996)
  1715. #endif
  1716. /*** Start of inlined file: juce_Atomic.h ***/
  1717. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1718. #define __JUCE_ATOMIC_JUCEHEADER__
  1719. /**
  1720. Simple class to hold a primitive value and perform atomic operations on it.
  1721. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  1722. There are methods to perform most of the basic atomic operations.
  1723. */
  1724. template <typename Type>
  1725. class Atomic
  1726. {
  1727. public:
  1728. /** Creates a new value, initialised to zero. */
  1729. inline Atomic() throw()
  1730. : value (0)
  1731. {
  1732. }
  1733. /** Creates a new value, with a given initial value. */
  1734. inline Atomic (const Type initialValue) throw()
  1735. : value (initialValue)
  1736. {
  1737. }
  1738. /** Copies another value (atomically). */
  1739. inline Atomic (const Atomic& other) throw()
  1740. : value (other.get())
  1741. {
  1742. }
  1743. /** Destructor. */
  1744. inline ~Atomic() throw()
  1745. {
  1746. // This class can only be used for types which are 32 or 64 bits in size.
  1747. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  1748. }
  1749. /** Atomically reads and returns the current value. */
  1750. Type get() const throw();
  1751. /** Copies another value onto this one (atomically). */
  1752. inline Atomic& operator= (const Atomic& other) throw() { exchange (other.get()); return *this; }
  1753. /** Copies another value onto this one (atomically). */
  1754. inline Atomic& operator= (const Type newValue) throw() { exchange (newValue); return *this; }
  1755. /** Atomically sets the current value. */
  1756. void set (Type newValue) throw() { exchange (newValue); }
  1757. /** Atomically sets the current value, returning the value that was replaced. */
  1758. Type exchange (Type value) throw();
  1759. /** Atomically adds a number to this value, returning the new value. */
  1760. Type operator+= (Type amountToAdd) throw();
  1761. /** Atomically subtracts a number from this value, returning the new value. */
  1762. Type operator-= (Type amountToSubtract) throw();
  1763. /** Atomically increments this value, returning the new value. */
  1764. Type operator++() throw();
  1765. /** Atomically decrements this value, returning the new value. */
  1766. Type operator--() throw();
  1767. /** Atomically compares this value with a target value, and if it is equal, sets
  1768. this to be equal to a new value.
  1769. This operation is the atomic equivalent of doing this:
  1770. @code
  1771. bool compareAndSetBool (Type newValue, Type valueToCompare)
  1772. {
  1773. if (get() == valueToCompare)
  1774. {
  1775. set (newValue);
  1776. return true;
  1777. }
  1778. return false;
  1779. }
  1780. @endcode
  1781. @returns true if the comparison was true and the value was replaced; false if
  1782. the comparison failed and the value was left unchanged.
  1783. @see compareAndSetValue
  1784. */
  1785. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  1786. /** Atomically compares this value with a target value, and if it is equal, sets
  1787. this to be equal to a new value.
  1788. This operation is the atomic equivalent of doing this:
  1789. @code
  1790. Type compareAndSetValue (Type newValue, Type valueToCompare)
  1791. {
  1792. Type oldValue = get();
  1793. if (oldValue == valueToCompare)
  1794. set (newValue);
  1795. return oldValue;
  1796. }
  1797. @endcode
  1798. @returns the old value before it was changed.
  1799. @see compareAndSetBool
  1800. */
  1801. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  1802. /** Implements a memory read/write barrier. */
  1803. static void memoryBarrier() throw();
  1804. #if JUCE_64BIT
  1805. JUCE_ALIGN (8)
  1806. #else
  1807. JUCE_ALIGN (4)
  1808. #endif
  1809. /** The raw value that this class operates on.
  1810. This is exposed publically in case you need to manipulate it directly
  1811. for performance reasons.
  1812. */
  1813. volatile Type value;
  1814. private:
  1815. static inline Type castFrom32Bit (int32 value) throw() { return *(Type*) &value; }
  1816. static inline Type castFrom64Bit (int64 value) throw() { return *(Type*) &value; }
  1817. static inline int32 castTo32Bit (Type value) throw() { return *(int32*) &value; }
  1818. static inline int64 castTo64Bit (Type value) throw() { return *(int64*) &value; }
  1819. Type operator++ (int); // better to just use pre-increment with atomics..
  1820. Type operator-- (int);
  1821. };
  1822. /*
  1823. The following code is in the header so that the atomics can be inlined where possible...
  1824. */
  1825. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1826. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1827. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1828. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1829. #define JUCE_MAC_ATOMICS_VOLATILE
  1830. #else
  1831. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1832. #endif
  1833. #if JUCE_PPC || JUCE_IOS
  1834. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1835. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return *a += b; }
  1836. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return ++*a; }
  1837. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return --*a; }
  1838. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) throw()
  1839. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1840. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1841. #endif
  1842. #elif JUCE_ANDROID
  1843. #define JUCE_ATOMICS_ANDROID 1 // Android atomic functions
  1844. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1845. #elif JUCE_GCC
  1846. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1847. #if JUCE_IOS
  1848. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1849. #endif
  1850. #else
  1851. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1852. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1853. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1854. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1855. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1856. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1857. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1858. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1859. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1860. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1861. #define juce_MemoryBarrier _ReadWriteBarrier
  1862. #else
  1863. // (these are defined in juce_win32_Threads.cpp)
  1864. long juce_InterlockedExchange (volatile long* a, long b) throw();
  1865. long juce_InterlockedIncrement (volatile long* a) throw();
  1866. long juce_InterlockedDecrement (volatile long* a) throw();
  1867. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  1868. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  1869. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  1870. inline void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  1871. #endif
  1872. #if JUCE_64BIT
  1873. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1874. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1875. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1876. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1877. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1878. #else
  1879. // None of these atomics are available in a 32-bit Windows build!!
  1880. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  1881. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  1882. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  1883. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  1884. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1885. #endif
  1886. #endif
  1887. #if JUCE_MSVC
  1888. #pragma warning (push)
  1889. #pragma warning (disable: 4311) // (truncation warning)
  1890. #endif
  1891. template <typename Type>
  1892. inline Type Atomic<Type>::get() const throw()
  1893. {
  1894. #if JUCE_ATOMICS_MAC
  1895. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1896. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1897. #elif JUCE_ATOMICS_WINDOWS
  1898. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1899. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1900. #elif JUCE_ATOMICS_ANDROID
  1901. return value;
  1902. #elif JUCE_ATOMICS_GCC
  1903. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1904. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1905. #endif
  1906. }
  1907. template <typename Type>
  1908. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  1909. {
  1910. #if JUCE_ATOMICS_ANDROID
  1911. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1912. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1913. Type currentVal = value;
  1914. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1915. return currentVal;
  1916. #elif JUCE_ATOMICS_WINDOWS
  1917. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1918. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1919. #endif
  1920. }
  1921. template <typename Type>
  1922. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  1923. {
  1924. #if JUCE_ATOMICS_MAC
  1925. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1926. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1927. #elif JUCE_ATOMICS_WINDOWS
  1928. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1929. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1930. #elif JUCE_ATOMICS_ANDROID
  1931. for (;;)
  1932. {
  1933. const Type oldValue (value);
  1934. const Type newValue (castFrom32Bit (castTo32Bit (oldValue) + castTo32Bit (amountToAdd)));
  1935. if (compareAndSetBool (newValue, oldValue))
  1936. return newValue;
  1937. }
  1938. #elif JUCE_ATOMICS_GCC
  1939. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1940. #endif
  1941. }
  1942. template <typename Type>
  1943. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  1944. {
  1945. return operator+= (juce_negate (amountToSubtract));
  1946. }
  1947. template <typename Type>
  1948. inline Type Atomic<Type>::operator++() throw()
  1949. {
  1950. #if JUCE_ATOMICS_MAC
  1951. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1952. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1953. #elif JUCE_ATOMICS_WINDOWS
  1954. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1955. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1956. #elif JUCE_ATOMICS_ANDROID
  1957. return (Type) (__atomic_inc ((volatile int*) &value) + 1);
  1958. #elif JUCE_ATOMICS_GCC
  1959. return (Type) __sync_add_and_fetch (&value, 1);
  1960. #endif
  1961. }
  1962. template <typename Type>
  1963. inline Type Atomic<Type>::operator--() throw()
  1964. {
  1965. #if JUCE_ATOMICS_MAC
  1966. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1967. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1968. #elif JUCE_ATOMICS_WINDOWS
  1969. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1970. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1971. #elif JUCE_ATOMICS_ANDROID
  1972. return (Type) (__atomic_dec ((volatile int*) &value) - 1);
  1973. #elif JUCE_ATOMICS_GCC
  1974. return (Type) __sync_add_and_fetch (&value, -1);
  1975. #endif
  1976. }
  1977. template <typename Type>
  1978. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  1979. {
  1980. #if JUCE_ATOMICS_MAC
  1981. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1982. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1983. #elif JUCE_ATOMICS_WINDOWS
  1984. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  1985. #elif JUCE_ATOMICS_ANDROID
  1986. return __atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value) == 0;
  1987. #elif JUCE_ATOMICS_GCC
  1988. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  1989. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  1990. #endif
  1991. }
  1992. template <typename Type>
  1993. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  1994. {
  1995. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_ANDROID
  1996. for (;;) // Annoying workaround for only having a bool CAS operation..
  1997. {
  1998. if (compareAndSetBool (newValue, valueToCompare))
  1999. return valueToCompare;
  2000. const Type result = value;
  2001. if (result != valueToCompare)
  2002. return result;
  2003. }
  2004. #elif JUCE_ATOMICS_WINDOWS
  2005. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  2006. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  2007. #elif JUCE_ATOMICS_GCC
  2008. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  2009. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  2010. #endif
  2011. }
  2012. template <typename Type>
  2013. inline void Atomic<Type>::memoryBarrier() throw()
  2014. {
  2015. #if JUCE_ATOMICS_MAC
  2016. OSMemoryBarrier();
  2017. #elif JUCE_ATOMICS_GCC
  2018. __sync_synchronize();
  2019. #elif JUCE_ATOMICS_WINDOWS
  2020. juce_MemoryBarrier();
  2021. #endif
  2022. }
  2023. #if JUCE_MSVC
  2024. #pragma warning (pop)
  2025. #endif
  2026. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2027. /*** End of inlined file: juce_Atomic.h ***/
  2028. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  2029. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2030. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2031. /**
  2032. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  2033. various methods to operate on the data.
  2034. @see CharPointer_UTF16, CharPointer_UTF32
  2035. */
  2036. class CharPointer_UTF8
  2037. {
  2038. public:
  2039. typedef char CharType;
  2040. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) throw()
  2041. : data (const_cast <CharType*> (rawPointer))
  2042. {
  2043. }
  2044. inline CharPointer_UTF8 (const CharPointer_UTF8& other) throw()
  2045. : data (other.data)
  2046. {
  2047. }
  2048. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) throw()
  2049. {
  2050. data = other.data;
  2051. return *this;
  2052. }
  2053. inline CharPointer_UTF8& operator= (const CharType* text) throw()
  2054. {
  2055. data = const_cast <CharType*> (text);
  2056. return *this;
  2057. }
  2058. /** This is a pointer comparison, it doesn't compare the actual text. */
  2059. inline bool operator== (const CharPointer_UTF8& other) const throw() { return data == other.data; }
  2060. inline bool operator!= (const CharPointer_UTF8& other) const throw() { return data != other.data; }
  2061. inline bool operator<= (const CharPointer_UTF8& other) const throw() { return data <= other.data; }
  2062. inline bool operator< (const CharPointer_UTF8& other) const throw() { return data < other.data; }
  2063. inline bool operator>= (const CharPointer_UTF8& other) const throw() { return data >= other.data; }
  2064. inline bool operator> (const CharPointer_UTF8& other) const throw() { return data > other.data; }
  2065. /** Returns the address that this pointer is pointing to. */
  2066. inline CharType* getAddress() const throw() { return data; }
  2067. /** Returns the address that this pointer is pointing to. */
  2068. inline operator const CharType*() const throw() { return data; }
  2069. /** Returns true if this pointer is pointing to a null character. */
  2070. inline bool isEmpty() const throw() { return *data == 0; }
  2071. /** Returns the unicode character that this pointer is pointing to. */
  2072. juce_wchar operator*() const throw()
  2073. {
  2074. const signed char byte = (signed char) *data;
  2075. if (byte >= 0)
  2076. return byte;
  2077. uint32 n = (uint32) (uint8) byte;
  2078. uint32 mask = 0x7f;
  2079. uint32 bit = 0x40;
  2080. size_t numExtraValues = 0;
  2081. while ((n & bit) != 0 && bit > 0x10)
  2082. {
  2083. mask >>= 1;
  2084. ++numExtraValues;
  2085. bit >>= 1;
  2086. }
  2087. n &= mask;
  2088. for (size_t i = 1; i <= numExtraValues; ++i)
  2089. {
  2090. const juce_wchar nextByte = data [i];
  2091. if ((nextByte & 0xc0) != 0x80)
  2092. break;
  2093. n <<= 6;
  2094. n |= (nextByte & 0x3f);
  2095. }
  2096. return (juce_wchar) n;
  2097. }
  2098. /** Moves this pointer along to the next character in the string. */
  2099. CharPointer_UTF8& operator++() throw()
  2100. {
  2101. const signed char n = (signed char) *data++;
  2102. if (n < 0)
  2103. {
  2104. juce_wchar bit = 0x40;
  2105. while ((n & bit) != 0 && bit > 0x8)
  2106. {
  2107. ++data;
  2108. bit >>= 1;
  2109. }
  2110. }
  2111. return *this;
  2112. }
  2113. /** Moves this pointer back to the previous character in the string. */
  2114. CharPointer_UTF8& operator--() throw()
  2115. {
  2116. const char n = *--data;
  2117. if ((n & 0xc0) == 0xc0)
  2118. {
  2119. int count = 3;
  2120. do
  2121. {
  2122. --data;
  2123. }
  2124. while ((*data & 0xc0) == 0xc0 && --count >= 0);
  2125. }
  2126. return *this;
  2127. }
  2128. /** Returns the character that this pointer is currently pointing to, and then
  2129. advances the pointer to point to the next character. */
  2130. juce_wchar getAndAdvance() throw()
  2131. {
  2132. const signed char byte = (signed char) *data++;
  2133. if (byte >= 0)
  2134. return byte;
  2135. uint32 n = (uint32) (uint8) byte;
  2136. uint32 mask = 0x7f;
  2137. uint32 bit = 0x40;
  2138. int numExtraValues = 0;
  2139. while ((n & bit) != 0 && bit > 0x8)
  2140. {
  2141. mask >>= 1;
  2142. ++numExtraValues;
  2143. bit >>= 1;
  2144. }
  2145. n &= mask;
  2146. while (--numExtraValues >= 0)
  2147. {
  2148. const uint32 nextByte = (uint32) (uint8) *data++;
  2149. if ((nextByte & 0xc0) != 0x80)
  2150. break;
  2151. n <<= 6;
  2152. n |= (nextByte & 0x3f);
  2153. }
  2154. return (juce_wchar) n;
  2155. }
  2156. /** Moves this pointer along to the next character in the string. */
  2157. CharPointer_UTF8 operator++ (int) throw()
  2158. {
  2159. CharPointer_UTF8 temp (*this);
  2160. ++*this;
  2161. return temp;
  2162. }
  2163. /** Moves this pointer forwards by the specified number of characters. */
  2164. void operator+= (int numToSkip) throw()
  2165. {
  2166. if (numToSkip < 0)
  2167. {
  2168. while (++numToSkip <= 0)
  2169. --*this;
  2170. }
  2171. else
  2172. {
  2173. while (--numToSkip >= 0)
  2174. ++*this;
  2175. }
  2176. }
  2177. /** Moves this pointer backwards by the specified number of characters. */
  2178. void operator-= (int numToSkip) throw()
  2179. {
  2180. operator+= (-numToSkip);
  2181. }
  2182. /** Returns the character at a given character index from the start of the string. */
  2183. juce_wchar operator[] (int characterIndex) const throw()
  2184. {
  2185. CharPointer_UTF8 p (*this);
  2186. p += characterIndex;
  2187. return *p;
  2188. }
  2189. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2190. CharPointer_UTF8 operator+ (int numToSkip) const throw()
  2191. {
  2192. CharPointer_UTF8 p (*this);
  2193. p += numToSkip;
  2194. return p;
  2195. }
  2196. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2197. CharPointer_UTF8 operator- (int numToSkip) const throw()
  2198. {
  2199. CharPointer_UTF8 p (*this);
  2200. p += -numToSkip;
  2201. return p;
  2202. }
  2203. /** Returns the number of characters in this string. */
  2204. size_t length() const throw()
  2205. {
  2206. const CharType* d = data;
  2207. size_t count = 0;
  2208. for (;;)
  2209. {
  2210. const uint32 n = (uint32) (uint8) *d++;
  2211. if ((n & 0x80) != 0)
  2212. {
  2213. uint32 bit = 0x40;
  2214. while ((n & bit) != 0)
  2215. {
  2216. ++d;
  2217. bit >>= 1;
  2218. if (bit == 0)
  2219. break; // illegal utf-8 sequence
  2220. }
  2221. }
  2222. else if (n == 0)
  2223. break;
  2224. ++count;
  2225. }
  2226. return count;
  2227. }
  2228. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2229. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2230. {
  2231. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2232. }
  2233. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2234. size_t lengthUpTo (const CharPointer_UTF8& end) const throw()
  2235. {
  2236. return CharacterFunctions::lengthUpTo (*this, end);
  2237. }
  2238. /** Returns the number of bytes that are used to represent this string.
  2239. This includes the terminating null character.
  2240. */
  2241. size_t sizeInBytes() const throw()
  2242. {
  2243. return strlen (data) + 1;
  2244. }
  2245. /** Returns the number of bytes that would be needed to represent the given
  2246. unicode character in this encoding format.
  2247. */
  2248. static size_t getBytesRequiredFor (const juce_wchar charToWrite) throw()
  2249. {
  2250. size_t num = 1;
  2251. const uint32 c = (uint32) charToWrite;
  2252. if (c >= 0x80)
  2253. {
  2254. ++num;
  2255. if (c >= 0x800)
  2256. {
  2257. ++num;
  2258. if (c >= 0x10000)
  2259. ++num;
  2260. }
  2261. }
  2262. return num;
  2263. }
  2264. /** Returns the number of bytes that would be needed to represent the given
  2265. string in this encoding format.
  2266. The value returned does NOT include the terminating null character.
  2267. */
  2268. template <class CharPointer>
  2269. static size_t getBytesRequiredFor (CharPointer text) throw()
  2270. {
  2271. size_t count = 0;
  2272. juce_wchar n;
  2273. while ((n = text.getAndAdvance()) != 0)
  2274. count += getBytesRequiredFor (n);
  2275. return count;
  2276. }
  2277. /** Returns a pointer to the null character that terminates this string. */
  2278. CharPointer_UTF8 findTerminatingNull() const throw()
  2279. {
  2280. return CharPointer_UTF8 (data + strlen (data));
  2281. }
  2282. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2283. void write (const juce_wchar charToWrite) throw()
  2284. {
  2285. const uint32 c = (uint32) charToWrite;
  2286. if (c >= 0x80)
  2287. {
  2288. int numExtraBytes = 1;
  2289. if (c >= 0x800)
  2290. {
  2291. ++numExtraBytes;
  2292. if (c >= 0x10000)
  2293. ++numExtraBytes;
  2294. }
  2295. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2296. while (--numExtraBytes >= 0)
  2297. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2298. }
  2299. else
  2300. {
  2301. *data++ = (CharType) c;
  2302. }
  2303. }
  2304. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2305. inline void writeNull() const throw()
  2306. {
  2307. *data = 0;
  2308. }
  2309. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2310. template <typename CharPointer>
  2311. void writeAll (const CharPointer& src) throw()
  2312. {
  2313. CharacterFunctions::copyAll (*this, src);
  2314. }
  2315. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2316. void writeAll (const CharPointer_UTF8& src) throw()
  2317. {
  2318. const CharType* s = src.data;
  2319. while ((*data = *s) != 0)
  2320. {
  2321. ++data;
  2322. ++s;
  2323. }
  2324. }
  2325. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2326. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2327. to the destination buffer before stopping.
  2328. */
  2329. template <typename CharPointer>
  2330. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2331. {
  2332. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2333. }
  2334. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2335. The maxChars parameter specifies the maximum number of characters that can be
  2336. written to the destination buffer before stopping (including the terminating null).
  2337. */
  2338. template <typename CharPointer>
  2339. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2340. {
  2341. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2342. }
  2343. /** Compares this string with another one. */
  2344. template <typename CharPointer>
  2345. int compare (const CharPointer& other) const throw()
  2346. {
  2347. return CharacterFunctions::compare (*this, other);
  2348. }
  2349. /** Compares this string with another one, up to a specified number of characters. */
  2350. template <typename CharPointer>
  2351. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2352. {
  2353. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2354. }
  2355. /** Compares this string with another one. */
  2356. template <typename CharPointer>
  2357. int compareIgnoreCase (const CharPointer& other) const throw()
  2358. {
  2359. return CharacterFunctions::compareIgnoreCase (*this, other);
  2360. }
  2361. /** Compares this string with another one. */
  2362. int compareIgnoreCase (const CharPointer_UTF8& other) const throw()
  2363. {
  2364. #if JUCE_WINDOWS
  2365. return stricmp (data, other.data);
  2366. #else
  2367. return strcasecmp (data, other.data);
  2368. #endif
  2369. }
  2370. /** Compares this string with another one, up to a specified number of characters. */
  2371. template <typename CharPointer>
  2372. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2373. {
  2374. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2375. }
  2376. /** Compares this string with another one, up to a specified number of characters. */
  2377. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const throw()
  2378. {
  2379. #if JUCE_WINDOWS
  2380. return strnicmp (data, other.data, maxChars);
  2381. #else
  2382. return strncasecmp (data, other.data, maxChars);
  2383. #endif
  2384. }
  2385. /** Returns the character index of a substring, or -1 if it isn't found. */
  2386. template <typename CharPointer>
  2387. int indexOf (const CharPointer& stringToFind) const throw()
  2388. {
  2389. return CharacterFunctions::indexOf (*this, stringToFind);
  2390. }
  2391. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2392. int indexOf (const juce_wchar charToFind) const throw()
  2393. {
  2394. return CharacterFunctions::indexOfChar (*this, charToFind);
  2395. }
  2396. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2397. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2398. {
  2399. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2400. : CharacterFunctions::indexOfChar (*this, charToFind);
  2401. }
  2402. /** Returns true if the first character of this string is whitespace. */
  2403. bool isWhitespace() const throw() { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2404. /** Returns true if the first character of this string is a digit. */
  2405. bool isDigit() const throw() { return *data >= '0' && *data <= '9'; }
  2406. /** Returns true if the first character of this string is a letter. */
  2407. bool isLetter() const throw() { return CharacterFunctions::isLetter (operator*()) != 0; }
  2408. /** Returns true if the first character of this string is a letter or digit. */
  2409. bool isLetterOrDigit() const throw() { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2410. /** Returns true if the first character of this string is upper-case. */
  2411. bool isUpperCase() const throw() { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2412. /** Returns true if the first character of this string is lower-case. */
  2413. bool isLowerCase() const throw() { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2414. /** Returns an upper-case version of the first character of this string. */
  2415. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (operator*()); }
  2416. /** Returns a lower-case version of the first character of this string. */
  2417. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (operator*()); }
  2418. /** Parses this string as a 32-bit integer. */
  2419. int getIntValue32() const throw() { return atoi (data); }
  2420. /** Parses this string as a 64-bit integer. */
  2421. int64 getIntValue64() const throw()
  2422. {
  2423. #if JUCE_LINUX || JUCE_ANDROID
  2424. return atoll (data);
  2425. #elif JUCE_WINDOWS
  2426. return _atoi64 (data);
  2427. #else
  2428. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2429. #endif
  2430. }
  2431. /** Parses this string as a floating point double. */
  2432. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  2433. /** Returns the first non-whitespace character in the string. */
  2434. CharPointer_UTF8 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  2435. /** Returns true if the given unicode character can be represented in this encoding. */
  2436. static bool canRepresent (juce_wchar character) throw()
  2437. {
  2438. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2439. }
  2440. /** Returns true if this data contains a valid string in this encoding. */
  2441. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2442. {
  2443. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2444. {
  2445. const signed char byte = (signed char) *dataToTest;
  2446. if (byte < 0)
  2447. {
  2448. uint32 n = (uint32) (uint8) byte;
  2449. uint32 mask = 0x7f;
  2450. uint32 bit = 0x40;
  2451. int numExtraValues = 0;
  2452. while ((n & bit) != 0)
  2453. {
  2454. if (bit <= 0x10)
  2455. return false;
  2456. mask >>= 1;
  2457. ++numExtraValues;
  2458. bit >>= 1;
  2459. }
  2460. n &= mask;
  2461. while (--numExtraValues >= 0)
  2462. {
  2463. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2464. if ((nextByte & 0xc0) != 0x80)
  2465. return false;
  2466. }
  2467. }
  2468. }
  2469. return true;
  2470. }
  2471. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2472. CharPointer_UTF8 atomicSwap (const CharPointer_UTF8& newValue)
  2473. {
  2474. return CharPointer_UTF8 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2475. }
  2476. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2477. enum
  2478. {
  2479. byteOrderMark1 = 0xef,
  2480. byteOrderMark2 = 0xbb,
  2481. byteOrderMark3 = 0xbf
  2482. };
  2483. private:
  2484. CharType* data;
  2485. };
  2486. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2487. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2488. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2489. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2490. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2491. /**
  2492. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2493. various methods to operate on the data.
  2494. @see CharPointer_UTF8, CharPointer_UTF32
  2495. */
  2496. class CharPointer_UTF16
  2497. {
  2498. public:
  2499. #if JUCE_NATIVE_WCHAR_IS_UTF16
  2500. typedef wchar_t CharType;
  2501. #else
  2502. typedef int16 CharType;
  2503. #endif
  2504. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) throw()
  2505. : data (const_cast <CharType*> (rawPointer))
  2506. {
  2507. }
  2508. inline CharPointer_UTF16 (const CharPointer_UTF16& other) throw()
  2509. : data (other.data)
  2510. {
  2511. }
  2512. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) throw()
  2513. {
  2514. data = other.data;
  2515. return *this;
  2516. }
  2517. inline CharPointer_UTF16& operator= (const CharType* text) throw()
  2518. {
  2519. data = const_cast <CharType*> (text);
  2520. return *this;
  2521. }
  2522. /** This is a pointer comparison, it doesn't compare the actual text. */
  2523. inline bool operator== (const CharPointer_UTF16& other) const throw() { return data == other.data; }
  2524. inline bool operator!= (const CharPointer_UTF16& other) const throw() { return data != other.data; }
  2525. inline bool operator<= (const CharPointer_UTF16& other) const throw() { return data <= other.data; }
  2526. inline bool operator< (const CharPointer_UTF16& other) const throw() { return data < other.data; }
  2527. inline bool operator>= (const CharPointer_UTF16& other) const throw() { return data >= other.data; }
  2528. inline bool operator> (const CharPointer_UTF16& other) const throw() { return data > other.data; }
  2529. /** Returns the address that this pointer is pointing to. */
  2530. inline CharType* getAddress() const throw() { return data; }
  2531. /** Returns the address that this pointer is pointing to. */
  2532. inline operator const CharType*() const throw() { return data; }
  2533. /** Returns true if this pointer is pointing to a null character. */
  2534. inline bool isEmpty() const throw() { return *data == 0; }
  2535. /** Returns the unicode character that this pointer is pointing to. */
  2536. juce_wchar operator*() const throw()
  2537. {
  2538. uint32 n = (uint32) (uint16) *data;
  2539. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2540. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2541. return (juce_wchar) n;
  2542. }
  2543. /** Moves this pointer along to the next character in the string. */
  2544. CharPointer_UTF16& operator++() throw()
  2545. {
  2546. const juce_wchar n = *data++;
  2547. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2548. ++data;
  2549. return *this;
  2550. }
  2551. /** Moves this pointer back to the previous character in the string. */
  2552. CharPointer_UTF16& operator--() throw()
  2553. {
  2554. const juce_wchar n = *--data;
  2555. if (n >= 0xdc00 && n <= 0xdfff)
  2556. --data;
  2557. return *this;
  2558. }
  2559. /** Returns the character that this pointer is currently pointing to, and then
  2560. advances the pointer to point to the next character. */
  2561. juce_wchar getAndAdvance() throw()
  2562. {
  2563. uint32 n = (uint32) (uint16) *data++;
  2564. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2565. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2566. return (juce_wchar) n;
  2567. }
  2568. /** Moves this pointer along to the next character in the string. */
  2569. CharPointer_UTF16 operator++ (int) throw()
  2570. {
  2571. CharPointer_UTF16 temp (*this);
  2572. ++*this;
  2573. return temp;
  2574. }
  2575. /** Moves this pointer forwards by the specified number of characters. */
  2576. void operator+= (int numToSkip) throw()
  2577. {
  2578. if (numToSkip < 0)
  2579. {
  2580. while (++numToSkip <= 0)
  2581. --*this;
  2582. }
  2583. else
  2584. {
  2585. while (--numToSkip >= 0)
  2586. ++*this;
  2587. }
  2588. }
  2589. /** Moves this pointer backwards by the specified number of characters. */
  2590. void operator-= (int numToSkip) throw()
  2591. {
  2592. operator+= (-numToSkip);
  2593. }
  2594. /** Returns the character at a given character index from the start of the string. */
  2595. juce_wchar operator[] (const int characterIndex) const throw()
  2596. {
  2597. CharPointer_UTF16 p (*this);
  2598. p += characterIndex;
  2599. return *p;
  2600. }
  2601. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2602. CharPointer_UTF16 operator+ (const int numToSkip) const throw()
  2603. {
  2604. CharPointer_UTF16 p (*this);
  2605. p += numToSkip;
  2606. return p;
  2607. }
  2608. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2609. CharPointer_UTF16 operator- (const int numToSkip) const throw()
  2610. {
  2611. CharPointer_UTF16 p (*this);
  2612. p += -numToSkip;
  2613. return p;
  2614. }
  2615. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2616. void write (juce_wchar charToWrite) throw()
  2617. {
  2618. if (charToWrite >= 0x10000)
  2619. {
  2620. charToWrite -= 0x10000;
  2621. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2622. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2623. }
  2624. else
  2625. {
  2626. *data++ = (CharType) charToWrite;
  2627. }
  2628. }
  2629. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2630. inline void writeNull() const throw()
  2631. {
  2632. *data = 0;
  2633. }
  2634. /** Returns the number of characters in this string. */
  2635. size_t length() const throw()
  2636. {
  2637. const CharType* d = data;
  2638. size_t count = 0;
  2639. for (;;)
  2640. {
  2641. const int n = *d++;
  2642. if (n >= 0xd800 && n <= 0xdfff)
  2643. {
  2644. if (*d++ == 0)
  2645. break;
  2646. }
  2647. else if (n == 0)
  2648. break;
  2649. ++count;
  2650. }
  2651. return count;
  2652. }
  2653. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2654. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2655. {
  2656. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2657. }
  2658. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2659. size_t lengthUpTo (const CharPointer_UTF16& end) const throw()
  2660. {
  2661. return CharacterFunctions::lengthUpTo (*this, end);
  2662. }
  2663. /** Returns the number of bytes that are used to represent this string.
  2664. This includes the terminating null character.
  2665. */
  2666. size_t sizeInBytes() const throw()
  2667. {
  2668. return sizeof (CharType) * (findNullIndex (data) + 1);
  2669. }
  2670. /** Returns the number of bytes that would be needed to represent the given
  2671. unicode character in this encoding format.
  2672. */
  2673. static size_t getBytesRequiredFor (const juce_wchar charToWrite) throw()
  2674. {
  2675. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2676. }
  2677. /** Returns the number of bytes that would be needed to represent the given
  2678. string in this encoding format.
  2679. The value returned does NOT include the terminating null character.
  2680. */
  2681. template <class CharPointer>
  2682. static size_t getBytesRequiredFor (CharPointer text) throw()
  2683. {
  2684. size_t count = 0;
  2685. juce_wchar n;
  2686. while ((n = text.getAndAdvance()) != 0)
  2687. count += getBytesRequiredFor (n);
  2688. return count;
  2689. }
  2690. /** Returns a pointer to the null character that terminates this string. */
  2691. CharPointer_UTF16 findTerminatingNull() const throw()
  2692. {
  2693. const CharType* t = data;
  2694. while (*t != 0)
  2695. ++t;
  2696. return CharPointer_UTF16 (t);
  2697. }
  2698. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2699. template <typename CharPointer>
  2700. void writeAll (const CharPointer& src) throw()
  2701. {
  2702. CharacterFunctions::copyAll (*this, src);
  2703. }
  2704. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2705. void writeAll (const CharPointer_UTF16& src) throw()
  2706. {
  2707. const CharType* s = src.data;
  2708. while ((*data = *s) != 0)
  2709. {
  2710. ++data;
  2711. ++s;
  2712. }
  2713. }
  2714. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2715. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2716. to the destination buffer before stopping.
  2717. */
  2718. template <typename CharPointer>
  2719. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2720. {
  2721. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2722. }
  2723. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2724. The maxChars parameter specifies the maximum number of characters that can be
  2725. written to the destination buffer before stopping (including the terminating null).
  2726. */
  2727. template <typename CharPointer>
  2728. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2729. {
  2730. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2731. }
  2732. /** Compares this string with another one. */
  2733. template <typename CharPointer>
  2734. int compare (const CharPointer& other) const throw()
  2735. {
  2736. return CharacterFunctions::compare (*this, other);
  2737. }
  2738. /** Compares this string with another one, up to a specified number of characters. */
  2739. template <typename CharPointer>
  2740. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2741. {
  2742. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2743. }
  2744. /** Compares this string with another one. */
  2745. template <typename CharPointer>
  2746. int compareIgnoreCase (const CharPointer& other) const throw()
  2747. {
  2748. return CharacterFunctions::compareIgnoreCase (*this, other);
  2749. }
  2750. /** Compares this string with another one, up to a specified number of characters. */
  2751. template <typename CharPointer>
  2752. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2753. {
  2754. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2755. }
  2756. #if JUCE_WINDOWS && ! DOXYGEN
  2757. int compareIgnoreCase (const CharPointer_UTF16& other) const throw()
  2758. {
  2759. return _wcsicmp (data, other.data);
  2760. }
  2761. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const throw()
  2762. {
  2763. return _wcsnicmp (data, other.data, maxChars);
  2764. }
  2765. int indexOf (const CharPointer_UTF16& stringToFind) const throw()
  2766. {
  2767. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2768. return t == 0 ? -1 : (int) (t - data);
  2769. }
  2770. #endif
  2771. /** Returns the character index of a substring, or -1 if it isn't found. */
  2772. template <typename CharPointer>
  2773. int indexOf (const CharPointer& stringToFind) const throw()
  2774. {
  2775. return CharacterFunctions::indexOf (*this, stringToFind);
  2776. }
  2777. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2778. int indexOf (const juce_wchar charToFind) const throw()
  2779. {
  2780. return CharacterFunctions::indexOfChar (*this, charToFind);
  2781. }
  2782. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2783. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2784. {
  2785. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2786. : CharacterFunctions::indexOfChar (*this, charToFind);
  2787. }
  2788. /** Returns true if the first character of this string is whitespace. */
  2789. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2790. /** Returns true if the first character of this string is a digit. */
  2791. bool isDigit() const throw() { return CharacterFunctions::isDigit (operator*()) != 0; }
  2792. /** Returns true if the first character of this string is a letter. */
  2793. bool isLetter() const throw() { return CharacterFunctions::isLetter (operator*()) != 0; }
  2794. /** Returns true if the first character of this string is a letter or digit. */
  2795. bool isLetterOrDigit() const throw() { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2796. /** Returns true if the first character of this string is upper-case. */
  2797. bool isUpperCase() const throw() { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2798. /** Returns true if the first character of this string is lower-case. */
  2799. bool isLowerCase() const throw() { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2800. /** Returns an upper-case version of the first character of this string. */
  2801. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (operator*()); }
  2802. /** Returns a lower-case version of the first character of this string. */
  2803. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (operator*()); }
  2804. /** Parses this string as a 32-bit integer. */
  2805. int getIntValue32() const throw()
  2806. {
  2807. #if JUCE_WINDOWS
  2808. return _wtoi (data);
  2809. #else
  2810. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2811. #endif
  2812. }
  2813. /** Parses this string as a 64-bit integer. */
  2814. int64 getIntValue64() const throw()
  2815. {
  2816. #if JUCE_WINDOWS
  2817. return _wtoi64 (data);
  2818. #else
  2819. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2820. #endif
  2821. }
  2822. /** Parses this string as a floating point double. */
  2823. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  2824. /** Returns the first non-whitespace character in the string. */
  2825. CharPointer_UTF16 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  2826. /** Returns true if the given unicode character can be represented in this encoding. */
  2827. static bool canRepresent (juce_wchar character) throw()
  2828. {
  2829. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2830. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2831. }
  2832. /** Returns true if this data contains a valid string in this encoding. */
  2833. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2834. {
  2835. maxBytesToRead /= sizeof (CharType);
  2836. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2837. {
  2838. const uint32 n = (uint32) (uint16) *dataToTest++;
  2839. if (n >= 0xd800)
  2840. {
  2841. if (n > 0x10ffff)
  2842. return false;
  2843. if (n <= 0xdfff)
  2844. {
  2845. if (n > 0xdc00)
  2846. return false;
  2847. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2848. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2849. return false;
  2850. }
  2851. }
  2852. }
  2853. return true;
  2854. }
  2855. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2856. CharPointer_UTF16 atomicSwap (const CharPointer_UTF16& newValue)
  2857. {
  2858. return CharPointer_UTF16 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2859. }
  2860. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2861. enum
  2862. {
  2863. byteOrderMarkBE1 = 0xfe,
  2864. byteOrderMarkBE2 = 0xff,
  2865. byteOrderMarkLE1 = 0xff,
  2866. byteOrderMarkLE2 = 0xfe
  2867. };
  2868. private:
  2869. CharType* data;
  2870. static int findNullIndex (const CharType* const t) throw()
  2871. {
  2872. int n = 0;
  2873. while (t[n] != 0)
  2874. ++n;
  2875. return n;
  2876. }
  2877. };
  2878. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2879. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2880. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2881. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2882. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2883. /**
  2884. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2885. various methods to operate on the data.
  2886. @see CharPointer_UTF8, CharPointer_UTF16
  2887. */
  2888. class CharPointer_UTF32
  2889. {
  2890. public:
  2891. typedef juce_wchar CharType;
  2892. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) throw()
  2893. : data (const_cast <CharType*> (rawPointer))
  2894. {
  2895. }
  2896. inline CharPointer_UTF32 (const CharPointer_UTF32& other) throw()
  2897. : data (other.data)
  2898. {
  2899. }
  2900. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) throw()
  2901. {
  2902. data = other.data;
  2903. return *this;
  2904. }
  2905. inline CharPointer_UTF32& operator= (const CharType* text) throw()
  2906. {
  2907. data = const_cast <CharType*> (text);
  2908. return *this;
  2909. }
  2910. /** This is a pointer comparison, it doesn't compare the actual text. */
  2911. inline bool operator== (const CharPointer_UTF32& other) const throw() { return data == other.data; }
  2912. inline bool operator!= (const CharPointer_UTF32& other) const throw() { return data != other.data; }
  2913. inline bool operator<= (const CharPointer_UTF32& other) const throw() { return data <= other.data; }
  2914. inline bool operator< (const CharPointer_UTF32& other) const throw() { return data < other.data; }
  2915. inline bool operator>= (const CharPointer_UTF32& other) const throw() { return data >= other.data; }
  2916. inline bool operator> (const CharPointer_UTF32& other) const throw() { return data > other.data; }
  2917. /** Returns the address that this pointer is pointing to. */
  2918. inline CharType* getAddress() const throw() { return data; }
  2919. /** Returns the address that this pointer is pointing to. */
  2920. inline operator const CharType*() const throw() { return data; }
  2921. /** Returns true if this pointer is pointing to a null character. */
  2922. inline bool isEmpty() const throw() { return *data == 0; }
  2923. /** Returns the unicode character that this pointer is pointing to. */
  2924. inline juce_wchar operator*() const throw() { return *data; }
  2925. /** Moves this pointer along to the next character in the string. */
  2926. inline CharPointer_UTF32& operator++() throw()
  2927. {
  2928. ++data;
  2929. return *this;
  2930. }
  2931. /** Moves this pointer to the previous character in the string. */
  2932. inline CharPointer_UTF32& operator--() throw()
  2933. {
  2934. --data;
  2935. return *this;
  2936. }
  2937. /** Returns the character that this pointer is currently pointing to, and then
  2938. advances the pointer to point to the next character. */
  2939. inline juce_wchar getAndAdvance() throw() { return *data++; }
  2940. /** Moves this pointer along to the next character in the string. */
  2941. CharPointer_UTF32 operator++ (int) throw()
  2942. {
  2943. CharPointer_UTF32 temp (*this);
  2944. ++data;
  2945. return temp;
  2946. }
  2947. /** Moves this pointer forwards by the specified number of characters. */
  2948. inline void operator+= (const int numToSkip) throw()
  2949. {
  2950. data += numToSkip;
  2951. }
  2952. inline void operator-= (const int numToSkip) throw()
  2953. {
  2954. data -= numToSkip;
  2955. }
  2956. /** Returns the character at a given character index from the start of the string. */
  2957. inline juce_wchar& operator[] (const int characterIndex) const throw()
  2958. {
  2959. return data [characterIndex];
  2960. }
  2961. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2962. CharPointer_UTF32 operator+ (const int numToSkip) const throw()
  2963. {
  2964. return CharPointer_UTF32 (data + numToSkip);
  2965. }
  2966. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2967. CharPointer_UTF32 operator- (const int numToSkip) const throw()
  2968. {
  2969. return CharPointer_UTF32 (data - numToSkip);
  2970. }
  2971. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2972. inline void write (const juce_wchar charToWrite) throw()
  2973. {
  2974. *data++ = charToWrite;
  2975. }
  2976. inline void replaceChar (const juce_wchar newChar) throw()
  2977. {
  2978. *data = newChar;
  2979. }
  2980. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2981. inline void writeNull() const throw()
  2982. {
  2983. *data = 0;
  2984. }
  2985. /** Returns the number of characters in this string. */
  2986. size_t length() const throw()
  2987. {
  2988. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  2989. return wcslen (data);
  2990. #else
  2991. size_t n = 0;
  2992. while (data[n] != 0)
  2993. ++n;
  2994. return n;
  2995. #endif
  2996. }
  2997. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2998. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2999. {
  3000. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3001. }
  3002. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3003. size_t lengthUpTo (const CharPointer_UTF32& end) const throw()
  3004. {
  3005. return CharacterFunctions::lengthUpTo (*this, end);
  3006. }
  3007. /** Returns the number of bytes that are used to represent this string.
  3008. This includes the terminating null character.
  3009. */
  3010. size_t sizeInBytes() const throw()
  3011. {
  3012. return sizeof (CharType) * (length() + 1);
  3013. }
  3014. /** Returns the number of bytes that would be needed to represent the given
  3015. unicode character in this encoding format.
  3016. */
  3017. static inline size_t getBytesRequiredFor (const juce_wchar) throw()
  3018. {
  3019. return sizeof (CharType);
  3020. }
  3021. /** Returns the number of bytes that would be needed to represent the given
  3022. string in this encoding format.
  3023. The value returned does NOT include the terminating null character.
  3024. */
  3025. template <class CharPointer>
  3026. static size_t getBytesRequiredFor (const CharPointer& text) throw()
  3027. {
  3028. return sizeof (CharType) * text.length();
  3029. }
  3030. /** Returns a pointer to the null character that terminates this string. */
  3031. CharPointer_UTF32 findTerminatingNull() const throw()
  3032. {
  3033. return CharPointer_UTF32 (data + length());
  3034. }
  3035. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3036. template <typename CharPointer>
  3037. void writeAll (const CharPointer& src) throw()
  3038. {
  3039. CharacterFunctions::copyAll (*this, src);
  3040. }
  3041. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3042. void writeAll (const CharPointer_UTF32& src) throw()
  3043. {
  3044. const CharType* s = src.data;
  3045. while ((*data = *s) != 0)
  3046. {
  3047. ++data;
  3048. ++s;
  3049. }
  3050. }
  3051. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3052. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3053. to the destination buffer before stopping.
  3054. */
  3055. template <typename CharPointer>
  3056. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  3057. {
  3058. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3059. }
  3060. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3061. The maxChars parameter specifies the maximum number of characters that can be
  3062. written to the destination buffer before stopping (including the terminating null).
  3063. */
  3064. template <typename CharPointer>
  3065. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  3066. {
  3067. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3068. }
  3069. /** Compares this string with another one. */
  3070. template <typename CharPointer>
  3071. int compare (const CharPointer& other) const throw()
  3072. {
  3073. return CharacterFunctions::compare (*this, other);
  3074. }
  3075. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3076. /** Compares this string with another one. */
  3077. int compare (const CharPointer_UTF32& other) const throw()
  3078. {
  3079. return wcscmp (data, other.data);
  3080. }
  3081. #endif
  3082. /** Compares this string with another one, up to a specified number of characters. */
  3083. template <typename CharPointer>
  3084. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  3085. {
  3086. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3087. }
  3088. /** Compares this string with another one. */
  3089. template <typename CharPointer>
  3090. int compareIgnoreCase (const CharPointer& other) const
  3091. {
  3092. return CharacterFunctions::compareIgnoreCase (*this, other);
  3093. }
  3094. /** Compares this string with another one, up to a specified number of characters. */
  3095. template <typename CharPointer>
  3096. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  3097. {
  3098. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3099. }
  3100. /** Returns the character index of a substring, or -1 if it isn't found. */
  3101. template <typename CharPointer>
  3102. int indexOf (const CharPointer& stringToFind) const throw()
  3103. {
  3104. return CharacterFunctions::indexOf (*this, stringToFind);
  3105. }
  3106. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3107. int indexOf (const juce_wchar charToFind) const throw()
  3108. {
  3109. int i = 0;
  3110. while (data[i] != 0)
  3111. {
  3112. if (data[i] == charToFind)
  3113. return i;
  3114. ++i;
  3115. }
  3116. return -1;
  3117. }
  3118. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3119. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  3120. {
  3121. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3122. : CharacterFunctions::indexOfChar (*this, charToFind);
  3123. }
  3124. /** Returns true if the first character of this string is whitespace. */
  3125. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3126. /** Returns true if the first character of this string is a digit. */
  3127. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3128. /** Returns true if the first character of this string is a letter. */
  3129. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3130. /** Returns true if the first character of this string is a letter or digit. */
  3131. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3132. /** Returns true if the first character of this string is upper-case. */
  3133. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3134. /** Returns true if the first character of this string is lower-case. */
  3135. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3136. /** Returns an upper-case version of the first character of this string. */
  3137. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (*data); }
  3138. /** Returns a lower-case version of the first character of this string. */
  3139. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (*data); }
  3140. /** Parses this string as a 32-bit integer. */
  3141. int getIntValue32() const throw() { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3142. /** Parses this string as a 64-bit integer. */
  3143. int64 getIntValue64() const throw() { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3144. /** Parses this string as a floating point double. */
  3145. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  3146. /** Returns the first non-whitespace character in the string. */
  3147. CharPointer_UTF32 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  3148. /** Returns true if the given unicode character can be represented in this encoding. */
  3149. static bool canRepresent (juce_wchar character) throw()
  3150. {
  3151. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3152. }
  3153. /** Returns true if this data contains a valid string in this encoding. */
  3154. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3155. {
  3156. maxBytesToRead /= sizeof (CharType);
  3157. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3158. if (! canRepresent (*dataToTest++))
  3159. return false;
  3160. return true;
  3161. }
  3162. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3163. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3164. {
  3165. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3166. }
  3167. private:
  3168. CharType* data;
  3169. };
  3170. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3171. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3172. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3173. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3174. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3175. /**
  3176. Wraps a pointer to a null-terminated ASCII character string, and provides
  3177. various methods to operate on the data.
  3178. A valid ASCII string is assumed to not contain any characters above 127.
  3179. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3180. */
  3181. class CharPointer_ASCII
  3182. {
  3183. public:
  3184. typedef char CharType;
  3185. inline explicit CharPointer_ASCII (const CharType* const rawPointer) throw()
  3186. : data (const_cast <CharType*> (rawPointer))
  3187. {
  3188. }
  3189. inline CharPointer_ASCII (const CharPointer_ASCII& other) throw()
  3190. : data (other.data)
  3191. {
  3192. }
  3193. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) throw()
  3194. {
  3195. data = other.data;
  3196. return *this;
  3197. }
  3198. inline CharPointer_ASCII& operator= (const CharType* text) throw()
  3199. {
  3200. data = const_cast <CharType*> (text);
  3201. return *this;
  3202. }
  3203. /** This is a pointer comparison, it doesn't compare the actual text. */
  3204. inline bool operator== (const CharPointer_ASCII& other) const throw() { return data == other.data; }
  3205. inline bool operator!= (const CharPointer_ASCII& other) const throw() { return data != other.data; }
  3206. inline bool operator<= (const CharPointer_ASCII& other) const throw() { return data <= other.data; }
  3207. inline bool operator< (const CharPointer_ASCII& other) const throw() { return data < other.data; }
  3208. inline bool operator>= (const CharPointer_ASCII& other) const throw() { return data >= other.data; }
  3209. inline bool operator> (const CharPointer_ASCII& other) const throw() { return data > other.data; }
  3210. /** Returns the address that this pointer is pointing to. */
  3211. inline CharType* getAddress() const throw() { return data; }
  3212. /** Returns the address that this pointer is pointing to. */
  3213. inline operator const CharType*() const throw() { return data; }
  3214. /** Returns true if this pointer is pointing to a null character. */
  3215. inline bool isEmpty() const throw() { return *data == 0; }
  3216. /** Returns the unicode character that this pointer is pointing to. */
  3217. inline juce_wchar operator*() const throw() { return *data; }
  3218. /** Moves this pointer along to the next character in the string. */
  3219. inline CharPointer_ASCII& operator++() throw()
  3220. {
  3221. ++data;
  3222. return *this;
  3223. }
  3224. /** Moves this pointer to the previous character in the string. */
  3225. inline CharPointer_ASCII& operator--() throw()
  3226. {
  3227. --data;
  3228. return *this;
  3229. }
  3230. /** Returns the character that this pointer is currently pointing to, and then
  3231. advances the pointer to point to the next character. */
  3232. inline juce_wchar getAndAdvance() throw() { return *data++; }
  3233. /** Moves this pointer along to the next character in the string. */
  3234. CharPointer_ASCII operator++ (int) throw()
  3235. {
  3236. CharPointer_ASCII temp (*this);
  3237. ++data;
  3238. return temp;
  3239. }
  3240. /** Moves this pointer forwards by the specified number of characters. */
  3241. inline void operator+= (const int numToSkip) throw()
  3242. {
  3243. data += numToSkip;
  3244. }
  3245. inline void operator-= (const int numToSkip) throw()
  3246. {
  3247. data -= numToSkip;
  3248. }
  3249. /** Returns the character at a given character index from the start of the string. */
  3250. inline juce_wchar operator[] (const int characterIndex) const throw()
  3251. {
  3252. return (juce_wchar) (unsigned char) data [characterIndex];
  3253. }
  3254. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3255. CharPointer_ASCII operator+ (const int numToSkip) const throw()
  3256. {
  3257. return CharPointer_ASCII (data + numToSkip);
  3258. }
  3259. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3260. CharPointer_ASCII operator- (const int numToSkip) const throw()
  3261. {
  3262. return CharPointer_ASCII (data - numToSkip);
  3263. }
  3264. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3265. inline void write (const juce_wchar charToWrite) throw()
  3266. {
  3267. *data++ = (char) charToWrite;
  3268. }
  3269. inline void replaceChar (const juce_wchar newChar) throw()
  3270. {
  3271. *data = (char) newChar;
  3272. }
  3273. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3274. inline void writeNull() const throw()
  3275. {
  3276. *data = 0;
  3277. }
  3278. /** Returns the number of characters in this string. */
  3279. size_t length() const throw()
  3280. {
  3281. return (size_t) strlen (data);
  3282. }
  3283. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3284. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  3285. {
  3286. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3287. }
  3288. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3289. size_t lengthUpTo (const CharPointer_ASCII& end) const throw()
  3290. {
  3291. return CharacterFunctions::lengthUpTo (*this, end);
  3292. }
  3293. /** Returns the number of bytes that are used to represent this string.
  3294. This includes the terminating null character.
  3295. */
  3296. size_t sizeInBytes() const throw()
  3297. {
  3298. return length() + 1;
  3299. }
  3300. /** Returns the number of bytes that would be needed to represent the given
  3301. unicode character in this encoding format.
  3302. */
  3303. static inline size_t getBytesRequiredFor (const juce_wchar) throw()
  3304. {
  3305. return 1;
  3306. }
  3307. /** Returns the number of bytes that would be needed to represent the given
  3308. string in this encoding format.
  3309. The value returned does NOT include the terminating null character.
  3310. */
  3311. template <class CharPointer>
  3312. static size_t getBytesRequiredFor (const CharPointer& text) throw()
  3313. {
  3314. return text.length();
  3315. }
  3316. /** Returns a pointer to the null character that terminates this string. */
  3317. CharPointer_ASCII findTerminatingNull() const throw()
  3318. {
  3319. return CharPointer_ASCII (data + length());
  3320. }
  3321. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3322. template <typename CharPointer>
  3323. void writeAll (const CharPointer& src) throw()
  3324. {
  3325. CharacterFunctions::copyAll (*this, src);
  3326. }
  3327. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3328. void writeAll (const CharPointer_ASCII& src) throw()
  3329. {
  3330. strcpy (data, src.data);
  3331. }
  3332. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3333. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3334. to the destination buffer before stopping.
  3335. */
  3336. template <typename CharPointer>
  3337. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  3338. {
  3339. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3340. }
  3341. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3342. The maxChars parameter specifies the maximum number of characters that can be
  3343. written to the destination buffer before stopping (including the terminating null).
  3344. */
  3345. template <typename CharPointer>
  3346. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  3347. {
  3348. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3349. }
  3350. /** Compares this string with another one. */
  3351. template <typename CharPointer>
  3352. int compare (const CharPointer& other) const throw()
  3353. {
  3354. return CharacterFunctions::compare (*this, other);
  3355. }
  3356. /** Compares this string with another one. */
  3357. int compare (const CharPointer_ASCII& other) const throw()
  3358. {
  3359. return strcmp (data, other.data);
  3360. }
  3361. /** Compares this string with another one, up to a specified number of characters. */
  3362. template <typename CharPointer>
  3363. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  3364. {
  3365. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3366. }
  3367. /** Compares this string with another one, up to a specified number of characters. */
  3368. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const throw()
  3369. {
  3370. return strncmp (data, other.data, (size_t) maxChars);
  3371. }
  3372. /** Compares this string with another one. */
  3373. template <typename CharPointer>
  3374. int compareIgnoreCase (const CharPointer& other) const
  3375. {
  3376. return CharacterFunctions::compareIgnoreCase (*this, other);
  3377. }
  3378. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3379. {
  3380. #if JUCE_WINDOWS
  3381. return stricmp (data, other.data);
  3382. #else
  3383. return strcasecmp (data, other.data);
  3384. #endif
  3385. }
  3386. /** Compares this string with another one, up to a specified number of characters. */
  3387. template <typename CharPointer>
  3388. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  3389. {
  3390. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3391. }
  3392. /** Returns the character index of a substring, or -1 if it isn't found. */
  3393. template <typename CharPointer>
  3394. int indexOf (const CharPointer& stringToFind) const throw()
  3395. {
  3396. return CharacterFunctions::indexOf (*this, stringToFind);
  3397. }
  3398. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3399. int indexOf (const juce_wchar charToFind) const throw()
  3400. {
  3401. int i = 0;
  3402. while (data[i] != 0)
  3403. {
  3404. if (data[i] == (char) charToFind)
  3405. return i;
  3406. ++i;
  3407. }
  3408. return -1;
  3409. }
  3410. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3411. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  3412. {
  3413. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3414. : CharacterFunctions::indexOfChar (*this, charToFind);
  3415. }
  3416. /** Returns true if the first character of this string is whitespace. */
  3417. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3418. /** Returns true if the first character of this string is a digit. */
  3419. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3420. /** Returns true if the first character of this string is a letter. */
  3421. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3422. /** Returns true if the first character of this string is a letter or digit. */
  3423. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3424. /** Returns true if the first character of this string is upper-case. */
  3425. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3426. /** Returns true if the first character of this string is lower-case. */
  3427. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3428. /** Returns an upper-case version of the first character of this string. */
  3429. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (*data); }
  3430. /** Returns a lower-case version of the first character of this string. */
  3431. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (*data); }
  3432. /** Parses this string as a 32-bit integer. */
  3433. int getIntValue32() const throw() { return atoi (data); }
  3434. /** Parses this string as a 64-bit integer. */
  3435. int64 getIntValue64() const throw()
  3436. {
  3437. #if JUCE_LINUX || JUCE_ANDROID
  3438. return atoll (data);
  3439. #elif JUCE_WINDOWS
  3440. return _atoi64 (data);
  3441. #else
  3442. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3443. #endif
  3444. }
  3445. /** Parses this string as a floating point double. */
  3446. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  3447. /** Returns the first non-whitespace character in the string. */
  3448. CharPointer_ASCII findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  3449. /** Returns true if the given unicode character can be represented in this encoding. */
  3450. static bool canRepresent (juce_wchar character) throw()
  3451. {
  3452. return ((unsigned int) character) < (unsigned int) 128;
  3453. }
  3454. /** Returns true if this data contains a valid string in this encoding. */
  3455. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3456. {
  3457. while (--maxBytesToRead >= 0)
  3458. {
  3459. if (((signed char) *dataToTest) <= 0)
  3460. return *dataToTest == 0;
  3461. ++dataToTest;
  3462. }
  3463. return true;
  3464. }
  3465. private:
  3466. CharType* data;
  3467. };
  3468. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3469. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3470. #if JUCE_MSVC
  3471. #pragma warning (pop)
  3472. #endif
  3473. class OutputStream;
  3474. /**
  3475. The JUCE String class!
  3476. Using a reference-counted internal representation, these strings are fast
  3477. and efficient, and there are methods to do just about any operation you'll ever
  3478. dream of.
  3479. @see StringArray, StringPairArray
  3480. */
  3481. class JUCE_API String
  3482. {
  3483. public:
  3484. /** Creates an empty string.
  3485. @see empty
  3486. */
  3487. String() throw();
  3488. /** Creates a copy of another string. */
  3489. String (const String& other) throw();
  3490. /** Creates a string from a zero-terminated ascii text string.
  3491. The string passed-in must not contain any characters with a value above 127, because
  3492. these can't be converted to unicode without knowing the original encoding that was
  3493. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3494. assertion.
  3495. To create strings with extended characters from UTF-8, you should explicitly call
  3496. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3497. use UTF-8 with escape characters in your source code to represent extended characters,
  3498. because there's no other way to represent unicode strings in a way that isn't dependent
  3499. on the compiler, source code editor and platform.
  3500. */
  3501. String (const char* text);
  3502. /** Creates a string from a string of 8-bit ascii characters.
  3503. The string passed-in must not contain any characters with a value above 127, because
  3504. these can't be converted to unicode without knowing the original encoding that was
  3505. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3506. assertion.
  3507. To create strings with extended characters from UTF-8, you should explicitly call
  3508. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3509. use UTF-8 with escape characters in your source code to represent extended characters,
  3510. because there's no other way to represent unicode strings in a way that isn't dependent
  3511. on the compiler, source code editor and platform.
  3512. This will use up the the first maxChars characters of the string (or less if the string
  3513. is actually shorter).
  3514. */
  3515. String (const char* text, size_t maxChars);
  3516. /** Creates a string from a whcar_t character string.
  3517. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3518. */
  3519. String (const wchar_t* text);
  3520. /** Creates a string from a whcar_t character string.
  3521. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3522. */
  3523. String (const wchar_t* text, size_t maxChars);
  3524. /** Creates a string from a UTF-8 character string */
  3525. String (const CharPointer_UTF8& text);
  3526. /** Creates a string from a UTF-8 character string */
  3527. String (const CharPointer_UTF8& text, size_t maxChars);
  3528. /** Creates a string from a UTF-8 character string */
  3529. String (const CharPointer_UTF8& start, const CharPointer_UTF8& end);
  3530. /** Creates a string from a UTF-16 character string */
  3531. String (const CharPointer_UTF16& text);
  3532. /** Creates a string from a UTF-16 character string */
  3533. String (const CharPointer_UTF16& text, size_t maxChars);
  3534. /** Creates a string from a UTF-16 character string */
  3535. String (const CharPointer_UTF16& start, const CharPointer_UTF16& end);
  3536. /** Creates a string from a UTF-32 character string */
  3537. String (const CharPointer_UTF32& text);
  3538. /** Creates a string from a UTF-32 character string */
  3539. String (const CharPointer_UTF32& text, size_t maxChars);
  3540. /** Creates a string from a UTF-32 character string */
  3541. String (const CharPointer_UTF32& start, const CharPointer_UTF32& end);
  3542. /** Creates a string from an ASCII character string */
  3543. String (const CharPointer_ASCII& text);
  3544. /** Creates a string from a single character. */
  3545. static const String charToString (juce_wchar character);
  3546. /** Destructor. */
  3547. ~String() throw();
  3548. /** This is an empty string that can be used whenever one is needed.
  3549. It's better to use this than String() because it explains what's going on
  3550. and is more efficient.
  3551. */
  3552. static const String empty;
  3553. /** This is the character encoding type used internally to store the string.
  3554. By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
  3555. internal storage format of the String class. UTF-8 uses the least space (if your strings
  3556. contain few extended characters), but call operator[] involves iterating the string to find
  3557. the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
  3558. per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
  3559. but is the native wchar_t format used in Windows.
  3560. It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
  3561. toUTF32() methods let you access the string's content in any of the other formats.
  3562. */
  3563. #if (JUCE_STRING_UTF_TYPE == 32)
  3564. typedef CharPointer_UTF32 CharPointerType;
  3565. #elif (JUCE_STRING_UTF_TYPE == 16)
  3566. typedef CharPointer_UTF16 CharPointerType;
  3567. #elif (JUCE_STRING_UTF_TYPE == 8)
  3568. typedef CharPointer_UTF8 CharPointerType;
  3569. #else
  3570. #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
  3571. #endif
  3572. /** Generates a probably-unique 32-bit hashcode from this string. */
  3573. int hashCode() const throw();
  3574. /** Generates a probably-unique 64-bit hashcode from this string. */
  3575. int64 hashCode64() const throw();
  3576. /** Returns the number of characters in the string. */
  3577. int length() const throw();
  3578. // Assignment and concatenation operators..
  3579. /** Replaces this string's contents with another string. */
  3580. String& operator= (const String& other) throw();
  3581. /** Appends another string at the end of this one. */
  3582. String& operator+= (const String& stringToAppend);
  3583. /** Appends another string at the end of this one. */
  3584. String& operator+= (const char* textToAppend);
  3585. /** Appends another string at the end of this one. */
  3586. String& operator+= (const wchar_t* textToAppend);
  3587. /** Appends a decimal number at the end of this string. */
  3588. String& operator+= (int numberToAppend);
  3589. /** Appends a character at the end of this string. */
  3590. String& operator+= (char characterToAppend);
  3591. /** Appends a character at the end of this string. */
  3592. String& operator+= (wchar_t characterToAppend);
  3593. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  3594. /** Appends a character at the end of this string. */
  3595. String& operator+= (juce_wchar characterToAppend);
  3596. #endif
  3597. /** Appends a string to the end of this one.
  3598. @param textToAppend the string to add
  3599. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3600. */
  3601. void append (const String& textToAppend, size_t maxCharsToTake);
  3602. /** Appends a string to the end of this one.
  3603. @param textToAppend the string to add
  3604. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3605. */
  3606. template <class CharPointer>
  3607. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3608. {
  3609. if (textToAppend.getAddress() != 0)
  3610. {
  3611. size_t extraBytesNeeded = 0;
  3612. size_t numChars = 0;
  3613. for (CharPointer t (textToAppend); numChars < maxCharsToTake && ! t.isEmpty();)
  3614. {
  3615. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3616. ++numChars;
  3617. }
  3618. if (numChars > 0)
  3619. {
  3620. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3621. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3622. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeWithCharLimit (textToAppend, (int) (numChars + 1));
  3623. }
  3624. }
  3625. }
  3626. /** Appends a string to the end of this one. */
  3627. template <class CharPointer>
  3628. void appendCharPointer (const CharPointer& textToAppend)
  3629. {
  3630. if (textToAppend.getAddress() != 0)
  3631. {
  3632. size_t extraBytesNeeded = 0;
  3633. for (CharPointer t (textToAppend); ! t.isEmpty();)
  3634. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3635. if (extraBytesNeeded > 0)
  3636. {
  3637. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3638. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3639. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeAll (textToAppend);
  3640. }
  3641. }
  3642. }
  3643. // Comparison methods..
  3644. /** Returns true if the string contains no characters.
  3645. Note that there's also an isNotEmpty() method to help write readable code.
  3646. @see containsNonWhitespaceChars()
  3647. */
  3648. inline bool isEmpty() const throw() { return text[0] == 0; }
  3649. /** Returns true if the string contains at least one character.
  3650. Note that there's also an isEmpty() method to help write readable code.
  3651. @see containsNonWhitespaceChars()
  3652. */
  3653. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  3654. /** Case-insensitive comparison with another string. */
  3655. bool equalsIgnoreCase (const String& other) const throw();
  3656. /** Case-insensitive comparison with another string. */
  3657. bool equalsIgnoreCase (const wchar_t* other) const throw();
  3658. /** Case-insensitive comparison with another string. */
  3659. bool equalsIgnoreCase (const char* other) const throw();
  3660. /** Case-sensitive comparison with another string.
  3661. @returns 0 if the two strings are identical; negative if this string comes before
  3662. the other one alphabetically, or positive if it comes after it.
  3663. */
  3664. int compare (const String& other) const throw();
  3665. /** Case-sensitive comparison with another string.
  3666. @returns 0 if the two strings are identical; negative if this string comes before
  3667. the other one alphabetically, or positive if it comes after it.
  3668. */
  3669. int compare (const char* other) const throw();
  3670. /** Case-sensitive comparison with another string.
  3671. @returns 0 if the two strings are identical; negative if this string comes before
  3672. the other one alphabetically, or positive if it comes after it.
  3673. */
  3674. int compare (const wchar_t* other) const throw();
  3675. /** Case-insensitive comparison with another string.
  3676. @returns 0 if the two strings are identical; negative if this string comes before
  3677. the other one alphabetically, or positive if it comes after it.
  3678. */
  3679. int compareIgnoreCase (const String& other) const throw();
  3680. /** Lexicographic comparison with another string.
  3681. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3682. characters, making it good for sorting human-readable strings.
  3683. @returns 0 if the two strings are identical; negative if this string comes before
  3684. the other one alphabetically, or positive if it comes after it.
  3685. */
  3686. int compareLexicographically (const String& other) const throw();
  3687. /** Tests whether the string begins with another string.
  3688. If the parameter is an empty string, this will always return true.
  3689. Uses a case-sensitive comparison.
  3690. */
  3691. bool startsWith (const String& text) const throw();
  3692. /** Tests whether the string begins with a particular character.
  3693. If the character is 0, this will always return false.
  3694. Uses a case-sensitive comparison.
  3695. */
  3696. bool startsWithChar (juce_wchar character) const throw();
  3697. /** Tests whether the string begins with another string.
  3698. If the parameter is an empty string, this will always return true.
  3699. Uses a case-insensitive comparison.
  3700. */
  3701. bool startsWithIgnoreCase (const String& text) const throw();
  3702. /** Tests whether the string ends with another string.
  3703. If the parameter is an empty string, this will always return true.
  3704. Uses a case-sensitive comparison.
  3705. */
  3706. bool endsWith (const String& text) const throw();
  3707. /** Tests whether the string ends with a particular character.
  3708. If the character is 0, this will always return false.
  3709. Uses a case-sensitive comparison.
  3710. */
  3711. bool endsWithChar (juce_wchar character) const throw();
  3712. /** Tests whether the string ends with another string.
  3713. If the parameter is an empty string, this will always return true.
  3714. Uses a case-insensitive comparison.
  3715. */
  3716. bool endsWithIgnoreCase (const String& text) const throw();
  3717. /** Tests whether the string contains another substring.
  3718. If the parameter is an empty string, this will always return true.
  3719. Uses a case-sensitive comparison.
  3720. */
  3721. bool contains (const String& text) const throw();
  3722. /** Tests whether the string contains a particular character.
  3723. Uses a case-sensitive comparison.
  3724. */
  3725. bool containsChar (juce_wchar character) const throw();
  3726. /** Tests whether the string contains another substring.
  3727. Uses a case-insensitive comparison.
  3728. */
  3729. bool containsIgnoreCase (const String& text) const throw();
  3730. /** Tests whether the string contains another substring as a distict word.
  3731. @returns true if the string contains this word, surrounded by
  3732. non-alphanumeric characters
  3733. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3734. */
  3735. bool containsWholeWord (const String& wordToLookFor) const throw();
  3736. /** Tests whether the string contains another substring as a distict word.
  3737. @returns true if the string contains this word, surrounded by
  3738. non-alphanumeric characters
  3739. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3740. */
  3741. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  3742. /** Finds an instance of another substring if it exists as a distict word.
  3743. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3744. then this will return the index of the start of the substring. If it isn't
  3745. found, then it will return -1
  3746. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3747. */
  3748. int indexOfWholeWord (const String& wordToLookFor) const throw();
  3749. /** Finds an instance of another substring if it exists as a distict word.
  3750. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3751. then this will return the index of the start of the substring. If it isn't
  3752. found, then it will return -1
  3753. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3754. */
  3755. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  3756. /** Looks for any of a set of characters in the string.
  3757. Uses a case-sensitive comparison.
  3758. @returns true if the string contains any of the characters from
  3759. the string that is passed in.
  3760. */
  3761. bool containsAnyOf (const String& charactersItMightContain) const throw();
  3762. /** Looks for a set of characters in the string.
  3763. Uses a case-sensitive comparison.
  3764. @returns Returns false if any of the characters in this string do not occur in
  3765. the parameter string. If this string is empty, the return value will
  3766. always be true.
  3767. */
  3768. bool containsOnly (const String& charactersItMightContain) const throw();
  3769. /** Returns true if this string contains any non-whitespace characters.
  3770. This will return false if the string contains only whitespace characters, or
  3771. if it's empty.
  3772. It is equivalent to calling "myString.trim().isNotEmpty()".
  3773. */
  3774. bool containsNonWhitespaceChars() const throw();
  3775. /** Returns true if the string matches this simple wildcard expression.
  3776. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3777. This isn't a full-blown regex though! The only wildcard characters supported
  3778. are "*" and "?". It's mainly intended for filename pattern matching.
  3779. */
  3780. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  3781. // Substring location methods..
  3782. /** Searches for a character inside this string.
  3783. Uses a case-sensitive comparison.
  3784. @returns the index of the first occurrence of the character in this
  3785. string, or -1 if it's not found.
  3786. */
  3787. int indexOfChar (juce_wchar characterToLookFor) const throw();
  3788. /** Searches for a character inside this string.
  3789. Uses a case-sensitive comparison.
  3790. @param startIndex the index from which the search should proceed
  3791. @param characterToLookFor the character to look for
  3792. @returns the index of the first occurrence of the character in this
  3793. string, or -1 if it's not found.
  3794. */
  3795. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  3796. /** Returns the index of the first character that matches one of the characters
  3797. passed-in to this method.
  3798. This scans the string, beginning from the startIndex supplied, and if it finds
  3799. a character that appears in the string charactersToLookFor, it returns its index.
  3800. If none of these characters are found, it returns -1.
  3801. If ignoreCase is true, the comparison will be case-insensitive.
  3802. @see indexOfChar, lastIndexOfAnyOf
  3803. */
  3804. int indexOfAnyOf (const String& charactersToLookFor,
  3805. int startIndex = 0,
  3806. bool ignoreCase = false) const throw();
  3807. /** Searches for a substring within this string.
  3808. Uses a case-sensitive comparison.
  3809. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3810. If textToLookFor is an empty string, this will always return 0.
  3811. */
  3812. int indexOf (const String& textToLookFor) const throw();
  3813. /** Searches for a substring within this string.
  3814. Uses a case-sensitive comparison.
  3815. @param startIndex the index from which the search should proceed
  3816. @param textToLookFor the string to search for
  3817. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3818. If textToLookFor is an empty string, this will always return -1.
  3819. */
  3820. int indexOf (int startIndex, const String& textToLookFor) const throw();
  3821. /** Searches for a substring within this string.
  3822. Uses a case-insensitive comparison.
  3823. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3824. If textToLookFor is an empty string, this will always return 0.
  3825. */
  3826. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  3827. /** Searches for a substring within this string.
  3828. Uses a case-insensitive comparison.
  3829. @param startIndex the index from which the search should proceed
  3830. @param textToLookFor the string to search for
  3831. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3832. If textToLookFor is an empty string, this will always return -1.
  3833. */
  3834. int indexOfIgnoreCase (int startIndex, const String& textToLookFor) const throw();
  3835. /** Searches for a character inside this string (working backwards from the end of the string).
  3836. Uses a case-sensitive comparison.
  3837. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  3838. */
  3839. int lastIndexOfChar (juce_wchar character) const throw();
  3840. /** Searches for a substring inside this string (working backwards from the end of the string).
  3841. Uses a case-sensitive comparison.
  3842. @returns the index of the start of the last occurrence of the substring within this string,
  3843. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  3844. */
  3845. int lastIndexOf (const String& textToLookFor) const throw();
  3846. /** Searches for a substring inside this string (working backwards from the end of the string).
  3847. Uses a case-insensitive comparison.
  3848. @returns the index of the start of the last occurrence of the substring within this string, or -1
  3849. if it's not found. If textToLookFor is an empty string, this will always return -1.
  3850. */
  3851. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  3852. /** Returns the index of the last character in this string that matches one of the
  3853. characters passed-in to this method.
  3854. This scans the string backwards, starting from its end, and if it finds
  3855. a character that appears in the string charactersToLookFor, it returns its index.
  3856. If none of these characters are found, it returns -1.
  3857. If ignoreCase is true, the comparison will be case-insensitive.
  3858. @see lastIndexOf, indexOfAnyOf
  3859. */
  3860. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3861. bool ignoreCase = false) const throw();
  3862. // Substring extraction and manipulation methods..
  3863. /** Returns the character at this index in the string.
  3864. In a release build, no checks are made to see if the index is within a valid range, so be
  3865. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  3866. Also beware that depending on the encoding format that the string is using internally, this
  3867. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  3868. If you're scanning through a string to inspect its characters, you should never use this operator
  3869. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  3870. then to use that to iterate the string.
  3871. @see getCharPointer
  3872. */
  3873. const juce_wchar operator[] (int index) const throw();
  3874. /** Returns the final character of the string.
  3875. If the string is empty this will return 0.
  3876. */
  3877. juce_wchar getLastCharacter() const throw();
  3878. /** Returns a subsection of the string.
  3879. If the range specified is beyond the limits of the string, as much as
  3880. possible is returned.
  3881. @param startIndex the index of the start of the substring needed
  3882. @param endIndex all characters from startIndex up to (but not including)
  3883. this index are returned
  3884. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3885. */
  3886. const String substring (int startIndex, int endIndex) const;
  3887. /** Returns a section of the string, starting from a given position.
  3888. @param startIndex the first character to include. If this is beyond the end
  3889. of the string, an empty string is returned. If it is zero or
  3890. less, the whole string is returned.
  3891. @returns the substring from startIndex up to the end of the string
  3892. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3893. */
  3894. const String substring (int startIndex) const;
  3895. /** Returns a version of this string with a number of characters removed
  3896. from the end.
  3897. @param numberToDrop the number of characters to drop from the end of the
  3898. string. If this is greater than the length of the string,
  3899. an empty string will be returned. If zero or less, the
  3900. original string will be returned.
  3901. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3902. */
  3903. const String dropLastCharacters (int numberToDrop) const;
  3904. /** Returns a number of characters from the end of the string.
  3905. This returns the last numCharacters characters from the end of the string. If the
  3906. string is shorter than numCharacters, the whole string is returned.
  3907. @see substring, dropLastCharacters, getLastCharacter
  3908. */
  3909. const String getLastCharacters (int numCharacters) const;
  3910. /** Returns a section of the string starting from a given substring.
  3911. This will search for the first occurrence of the given substring, and
  3912. return the section of the string starting from the point where this is
  3913. found (optionally not including the substring itself).
  3914. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3915. fromFirstOccurrenceOf ("34", false) would return "56".
  3916. If the substring isn't found, the method will return an empty string.
  3917. If ignoreCase is true, the comparison will be case-insensitive.
  3918. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3919. */
  3920. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3921. bool includeSubStringInResult,
  3922. bool ignoreCase) const;
  3923. /** Returns a section of the string starting from the last occurrence of a given substring.
  3924. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3925. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3926. return the whole of the original string.
  3927. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3928. */
  3929. const String fromLastOccurrenceOf (const String& substringToFind,
  3930. bool includeSubStringInResult,
  3931. bool ignoreCase) const;
  3932. /** Returns the start of this string, up to the first occurrence of a substring.
  3933. This will search for the first occurrence of a given substring, and then
  3934. return a copy of the string, up to the position of this substring,
  3935. optionally including or excluding the substring itself in the result.
  3936. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3937. upTo ("34", true) would return "1234".
  3938. If the substring isn't found, this will return the whole of the original string.
  3939. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3940. */
  3941. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  3942. bool includeSubStringInResult,
  3943. bool ignoreCase) const;
  3944. /** Returns the start of this string, up to the last occurrence of a substring.
  3945. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3946. If the substring isn't found, this will return the whole of the original string.
  3947. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3948. */
  3949. const String upToLastOccurrenceOf (const String& substringToFind,
  3950. bool includeSubStringInResult,
  3951. bool ignoreCase) const;
  3952. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3953. const String trim() const;
  3954. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3955. const String trimStart() const;
  3956. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3957. const String trimEnd() const;
  3958. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3959. Characters are removed from the start of the string until it finds one that is not in the
  3960. specified set, and then it stops.
  3961. @param charactersToTrim the set of characters to remove.
  3962. @see trim, trimStart, trimCharactersAtEnd
  3963. */
  3964. const String trimCharactersAtStart (const String& charactersToTrim) const;
  3965. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3966. Characters are removed from the end of the string until it finds one that is not in the
  3967. specified set, and then it stops.
  3968. @param charactersToTrim the set of characters to remove.
  3969. @see trim, trimEnd, trimCharactersAtStart
  3970. */
  3971. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  3972. /** Returns an upper-case version of this string. */
  3973. const String toUpperCase() const;
  3974. /** Returns an lower-case version of this string. */
  3975. const String toLowerCase() const;
  3976. /** Replaces a sub-section of the string with another string.
  3977. This will return a copy of this string, with a set of characters
  3978. from startIndex to startIndex + numCharsToReplace removed, and with
  3979. a new string inserted in their place.
  3980. Note that this is a const method, and won't alter the string itself.
  3981. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3982. it will be constrained to a valid range.
  3983. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3984. characters will be taken out.
  3985. @param stringToInsert the new string to insert at startIndex after the characters have been
  3986. removed.
  3987. */
  3988. const String replaceSection (int startIndex,
  3989. int numCharactersToReplace,
  3990. const String& stringToInsert) const;
  3991. /** Replaces all occurrences of a substring with another string.
  3992. Returns a copy of this string, with any occurrences of stringToReplace
  3993. swapped for stringToInsertInstead.
  3994. Note that this is a const method, and won't alter the string itself.
  3995. */
  3996. const String replace (const String& stringToReplace,
  3997. const String& stringToInsertInstead,
  3998. bool ignoreCase = false) const;
  3999. /** Returns a string with all occurrences of a character replaced with a different one. */
  4000. const String replaceCharacter (juce_wchar characterToReplace,
  4001. juce_wchar characterToInsertInstead) const;
  4002. /** Replaces a set of characters with another set.
  4003. Returns a string in which each character from charactersToReplace has been replaced
  4004. by the character at the equivalent position in newCharacters (so the two strings
  4005. passed in must be the same length).
  4006. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  4007. Note that this is a const method, and won't affect the string itself.
  4008. */
  4009. const String replaceCharacters (const String& charactersToReplace,
  4010. const String& charactersToInsertInstead) const;
  4011. /** Returns a version of this string that only retains a fixed set of characters.
  4012. This will return a copy of this string, omitting any characters which are not
  4013. found in the string passed-in.
  4014. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  4015. Note that this is a const method, and won't alter the string itself.
  4016. */
  4017. const String retainCharacters (const String& charactersToRetain) const;
  4018. /** Returns a version of this string with a set of characters removed.
  4019. This will return a copy of this string, omitting any characters which are
  4020. found in the string passed-in.
  4021. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  4022. Note that this is a const method, and won't alter the string itself.
  4023. */
  4024. const String removeCharacters (const String& charactersToRemove) const;
  4025. /** Returns a section from the start of the string that only contains a certain set of characters.
  4026. This returns the leftmost section of the string, up to (and not including) the
  4027. first character that doesn't appear in the string passed in.
  4028. */
  4029. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  4030. /** Returns a section from the start of the string that only contains a certain set of characters.
  4031. This returns the leftmost section of the string, up to (and not including) the
  4032. first character that occurs in the string passed in. (If none of the specified
  4033. characters are found in the string, the return value will just be the original string).
  4034. */
  4035. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  4036. /** Checks whether the string might be in quotation marks.
  4037. @returns true if the string begins with a quote character (either a double or single quote).
  4038. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  4039. @see unquoted, quoted
  4040. */
  4041. bool isQuotedString() const;
  4042. /** Removes quotation marks from around the string, (if there are any).
  4043. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  4044. at the ends of the string are not affected. If there aren't any quotes, the original string
  4045. is returned.
  4046. Note that this is a const method, and won't alter the string itself.
  4047. @see isQuotedString, quoted
  4048. */
  4049. const String unquoted() const;
  4050. /** Adds quotation marks around a string.
  4051. This will return a copy of the string with a quote at the start and end, (but won't
  4052. add the quote if there's already one there, so it's safe to call this on strings that
  4053. may already have quotes around them).
  4054. Note that this is a const method, and won't alter the string itself.
  4055. @param quoteCharacter the character to add at the start and end
  4056. @see isQuotedString, unquoted
  4057. */
  4058. const String quoted (juce_wchar quoteCharacter = '"') const;
  4059. /** Creates a string which is a version of a string repeated and joined together.
  4060. @param stringToRepeat the string to repeat
  4061. @param numberOfTimesToRepeat how many times to repeat it
  4062. */
  4063. static const String repeatedString (const String& stringToRepeat,
  4064. int numberOfTimesToRepeat);
  4065. /** Returns a copy of this string with the specified character repeatedly added to its
  4066. beginning until the total length is at least the minimum length specified.
  4067. */
  4068. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  4069. /** Returns a copy of this string with the specified character repeatedly added to its
  4070. end until the total length is at least the minimum length specified.
  4071. */
  4072. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  4073. /** Creates a string from data in an unknown format.
  4074. This looks at some binary data and tries to guess whether it's Unicode
  4075. or 8-bit characters, then returns a string that represents it correctly.
  4076. Should be able to handle Unicode endianness correctly, by looking at
  4077. the first two bytes.
  4078. */
  4079. static const String createStringFromData (const void* data, int size);
  4080. /** Creates a String from a printf-style parameter list.
  4081. I don't like this method. I don't use it myself, and I recommend avoiding it and
  4082. using the operator<< methods or pretty much anything else instead. It's only provided
  4083. here because of the popular unrest that was stirred-up when I tried to remove it...
  4084. If you're really determined to use it, at least make sure that you never, ever,
  4085. pass any String objects to it as parameters. And bear in mind that internally, depending
  4086. on the platform, it may be using wchar_t or char character types, so that even string
  4087. literals can't be safely used as parameters if you're writing portable code.
  4088. */
  4089. static const String formatted (const String formatString, ... );
  4090. // Numeric conversions..
  4091. /** Creates a string containing this signed 32-bit integer as a decimal number.
  4092. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4093. */
  4094. explicit String (int decimalInteger);
  4095. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  4096. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4097. */
  4098. explicit String (unsigned int decimalInteger);
  4099. /** Creates a string containing this signed 16-bit integer as a decimal number.
  4100. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4101. */
  4102. explicit String (short decimalInteger);
  4103. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  4104. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4105. */
  4106. explicit String (unsigned short decimalInteger);
  4107. /** Creates a string containing this signed 64-bit integer as a decimal number.
  4108. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4109. */
  4110. explicit String (int64 largeIntegerValue);
  4111. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  4112. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4113. */
  4114. explicit String (uint64 largeIntegerValue);
  4115. /** Creates a string representing this floating-point number.
  4116. @param floatValue the value to convert to a string
  4117. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4118. decimal places, and will not use exponent notation. If 0 or
  4119. less, it will use exponent notation if necessary.
  4120. @see getDoubleValue, getIntValue
  4121. */
  4122. explicit String (float floatValue,
  4123. int numberOfDecimalPlaces = 0);
  4124. /** Creates a string representing this floating-point number.
  4125. @param doubleValue the value to convert to a string
  4126. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4127. decimal places, and will not use exponent notation. If 0 or
  4128. less, it will use exponent notation if necessary.
  4129. @see getFloatValue, getIntValue
  4130. */
  4131. explicit String (double doubleValue,
  4132. int numberOfDecimalPlaces = 0);
  4133. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  4134. @returns the value of the string as a 32 bit signed base-10 integer.
  4135. @see getTrailingIntValue, getHexValue32, getHexValue64
  4136. */
  4137. int getIntValue() const throw();
  4138. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  4139. @returns the value of the string as a 64 bit signed base-10 integer.
  4140. */
  4141. int64 getLargeIntValue() const throw();
  4142. /** Parses a decimal number from the end of the string.
  4143. This will look for a value at the end of the string.
  4144. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  4145. Negative numbers are not handled, so "xyz-5" returns 5.
  4146. @see getIntValue
  4147. */
  4148. int getTrailingIntValue() const throw();
  4149. /** Parses this string as a floating point number.
  4150. @returns the value of the string as a 32-bit floating point value.
  4151. @see getDoubleValue
  4152. */
  4153. float getFloatValue() const throw();
  4154. /** Parses this string as a floating point number.
  4155. @returns the value of the string as a 64-bit floating point value.
  4156. @see getFloatValue
  4157. */
  4158. double getDoubleValue() const throw();
  4159. /** Parses the string as a hexadecimal number.
  4160. Non-hexadecimal characters in the string are ignored.
  4161. If the string contains too many characters, then the lowest significant
  4162. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  4163. @returns a 32-bit number which is the value of the string in hex.
  4164. */
  4165. int getHexValue32() const throw();
  4166. /** Parses the string as a hexadecimal number.
  4167. Non-hexadecimal characters in the string are ignored.
  4168. If the string contains too many characters, then the lowest significant
  4169. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4170. @returns a 64-bit number which is the value of the string in hex.
  4171. */
  4172. int64 getHexValue64() const throw();
  4173. /** Creates a string representing this 32-bit value in hexadecimal. */
  4174. static const String toHexString (int number);
  4175. /** Creates a string representing this 64-bit value in hexadecimal. */
  4176. static const String toHexString (int64 number);
  4177. /** Creates a string representing this 16-bit value in hexadecimal. */
  4178. static const String toHexString (short number);
  4179. /** Creates a string containing a hex dump of a block of binary data.
  4180. @param data the binary data to use as input
  4181. @param size how many bytes of data to use
  4182. @param groupSize how many bytes are grouped together before inserting a
  4183. space into the output. e.g. group size 0 has no spaces,
  4184. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4185. like "bea1 c2ff".
  4186. */
  4187. static const String toHexString (const unsigned char* data,
  4188. int size,
  4189. int groupSize = 1);
  4190. /** Returns the character pointer currently being used to store this string.
  4191. Because it returns a reference to the string's internal data, the pointer
  4192. that is returned must not be stored anywhere, as it can be deleted whenever the
  4193. string changes.
  4194. */
  4195. inline const CharPointerType& getCharPointer() const throw() { return text; }
  4196. /** Returns a pointer to a UTF-8 version of this string.
  4197. Because it returns a reference to the string's internal data, the pointer
  4198. that is returned must not be stored anywhere, as it can be deleted whenever the
  4199. string changes.
  4200. To find out how many bytes you need to store this string as UTF-8, you can call
  4201. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4202. @see getCharPointer, toUTF16, toUTF32
  4203. */
  4204. const CharPointer_UTF8 toUTF8() const;
  4205. /** Returns a pointer to a UTF-32 version of this string.
  4206. Because it returns a reference to the string's internal data, the pointer
  4207. that is returned must not be stored anywhere, as it can be deleted whenever the
  4208. string changes.
  4209. To find out how many bytes you need to store this string as UTF-16, you can call
  4210. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4211. @see getCharPointer, toUTF8, toUTF32
  4212. */
  4213. CharPointer_UTF16 toUTF16() const;
  4214. /** Returns a pointer to a UTF-32 version of this string.
  4215. Because it returns a reference to the string's internal data, the pointer
  4216. that is returned must not be stored anywhere, as it can be deleted whenever the
  4217. string changes.
  4218. @see getCharPointer, toUTF8, toUTF16
  4219. */
  4220. CharPointer_UTF32 toUTF32() const;
  4221. /** Returns a pointer to a wchar_t version of this string.
  4222. Because it returns a reference to the string's internal data, the pointer
  4223. that is returned must not be stored anywhere, as it can be deleted whenever the
  4224. string changes.
  4225. Bear in mind that the wchar_t type is different on different platforms, so on
  4226. Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
  4227. as calling toUTF32(), etc.
  4228. @see getCharPointer, toUTF8, toUTF16, toUTF32
  4229. */
  4230. const wchar_t* toWideCharPointer() const;
  4231. /** Creates a String from a UTF-8 encoded buffer.
  4232. If the size is < 0, it'll keep reading until it hits a zero.
  4233. */
  4234. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4235. /** Returns the number of bytes required to represent this string as UTF8.
  4236. The number returned does NOT include the trailing zero.
  4237. @see toUTF8, copyToUTF8
  4238. */
  4239. int getNumBytesAsUTF8() const throw();
  4240. /** Copies the string to a buffer as UTF-8 characters.
  4241. Returns the number of bytes copied to the buffer, including the terminating null
  4242. character.
  4243. To find out how many bytes you need to store this string as UTF-8, you can call
  4244. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4245. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4246. returns the number of bytes required (including the terminating null character).
  4247. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4248. put in as many as it can while still allowing for a terminating null char at the
  4249. end, and will return the number of bytes that were actually used.
  4250. @see CharPointer_UTF8::writeWithDestByteLimit
  4251. */
  4252. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4253. /** Copies the string to a buffer as UTF-16 characters.
  4254. Returns the number of bytes copied to the buffer, including the terminating null
  4255. character.
  4256. To find out how many bytes you need to store this string as UTF-16, you can call
  4257. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4258. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4259. returns the number of bytes required (including the terminating null character).
  4260. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4261. put in as many as it can while still allowing for a terminating null char at the
  4262. end, and will return the number of bytes that were actually used.
  4263. @see CharPointer_UTF16::writeWithDestByteLimit
  4264. */
  4265. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4266. /** Copies the string to a buffer as UTF-16 characters.
  4267. Returns the number of bytes copied to the buffer, including the terminating null
  4268. character.
  4269. To find out how many bytes you need to store this string as UTF-32, you can call
  4270. CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
  4271. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4272. returns the number of bytes required (including the terminating null character).
  4273. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4274. put in as many as it can while still allowing for a terminating null char at the
  4275. end, and will return the number of bytes that were actually used.
  4276. @see CharPointer_UTF32::writeWithDestByteLimit
  4277. */
  4278. int copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4279. /** Increases the string's internally allocated storage.
  4280. Although the string's contents won't be affected by this call, it will
  4281. increase the amount of memory allocated internally for the string to grow into.
  4282. If you're about to make a large number of calls to methods such
  4283. as += or <<, it's more efficient to preallocate enough extra space
  4284. beforehand, so that these methods won't have to keep resizing the string
  4285. to append the extra characters.
  4286. @param numBytesNeeded the number of bytes to allocate storage for. If this
  4287. value is less than the currently allocated size, it will
  4288. have no effect.
  4289. */
  4290. void preallocateBytes (size_t numBytesNeeded);
  4291. /** Swaps the contents of this string with another one.
  4292. This is a very fast operation, as no allocation or copying needs to be done.
  4293. */
  4294. void swapWith (String& other) throw();
  4295. /** A helper class to improve performance when concatenating many large strings
  4296. together.
  4297. Because appending one string to another involves measuring the length of
  4298. both strings, repeatedly doing this for many long strings will become
  4299. an exponentially slow operation. This class uses some internal state to
  4300. avoid that, so that each append operation only needs to measure the length
  4301. of the appended string.
  4302. */
  4303. class JUCE_API Concatenator
  4304. {
  4305. public:
  4306. Concatenator (String& stringToAppendTo);
  4307. ~Concatenator();
  4308. void append (const String& s);
  4309. private:
  4310. String& result;
  4311. int nextIndex;
  4312. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4313. };
  4314. private:
  4315. CharPointerType text;
  4316. struct PreallocationBytes
  4317. {
  4318. explicit PreallocationBytes (size_t);
  4319. size_t numBytes;
  4320. };
  4321. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  4322. void appendFixedLength (const char* text, int numExtraChars);
  4323. size_t getByteOffsetOfEnd() const throw();
  4324. JUCE_DEPRECATED (String (const String& stringToCopy, size_t charsToAllocate));
  4325. // This private cast operator should prevent strings being accidentally cast
  4326. // to bools (this is possible because the compiler can add an implicit cast
  4327. // via a const char*)
  4328. operator bool() const throw() { return false; }
  4329. };
  4330. /** Concatenates two strings. */
  4331. JUCE_API const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4332. /** Concatenates two strings. */
  4333. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4334. /** Concatenates two strings. */
  4335. JUCE_API const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4336. /** Concatenates two strings. */
  4337. JUCE_API const String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
  4338. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4339. /** Concatenates two strings. */
  4340. JUCE_API const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4341. #endif
  4342. /** Concatenates two strings. */
  4343. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4344. /** Concatenates two strings. */
  4345. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4346. /** Concatenates two strings. */
  4347. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4348. /** Concatenates two strings. */
  4349. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4350. /** Concatenates two strings. */
  4351. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4352. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4353. /** Concatenates two strings. */
  4354. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4355. #endif
  4356. /** Appends a character at the end of a string. */
  4357. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4358. /** Appends a character at the end of a string. */
  4359. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
  4360. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4361. /** Appends a character at the end of a string. */
  4362. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4363. #endif
  4364. /** Appends a string to the end of the first one. */
  4365. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4366. /** Appends a string to the end of the first one. */
  4367. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
  4368. /** Appends a string to the end of the first one. */
  4369. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4370. /** Appends a decimal number at the end of a string. */
  4371. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4372. /** Appends a decimal number at the end of a string. */
  4373. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4374. /** Appends a decimal number at the end of a string. */
  4375. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4376. /** Appends a decimal number at the end of a string. */
  4377. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4378. /** Appends a decimal number at the end of a string. */
  4379. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4380. /** Case-sensitive comparison of two strings. */
  4381. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  4382. /** Case-sensitive comparison of two strings. */
  4383. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  4384. /** Case-sensitive comparison of two strings. */
  4385. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) throw();
  4386. /** Case-sensitive comparison of two strings. */
  4387. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw();
  4388. /** Case-sensitive comparison of two strings. */
  4389. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw();
  4390. /** Case-sensitive comparison of two strings. */
  4391. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw();
  4392. /** Case-sensitive comparison of two strings. */
  4393. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  4394. /** Case-sensitive comparison of two strings. */
  4395. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  4396. /** Case-sensitive comparison of two strings. */
  4397. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) throw();
  4398. /** Case-sensitive comparison of two strings. */
  4399. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw();
  4400. /** Case-sensitive comparison of two strings. */
  4401. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw();
  4402. /** Case-sensitive comparison of two strings. */
  4403. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw();
  4404. /** Case-sensitive comparison of two strings. */
  4405. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  4406. /** Case-sensitive comparison of two strings. */
  4407. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  4408. /** Case-sensitive comparison of two strings. */
  4409. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  4410. /** Case-sensitive comparison of two strings. */
  4411. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  4412. /** This operator allows you to write a juce String directly to std output streams.
  4413. This is handy for writing strings to std::cout, std::cerr, etc.
  4414. */
  4415. template <class traits>
  4416. std::basic_ostream <char, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite)
  4417. {
  4418. return stream << stringToWrite.toUTF8().getAddress();
  4419. }
  4420. /** This operator allows you to write a juce String directly to std output streams.
  4421. This is handy for writing strings to std::wcout, std::wcerr, etc.
  4422. */
  4423. template <class traits>
  4424. std::basic_ostream <wchar_t, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <wchar_t, traits>& stream, const String& stringToWrite)
  4425. {
  4426. return stream << stringToWrite.toWideCharPointer();
  4427. }
  4428. /** Writes a string to an OutputStream as UTF8. */
  4429. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& stringToWrite);
  4430. #endif // __JUCE_STRING_JUCEHEADER__
  4431. /*** End of inlined file: juce_String.h ***/
  4432. /**
  4433. Acts as an application-wide logging class.
  4434. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4435. method and this will then be used by all calls to writeToLog.
  4436. The logger class also contains methods for writing messages to the debugger's
  4437. output stream.
  4438. @see FileLogger
  4439. */
  4440. class JUCE_API Logger
  4441. {
  4442. public:
  4443. /** Destructor. */
  4444. virtual ~Logger();
  4445. /** Sets the current logging class to use.
  4446. Note that the object passed in won't be deleted when no longer needed.
  4447. A null pointer can be passed-in to disable any logging.
  4448. If deleteOldLogger is set to true, the existing logger will be
  4449. deleted (if there is one).
  4450. */
  4451. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4452. bool deleteOldLogger = false);
  4453. /** Writes a string to the current logger.
  4454. This will pass the string to the logger's logMessage() method if a logger
  4455. has been set.
  4456. @see logMessage
  4457. */
  4458. static void JUCE_CALLTYPE writeToLog (const String& message);
  4459. /** Writes a message to the standard error stream.
  4460. This can be called directly, or by using the DBG() macro in
  4461. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4462. */
  4463. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4464. protected:
  4465. Logger();
  4466. /** This is overloaded by subclasses to implement custom logging behaviour.
  4467. @see setCurrentLogger
  4468. */
  4469. virtual void logMessage (const String& message) = 0;
  4470. private:
  4471. static Logger* currentLogger;
  4472. };
  4473. #endif // __JUCE_LOGGER_JUCEHEADER__
  4474. /*** End of inlined file: juce_Logger.h ***/
  4475. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4476. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4477. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4478. /**
  4479. Embedding an instance of this class inside another class can be used as a low-overhead
  4480. way of detecting leaked instances.
  4481. This class keeps an internal static count of the number of instances that are
  4482. active, so that when the app is shutdown and the static destructors are called,
  4483. it can check whether there are any left-over instances that may have been leaked.
  4484. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4485. class declaration. Have a look through the juce codebase for examples, it's used
  4486. in most of the classes.
  4487. */
  4488. template <class OwnerClass>
  4489. class LeakedObjectDetector
  4490. {
  4491. public:
  4492. LeakedObjectDetector() throw() { ++(getCounter().numObjects); }
  4493. LeakedObjectDetector (const LeakedObjectDetector&) throw() { ++(getCounter().numObjects); }
  4494. ~LeakedObjectDetector()
  4495. {
  4496. if (--(getCounter().numObjects) < 0)
  4497. {
  4498. DBG ("*** Dangling pointer deletion! Class: " << getLeakedObjectClassName());
  4499. /** If you hit this, then you've managed to delete more instances of this class than you've
  4500. created.. That indicates that you're deleting some dangling pointers.
  4501. Note that although this assertion will have been triggered during a destructor, it might
  4502. not be this particular deletion that's at fault - the incorrect one may have happened
  4503. at an earlier point in the program, and simply not been detected until now.
  4504. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4505. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4506. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4507. */
  4508. jassertfalse;
  4509. }
  4510. }
  4511. private:
  4512. class LeakCounter
  4513. {
  4514. public:
  4515. LeakCounter() throw() {}
  4516. ~LeakCounter()
  4517. {
  4518. if (numObjects.value > 0)
  4519. {
  4520. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << getLeakedObjectClassName());
  4521. /** If you hit this, then you've leaked one or more objects of the type specified by
  4522. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4523. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4524. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4525. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4526. */
  4527. jassertfalse;
  4528. }
  4529. }
  4530. Atomic<int> numObjects;
  4531. };
  4532. static const char* getLeakedObjectClassName()
  4533. {
  4534. return OwnerClass::getLeakedObjectClassName();
  4535. }
  4536. static LeakCounter& getCounter() throw()
  4537. {
  4538. static LeakCounter counter;
  4539. return counter;
  4540. }
  4541. };
  4542. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4543. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4544. /** This macro lets you embed a leak-detecting object inside a class.
  4545. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4546. of the class declaration. E.g.
  4547. @code
  4548. class MyClass
  4549. {
  4550. public:
  4551. MyClass();
  4552. void blahBlah();
  4553. private:
  4554. JUCE_LEAK_DETECTOR (MyClass);
  4555. };@endcode
  4556. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4557. */
  4558. #define JUCE_LEAK_DETECTOR(OwnerClass) \
  4559. friend class JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass>; \
  4560. static const char* getLeakedObjectClassName() throw() { return #OwnerClass; } \
  4561. JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4562. #else
  4563. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4564. #endif
  4565. #endif
  4566. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4567. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4568. END_JUCE_NAMESPACE
  4569. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4570. /*** End of inlined file: juce_StandardHeader.h ***/
  4571. BEGIN_JUCE_NAMESPACE
  4572. #if JUCE_MSVC
  4573. // this is set explicitly in case the app is using a different packing size.
  4574. #pragma pack (push, 8)
  4575. #pragma warning (push)
  4576. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4577. #ifdef __INTEL_COMPILER
  4578. #pragma warning (disable: 1125)
  4579. #endif
  4580. #endif
  4581. // this is where all the class header files get brought in..
  4582. /*** Start of inlined file: juce_core_includes.h ***/
  4583. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4584. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4585. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4586. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4587. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4588. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4589. /**
  4590. Encapsulates the logic required to implement a lock-free FIFO.
  4591. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4592. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4593. its position and status when reading or writing to it.
  4594. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4595. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4596. outgoing block should be read from.
  4597. e.g.
  4598. @code
  4599. class MyFifo
  4600. {
  4601. public:
  4602. MyFifo() : abstractFifo (1024)
  4603. {
  4604. }
  4605. void addToFifo (const int* someData, int numItems)
  4606. {
  4607. int start1, size1, start2, size2;
  4608. prepareToWrite (numItems, start1, size1, start2, size2);
  4609. if (size1 > 0)
  4610. copySomeData (myBuffer + start1, someData, size1);
  4611. if (size2 > 0)
  4612. copySomeData (myBuffer + start2, someData + size1, size2);
  4613. finishedWrite (size1 + size2);
  4614. }
  4615. void readFromFifo (int* someData, int numItems)
  4616. {
  4617. int start1, size1, start2, size2;
  4618. prepareToRead (numSamples, start1, size1, start2, size2);
  4619. if (size1 > 0)
  4620. copySomeData (someData, myBuffer + start1, size1);
  4621. if (size2 > 0)
  4622. copySomeData (someData + size1, myBuffer + start2, size2);
  4623. finishedRead (size1 + size2);
  4624. }
  4625. private:
  4626. AbstractFifo abstractFifo;
  4627. int myBuffer [1024];
  4628. };
  4629. @endcode
  4630. */
  4631. class JUCE_API AbstractFifo
  4632. {
  4633. public:
  4634. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4635. AbstractFifo (int capacity) throw();
  4636. /** Destructor */
  4637. ~AbstractFifo();
  4638. /** Returns the total size of the buffer being managed. */
  4639. int getTotalSize() const throw();
  4640. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4641. int getFreeSpace() const throw();
  4642. /** Returns the number of items that can currently be read from the buffer. */
  4643. int getNumReady() const throw();
  4644. /** Clears the buffer positions, so that it appears empty. */
  4645. void reset() throw();
  4646. /** Changes the buffer's total size.
  4647. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4648. might overlap with a call to any other method in this class!
  4649. */
  4650. void setTotalSize (int newSize) throw();
  4651. /** Returns the location within the buffer at which an incoming block of data should be written.
  4652. Because the section of data that you want to add to the buffer may overlap the end
  4653. and wrap around to the start, two blocks within your buffer are returned, and you
  4654. should copy your data into the first one, with any remaining data spilling over into
  4655. the second.
  4656. If the number of items you ask for is too large to fit within the buffer's free space, then
  4657. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4658. may decide to keep waiting and re-trying the method until there's enough space available.
  4659. After calling this method, if you choose to write your data into the blocks returned, you
  4660. must call finishedWrite() to tell the FIFO how much data you actually added.
  4661. e.g.
  4662. @code
  4663. void addToFifo (const int* someData, int numItems)
  4664. {
  4665. int start1, size1, start2, size2;
  4666. prepareToWrite (numItems, start1, size1, start2, size2);
  4667. if (size1 > 0)
  4668. copySomeData (myBuffer + start1, someData, size1);
  4669. if (size2 > 0)
  4670. copySomeData (myBuffer + start2, someData + size1, size2);
  4671. finishedWrite (size1 + size2);
  4672. }
  4673. @endcode
  4674. @param numToWrite indicates how many items you'd like to add to the buffer
  4675. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4676. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4677. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4678. the first block should be written
  4679. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4680. @see finishedWrite
  4681. */
  4682. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  4683. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4684. @see prepareToWrite
  4685. */
  4686. void finishedWrite (int numWritten) throw();
  4687. /** Returns the location within the buffer from which the next block of data should be read.
  4688. Because the section of data that you want to read from the buffer may overlap the end
  4689. and wrap around to the start, two blocks within your buffer are returned, and you
  4690. should read from both of them.
  4691. If the number of items you ask for is greater than the amount of data available, then
  4692. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4693. may decide to keep waiting and re-trying the method until there's enough data available.
  4694. After calling this method, if you choose to read the data, you must call finishedRead() to
  4695. tell the FIFO how much data you have consumed.
  4696. e.g.
  4697. @code
  4698. void readFromFifo (int* someData, int numItems)
  4699. {
  4700. int start1, size1, start2, size2;
  4701. prepareToRead (numSamples, start1, size1, start2, size2);
  4702. if (size1 > 0)
  4703. copySomeData (someData, myBuffer + start1, size1);
  4704. if (size2 > 0)
  4705. copySomeData (someData + size1, myBuffer + start2, size2);
  4706. finishedRead (size1 + size2);
  4707. }
  4708. @endcode
  4709. @param numWanted indicates how many items you'd like to add to the buffer
  4710. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4711. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4712. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4713. the first block should be written
  4714. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4715. @see finishedRead
  4716. */
  4717. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  4718. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4719. @see prepareToRead
  4720. */
  4721. void finishedRead (int numRead) throw();
  4722. private:
  4723. int bufferSize;
  4724. Atomic <int> validStart, validEnd;
  4725. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4726. };
  4727. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4728. /*** End of inlined file: juce_AbstractFifo.h ***/
  4729. #endif
  4730. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4731. /*** Start of inlined file: juce_Array.h ***/
  4732. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4733. #define __JUCE_ARRAY_JUCEHEADER__
  4734. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4735. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4736. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4737. /*** Start of inlined file: juce_HeapBlock.h ***/
  4738. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4739. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4740. /**
  4741. Very simple container class to hold a pointer to some data on the heap.
  4742. When you need to allocate some heap storage for something, always try to use
  4743. this class instead of allocating the memory directly using malloc/free.
  4744. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4745. as an char*, but as long as you allocate it on the stack or as a class member,
  4746. it's almost impossible for it to leak memory.
  4747. It also makes your code much more concise and readable than doing the same thing
  4748. using direct allocations,
  4749. E.g. instead of this:
  4750. @code
  4751. int* temp = (int*) malloc (1024 * sizeof (int));
  4752. memcpy (temp, xyz, 1024 * sizeof (int));
  4753. free (temp);
  4754. temp = (int*) calloc (2048 * sizeof (int));
  4755. temp[0] = 1234;
  4756. memcpy (foobar, temp, 2048 * sizeof (int));
  4757. free (temp);
  4758. @endcode
  4759. ..you could just write this:
  4760. @code
  4761. HeapBlock <int> temp (1024);
  4762. memcpy (temp, xyz, 1024 * sizeof (int));
  4763. temp.calloc (2048);
  4764. temp[0] = 1234;
  4765. memcpy (foobar, temp, 2048 * sizeof (int));
  4766. @endcode
  4767. The class is extremely lightweight, containing only a pointer to the
  4768. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4769. as their less object-oriented counterparts. Despite adding safety, you probably
  4770. won't sacrifice any performance by using this in place of normal pointers.
  4771. @see Array, OwnedArray, MemoryBlock
  4772. */
  4773. template <class ElementType>
  4774. class HeapBlock
  4775. {
  4776. public:
  4777. /** Creates a HeapBlock which is initially just a null pointer.
  4778. After creation, you can resize the array using the malloc(), calloc(),
  4779. or realloc() methods.
  4780. */
  4781. HeapBlock() throw() : data (0)
  4782. {
  4783. }
  4784. /** Creates a HeapBlock containing a number of elements.
  4785. The contents of the block are undefined, as it will have been created by a
  4786. malloc call.
  4787. If you want an array of zero values, you can use the calloc() method instead.
  4788. */
  4789. explicit HeapBlock (const size_t numElements)
  4790. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4791. {
  4792. }
  4793. /** Destructor.
  4794. This will free the data, if any has been allocated.
  4795. */
  4796. ~HeapBlock()
  4797. {
  4798. ::free (data);
  4799. }
  4800. /** Returns a raw pointer to the allocated data.
  4801. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4802. freed by calling the free() method.
  4803. */
  4804. inline operator ElementType*() const throw() { return data; }
  4805. /** Returns a raw pointer to the allocated data.
  4806. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4807. freed by calling the free() method.
  4808. */
  4809. inline ElementType* getData() const throw() { return data; }
  4810. /** Returns a void pointer to the allocated data.
  4811. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4812. freed by calling the free() method.
  4813. */
  4814. inline operator void*() const throw() { return static_cast <void*> (data); }
  4815. /** Returns a void pointer to the allocated data.
  4816. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4817. freed by calling the free() method.
  4818. */
  4819. inline operator const void*() const throw() { return static_cast <const void*> (data); }
  4820. /** Lets you use indirect calls to the first element in the array.
  4821. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4822. be referencing a null pointer.
  4823. */
  4824. inline ElementType* operator->() const throw() { return data; }
  4825. /** Returns a reference to one of the data elements.
  4826. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4827. has no idea of the size it currently has allocated.
  4828. */
  4829. template <typename IndexType>
  4830. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  4831. /** Returns a pointer to a data element at an offset from the start of the array.
  4832. This is the same as doing pointer arithmetic on the raw pointer itself.
  4833. */
  4834. template <typename IndexType>
  4835. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  4836. /** Compares the pointer with another pointer.
  4837. This can be handy for checking whether this is a null pointer.
  4838. */
  4839. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  4840. /** Compares the pointer with another pointer.
  4841. This can be handy for checking whether this is a null pointer.
  4842. */
  4843. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  4844. /** Allocates a specified amount of memory.
  4845. This uses the normal malloc to allocate an amount of memory for this object.
  4846. Any previously allocated memory will be freed by this method.
  4847. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4848. you wouldn't need to specify the second parameter, but it can be handy if you need
  4849. to allocate a size in bytes rather than in terms of the number of elements.
  4850. The data that is allocated will be freed when this object is deleted, or when you
  4851. call free() or any of the allocation methods.
  4852. */
  4853. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4854. {
  4855. ::free (data);
  4856. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4857. }
  4858. /** Allocates a specified amount of memory and clears it.
  4859. This does the same job as the malloc() method, but clears the memory that it allocates.
  4860. */
  4861. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4862. {
  4863. ::free (data);
  4864. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4865. }
  4866. /** Allocates a specified amount of memory and optionally clears it.
  4867. This does the same job as either malloc() or calloc(), depending on the
  4868. initialiseToZero parameter.
  4869. */
  4870. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4871. {
  4872. ::free (data);
  4873. if (initialiseToZero)
  4874. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4875. else
  4876. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4877. }
  4878. /** Re-allocates a specified amount of memory.
  4879. The semantics of this method are the same as malloc() and calloc(), but it
  4880. uses realloc() to keep as much of the existing data as possible.
  4881. */
  4882. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4883. {
  4884. if (data == 0)
  4885. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4886. else
  4887. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4888. }
  4889. /** Frees any currently-allocated data.
  4890. This will free the data and reset this object to be a null pointer.
  4891. */
  4892. void free()
  4893. {
  4894. ::free (data);
  4895. data = 0;
  4896. }
  4897. /** Swaps this object's data with the data of another HeapBlock.
  4898. The two objects simply exchange their data pointers.
  4899. */
  4900. void swapWith (HeapBlock <ElementType>& other) throw()
  4901. {
  4902. swapVariables (data, other.data);
  4903. }
  4904. /** This fills the block with zeros, up to the number of elements specified.
  4905. Since the block has no way of knowing its own size, you must make sure that the number of
  4906. elements you specify doesn't exceed the allocated size.
  4907. */
  4908. void clear (size_t numElements) throw()
  4909. {
  4910. zeromem (data, sizeof (ElementType) * numElements);
  4911. }
  4912. private:
  4913. ElementType* data;
  4914. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4915. };
  4916. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4917. /*** End of inlined file: juce_HeapBlock.h ***/
  4918. /**
  4919. Implements some basic array storage allocation functions.
  4920. This class isn't really for public use - it's used by the other
  4921. array classes, but might come in handy for some purposes.
  4922. It inherits from a critical section class to allow the arrays to use
  4923. the "empty base class optimisation" pattern to reduce their footprint.
  4924. @see Array, OwnedArray, ReferenceCountedArray
  4925. */
  4926. template <class ElementType, class TypeOfCriticalSectionToUse>
  4927. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4928. {
  4929. public:
  4930. /** Creates an empty array. */
  4931. ArrayAllocationBase() throw()
  4932. : numAllocated (0)
  4933. {
  4934. }
  4935. /** Destructor. */
  4936. ~ArrayAllocationBase()
  4937. {
  4938. }
  4939. /** Changes the amount of storage allocated.
  4940. This will retain any data currently held in the array, and either add or
  4941. remove extra space at the end.
  4942. @param numElements the number of elements that are needed
  4943. */
  4944. void setAllocatedSize (const int numElements)
  4945. {
  4946. if (numAllocated != numElements)
  4947. {
  4948. if (numElements > 0)
  4949. elements.realloc (numElements);
  4950. else
  4951. elements.free();
  4952. numAllocated = numElements;
  4953. }
  4954. }
  4955. /** Increases the amount of storage allocated if it is less than a given amount.
  4956. This will retain any data currently held in the array, but will add
  4957. extra space at the end to make sure there it's at least as big as the size
  4958. passed in. If it's already bigger, no action is taken.
  4959. @param minNumElements the minimum number of elements that are needed
  4960. */
  4961. void ensureAllocatedSize (const int minNumElements)
  4962. {
  4963. if (minNumElements > numAllocated)
  4964. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4965. }
  4966. /** Minimises the amount of storage allocated so that it's no more than
  4967. the given number of elements.
  4968. */
  4969. void shrinkToNoMoreThan (const int maxNumElements)
  4970. {
  4971. if (maxNumElements < numAllocated)
  4972. setAllocatedSize (maxNumElements);
  4973. }
  4974. /** Swap the contents of two objects. */
  4975. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  4976. {
  4977. elements.swapWith (other.elements);
  4978. swapVariables (numAllocated, other.numAllocated);
  4979. }
  4980. HeapBlock <ElementType> elements;
  4981. int numAllocated;
  4982. private:
  4983. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4984. };
  4985. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4986. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  4987. /*** Start of inlined file: juce_ElementComparator.h ***/
  4988. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4989. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4990. /**
  4991. Sorts a range of elements in an array.
  4992. The comparator object that is passed-in must define a public method with the following
  4993. signature:
  4994. @code
  4995. int compareElements (ElementType first, ElementType second);
  4996. @endcode
  4997. ..and this method must return:
  4998. - a value of < 0 if the first comes before the second
  4999. - a value of 0 if the two objects are equivalent
  5000. - a value of > 0 if the second comes before the first
  5001. To improve performance, the compareElements() method can be declared as static or const.
  5002. @param comparator an object which defines a compareElements() method
  5003. @param array the array to sort
  5004. @param firstElement the index of the first element of the range to be sorted
  5005. @param lastElement the index of the last element in the range that needs
  5006. sorting (this is inclusive)
  5007. @param retainOrderOfEquivalentItems if true, the order of items that the
  5008. comparator deems the same will be maintained - this will be
  5009. a slower algorithm than if they are allowed to be moved around.
  5010. @see sortArrayRetainingOrder
  5011. */
  5012. template <class ElementType, class ElementComparator>
  5013. static void sortArray (ElementComparator& comparator,
  5014. ElementType* const array,
  5015. int firstElement,
  5016. int lastElement,
  5017. const bool retainOrderOfEquivalentItems)
  5018. {
  5019. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5020. // avoids getting warning messages about the parameter being unused
  5021. if (lastElement > firstElement)
  5022. {
  5023. if (retainOrderOfEquivalentItems)
  5024. {
  5025. for (int i = firstElement; i < lastElement; ++i)
  5026. {
  5027. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  5028. {
  5029. swapVariables (array[i], array[i + 1]);
  5030. if (i > firstElement)
  5031. i -= 2;
  5032. }
  5033. }
  5034. }
  5035. else
  5036. {
  5037. int fromStack[30], toStack[30];
  5038. int stackIndex = 0;
  5039. for (;;)
  5040. {
  5041. const int size = (lastElement - firstElement) + 1;
  5042. if (size <= 8)
  5043. {
  5044. int j = lastElement;
  5045. int maxIndex;
  5046. while (j > firstElement)
  5047. {
  5048. maxIndex = firstElement;
  5049. for (int k = firstElement + 1; k <= j; ++k)
  5050. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  5051. maxIndex = k;
  5052. swapVariables (array[j], array[maxIndex]);
  5053. --j;
  5054. }
  5055. }
  5056. else
  5057. {
  5058. const int mid = firstElement + (size >> 1);
  5059. swapVariables (array[mid], array[firstElement]);
  5060. int i = firstElement;
  5061. int j = lastElement + 1;
  5062. for (;;)
  5063. {
  5064. while (++i <= lastElement
  5065. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  5066. {}
  5067. while (--j > firstElement
  5068. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  5069. {}
  5070. if (j < i)
  5071. break;
  5072. swapVariables (array[i], array[j]);
  5073. }
  5074. swapVariables (array[j], array[firstElement]);
  5075. if (j - 1 - firstElement >= lastElement - i)
  5076. {
  5077. if (firstElement + 1 < j)
  5078. {
  5079. fromStack [stackIndex] = firstElement;
  5080. toStack [stackIndex] = j - 1;
  5081. ++stackIndex;
  5082. }
  5083. if (i < lastElement)
  5084. {
  5085. firstElement = i;
  5086. continue;
  5087. }
  5088. }
  5089. else
  5090. {
  5091. if (i < lastElement)
  5092. {
  5093. fromStack [stackIndex] = i;
  5094. toStack [stackIndex] = lastElement;
  5095. ++stackIndex;
  5096. }
  5097. if (firstElement + 1 < j)
  5098. {
  5099. lastElement = j - 1;
  5100. continue;
  5101. }
  5102. }
  5103. }
  5104. if (--stackIndex < 0)
  5105. break;
  5106. jassert (stackIndex < numElementsInArray (fromStack));
  5107. firstElement = fromStack [stackIndex];
  5108. lastElement = toStack [stackIndex];
  5109. }
  5110. }
  5111. }
  5112. }
  5113. /**
  5114. Searches a sorted array of elements, looking for the index at which a specified value
  5115. should be inserted for it to be in the correct order.
  5116. The comparator object that is passed-in must define a public method with the following
  5117. signature:
  5118. @code
  5119. int compareElements (ElementType first, ElementType second);
  5120. @endcode
  5121. ..and this method must return:
  5122. - a value of < 0 if the first comes before the second
  5123. - a value of 0 if the two objects are equivalent
  5124. - a value of > 0 if the second comes before the first
  5125. To improve performance, the compareElements() method can be declared as static or const.
  5126. @param comparator an object which defines a compareElements() method
  5127. @param array the array to search
  5128. @param newElement the value that is going to be inserted
  5129. @param firstElement the index of the first element to search
  5130. @param lastElement the index of the last element in the range (this is non-inclusive)
  5131. */
  5132. template <class ElementType, class ElementComparator>
  5133. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  5134. ElementType* const array,
  5135. const ElementType newElement,
  5136. int firstElement,
  5137. int lastElement)
  5138. {
  5139. jassert (firstElement <= lastElement);
  5140. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5141. // avoids getting warning messages about the parameter being unused
  5142. while (firstElement < lastElement)
  5143. {
  5144. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  5145. {
  5146. ++firstElement;
  5147. break;
  5148. }
  5149. else
  5150. {
  5151. const int halfway = (firstElement + lastElement) >> 1;
  5152. if (halfway == firstElement)
  5153. {
  5154. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5155. ++firstElement;
  5156. break;
  5157. }
  5158. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5159. {
  5160. firstElement = halfway;
  5161. }
  5162. else
  5163. {
  5164. lastElement = halfway;
  5165. }
  5166. }
  5167. }
  5168. return firstElement;
  5169. }
  5170. /**
  5171. A simple ElementComparator class that can be used to sort an array of
  5172. objects that support the '<' operator.
  5173. This will work for primitive types and objects that implement operator<().
  5174. Example: @code
  5175. Array <int> myArray;
  5176. DefaultElementComparator<int> sorter;
  5177. myArray.sort (sorter);
  5178. @endcode
  5179. @see ElementComparator
  5180. */
  5181. template <class ElementType>
  5182. class DefaultElementComparator
  5183. {
  5184. private:
  5185. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5186. public:
  5187. static int compareElements (ParameterType first, ParameterType second)
  5188. {
  5189. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5190. }
  5191. };
  5192. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5193. /*** End of inlined file: juce_ElementComparator.h ***/
  5194. /*** Start of inlined file: juce_CriticalSection.h ***/
  5195. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5196. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5197. /*** Start of inlined file: juce_ScopedLock.h ***/
  5198. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5199. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5200. /**
  5201. Automatically locks and unlocks a mutex object.
  5202. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5203. The templated class could be a CriticalSection, SpinLock, or anything else that
  5204. provides enter() and exit() methods.
  5205. e.g. @code
  5206. CriticalSection myCriticalSection;
  5207. for (;;)
  5208. {
  5209. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5210. // myCriticalSection is now locked
  5211. ...do some stuff...
  5212. // myCriticalSection gets unlocked here.
  5213. }
  5214. @endcode
  5215. @see GenericScopedUnlock, CriticalSection, SpinLock, ScopedLock, ScopedUnlock
  5216. */
  5217. template <class LockType>
  5218. class GenericScopedLock
  5219. {
  5220. public:
  5221. /** Creates a GenericScopedLock.
  5222. As soon as it is created, this will acquire the lock, and when the GenericScopedLock
  5223. object is deleted, the lock will be released.
  5224. Make sure this object is created and deleted by the same thread,
  5225. otherwise there are no guarantees what will happen! Best just to use it
  5226. as a local stack object, rather than creating one with the new() operator.
  5227. */
  5228. inline explicit GenericScopedLock (const LockType& lock) throw() : lock_ (lock) { lock.enter(); }
  5229. /** Destructor.
  5230. The lock will be released when the destructor is called.
  5231. Make sure this object is created and deleted by the same thread, otherwise there are
  5232. no guarantees what will happen!
  5233. */
  5234. inline ~GenericScopedLock() throw() { lock_.exit(); }
  5235. private:
  5236. const LockType& lock_;
  5237. JUCE_DECLARE_NON_COPYABLE (GenericScopedLock);
  5238. };
  5239. /**
  5240. Automatically unlocks and re-locks a mutex object.
  5241. This is the reverse of a GenericScopedLock object - instead of locking the mutex
  5242. for the lifetime of this object, it unlocks it.
  5243. Make sure you don't try to unlock mutexes that aren't actually locked!
  5244. e.g. @code
  5245. CriticalSection myCriticalSection;
  5246. for (;;)
  5247. {
  5248. const GenericScopedLock<CriticalSection> myScopedLock (myCriticalSection);
  5249. // myCriticalSection is now locked
  5250. ... do some stuff with it locked ..
  5251. while (xyz)
  5252. {
  5253. ... do some stuff with it locked ..
  5254. const GenericScopedUnlock<CriticalSection> unlocker (myCriticalSection);
  5255. // myCriticalSection is now unlocked for the remainder of this block,
  5256. // and re-locked at the end.
  5257. ...do some stuff with it unlocked ...
  5258. }
  5259. // myCriticalSection gets unlocked here.
  5260. }
  5261. @endcode
  5262. @see GenericScopedLock, CriticalSection, ScopedLock, ScopedUnlock
  5263. */
  5264. template <class LockType>
  5265. class GenericScopedUnlock
  5266. {
  5267. public:
  5268. /** Creates a GenericScopedUnlock.
  5269. As soon as it is created, this will unlock the CriticalSection, and
  5270. when the ScopedLock object is deleted, the CriticalSection will
  5271. be re-locked.
  5272. Make sure this object is created and deleted by the same thread,
  5273. otherwise there are no guarantees what will happen! Best just to use it
  5274. as a local stack object, rather than creating one with the new() operator.
  5275. */
  5276. inline explicit GenericScopedUnlock (const LockType& lock) throw() : lock_ (lock) { lock.exit(); }
  5277. /** Destructor.
  5278. The CriticalSection will be unlocked when the destructor is called.
  5279. Make sure this object is created and deleted by the same thread,
  5280. otherwise there are no guarantees what will happen!
  5281. */
  5282. inline ~GenericScopedUnlock() throw() { lock_.enter(); }
  5283. private:
  5284. const LockType& lock_;
  5285. JUCE_DECLARE_NON_COPYABLE (GenericScopedUnlock);
  5286. };
  5287. /**
  5288. Automatically locks and unlocks a mutex object.
  5289. Use one of these as a local variable to provide RAII-based locking of a mutex.
  5290. The templated class could be a CriticalSection, SpinLock, or anything else that
  5291. provides enter() and exit() methods.
  5292. e.g. @code
  5293. CriticalSection myCriticalSection;
  5294. for (;;)
  5295. {
  5296. const GenericScopedTryLock<CriticalSection> myScopedTryLock (myCriticalSection);
  5297. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5298. // should test this with the isLocked() method before doing your thread-unsafe
  5299. // action..
  5300. if (myScopedTryLock.isLocked())
  5301. {
  5302. ...do some stuff...
  5303. }
  5304. else
  5305. {
  5306. ..our attempt at locking failed because another thread had already locked it..
  5307. }
  5308. // myCriticalSection gets unlocked here (if it was locked)
  5309. }
  5310. @endcode
  5311. @see CriticalSection::tryEnter, GenericScopedLock, GenericScopedUnlock
  5312. */
  5313. template <class LockType>
  5314. class GenericScopedTryLock
  5315. {
  5316. public:
  5317. /** Creates a GenericScopedTryLock.
  5318. As soon as it is created, this will attempt to acquire the lock, and when the
  5319. GenericScopedTryLock is deleted, the lock will be released (if the lock was
  5320. successfully acquired).
  5321. Make sure this object is created and deleted by the same thread,
  5322. otherwise there are no guarantees what will happen! Best just to use it
  5323. as a local stack object, rather than creating one with the new() operator.
  5324. */
  5325. inline explicit GenericScopedTryLock (const LockType& lock) throw()
  5326. : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  5327. /** Destructor.
  5328. The mutex will be unlocked (if it had been successfully locked) when the
  5329. destructor is called.
  5330. Make sure this object is created and deleted by the same thread,
  5331. otherwise there are no guarantees what will happen!
  5332. */
  5333. inline ~GenericScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  5334. /** Returns true if the mutex was successfully locked. */
  5335. bool isLocked() const throw() { return lockWasSuccessful; }
  5336. private:
  5337. const LockType& lock_;
  5338. const bool lockWasSuccessful;
  5339. JUCE_DECLARE_NON_COPYABLE (GenericScopedTryLock);
  5340. };
  5341. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5342. /*** End of inlined file: juce_ScopedLock.h ***/
  5343. /**
  5344. A mutex class.
  5345. A CriticalSection acts as a re-entrant mutex lock. The best way to lock and unlock
  5346. one of these is by using RAII in the form of a local ScopedLock object - have a look
  5347. through the codebase for many examples of how to do this.
  5348. @see ScopedLock, ScopedTryLock, ScopedUnlock, SpinLock, ReadWriteLock, Thread, InterProcessLock
  5349. */
  5350. class JUCE_API CriticalSection
  5351. {
  5352. public:
  5353. /** Creates a CriticalSection object. */
  5354. CriticalSection() throw();
  5355. /** Destructor.
  5356. If the critical section is deleted whilst locked, any subsequent behaviour
  5357. is unpredictable.
  5358. */
  5359. ~CriticalSection() throw();
  5360. /** Acquires the lock.
  5361. If the lock is already held by the caller thread, the method returns immediately.
  5362. If the lock is currently held by another thread, this will wait until it becomes free.
  5363. It's strongly recommended that you never call this method directly - instead use the
  5364. ScopedLock class to manage the locking using an RAII pattern instead.
  5365. @see exit, tryEnter, ScopedLock
  5366. */
  5367. void enter() const throw();
  5368. /** Attempts to lock this critical section without blocking.
  5369. This method behaves identically to CriticalSection::enter, except that the caller thread
  5370. does not wait if the lock is currently held by another thread but returns false immediately.
  5371. @returns false if the lock is currently held by another thread, true otherwise.
  5372. @see enter
  5373. */
  5374. bool tryEnter() const throw();
  5375. /** Releases the lock.
  5376. If the caller thread hasn't got the lock, this can have unpredictable results.
  5377. If the enter() method has been called multiple times by the thread, each
  5378. call must be matched by a call to exit() before other threads will be allowed
  5379. to take over the lock.
  5380. @see enter, ScopedLock
  5381. */
  5382. void exit() const throw();
  5383. /** Provides the type of scoped lock to use with a CriticalSection. */
  5384. typedef GenericScopedLock <CriticalSection> ScopedLockType;
  5385. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  5386. typedef GenericScopedUnlock <CriticalSection> ScopedUnlockType;
  5387. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  5388. typedef GenericScopedTryLock <CriticalSection> ScopedTryLockType;
  5389. private:
  5390. #if JUCE_WINDOWS
  5391. // To avoid including windows.h in the public JUCE headers, we'll just allocate a
  5392. // block of memory here that's big enough to be used internally as a windows critical
  5393. // section structure.
  5394. #if JUCE_64BIT
  5395. uint8 internal [44];
  5396. #else
  5397. uint8 internal [24];
  5398. #endif
  5399. #else
  5400. mutable pthread_mutex_t internal;
  5401. #endif
  5402. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5403. };
  5404. /**
  5405. A class that can be used in place of a real CriticalSection object, but which
  5406. doesn't perform any locking.
  5407. This is currently used by some templated classes, and most compilers should
  5408. manage to optimise it out of existence.
  5409. @see CriticalSection, Array, OwnedArray, ReferenceCountedArray
  5410. */
  5411. class JUCE_API DummyCriticalSection
  5412. {
  5413. public:
  5414. inline DummyCriticalSection() throw() {}
  5415. inline ~DummyCriticalSection() throw() {}
  5416. inline void enter() const throw() {}
  5417. inline bool tryEnter() const throw() { return true; }
  5418. inline void exit() const throw() {}
  5419. /** A dummy scoped-lock type to use with a dummy critical section. */
  5420. struct ScopedLockType
  5421. {
  5422. ScopedLockType (const DummyCriticalSection&) throw() {}
  5423. };
  5424. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5425. typedef ScopedLockType ScopedUnlockType;
  5426. private:
  5427. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5428. };
  5429. /**
  5430. Automatically locks and unlocks a CriticalSection object.
  5431. Use one of these as a local variable to provide RAII-based locking of a CriticalSection.
  5432. e.g. @code
  5433. CriticalSection myCriticalSection;
  5434. for (;;)
  5435. {
  5436. const ScopedLock myScopedLock (myCriticalSection);
  5437. // myCriticalSection is now locked
  5438. ...do some stuff...
  5439. // myCriticalSection gets unlocked here.
  5440. }
  5441. @endcode
  5442. @see CriticalSection, ScopedUnlock
  5443. */
  5444. typedef CriticalSection::ScopedLockType ScopedLock;
  5445. /**
  5446. Automatically unlocks and re-locks a CriticalSection object.
  5447. This is the reverse of a ScopedLock object - instead of locking the critical
  5448. section for the lifetime of this object, it unlocks it.
  5449. Make sure you don't try to unlock critical sections that aren't actually locked!
  5450. e.g. @code
  5451. CriticalSection myCriticalSection;
  5452. for (;;)
  5453. {
  5454. const ScopedLock myScopedLock (myCriticalSection);
  5455. // myCriticalSection is now locked
  5456. ... do some stuff with it locked ..
  5457. while (xyz)
  5458. {
  5459. ... do some stuff with it locked ..
  5460. const ScopedUnlock unlocker (myCriticalSection);
  5461. // myCriticalSection is now unlocked for the remainder of this block,
  5462. // and re-locked at the end.
  5463. ...do some stuff with it unlocked ...
  5464. }
  5465. // myCriticalSection gets unlocked here.
  5466. }
  5467. @endcode
  5468. @see CriticalSection, ScopedLock
  5469. */
  5470. typedef CriticalSection::ScopedUnlockType ScopedUnlock;
  5471. /**
  5472. Automatically tries to lock and unlock a CriticalSection object.
  5473. Use one of these as a local variable to control access to a CriticalSection.
  5474. e.g. @code
  5475. CriticalSection myCriticalSection;
  5476. for (;;)
  5477. {
  5478. const ScopedTryLock myScopedTryLock (myCriticalSection);
  5479. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  5480. // should test this with the isLocked() method before doing your thread-unsafe
  5481. // action..
  5482. if (myScopedTryLock.isLocked())
  5483. {
  5484. ...do some stuff...
  5485. }
  5486. else
  5487. {
  5488. ..our attempt at locking failed because another thread had already locked it..
  5489. }
  5490. // myCriticalSection gets unlocked here (if it was locked)
  5491. }
  5492. @endcode
  5493. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  5494. */
  5495. typedef CriticalSection::ScopedTryLockType ScopedTryLock;
  5496. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5497. /*** End of inlined file: juce_CriticalSection.h ***/
  5498. /**
  5499. Holds a resizable array of primitive or copy-by-value objects.
  5500. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5501. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5502. do so, the class must fulfil these requirements:
  5503. - it must have a copy constructor and assignment operator
  5504. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5505. objects whose functionality relies on external pointers or references to themselves can be used.
  5506. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5507. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5508. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5509. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5510. specialised class StringArray, which provides more useful functions.
  5511. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5512. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5513. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5514. */
  5515. template <typename ElementType,
  5516. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5517. class Array
  5518. {
  5519. private:
  5520. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5521. public:
  5522. /** Creates an empty array. */
  5523. Array() throw()
  5524. : numUsed (0)
  5525. {
  5526. }
  5527. /** Creates a copy of another array.
  5528. @param other the array to copy
  5529. */
  5530. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5531. {
  5532. const ScopedLockType lock (other.getLock());
  5533. numUsed = other.numUsed;
  5534. data.setAllocatedSize (other.numUsed);
  5535. for (int i = 0; i < numUsed; ++i)
  5536. new (data.elements + i) ElementType (other.data.elements[i]);
  5537. }
  5538. /** Initalises from a null-terminated C array of values.
  5539. @param values the array to copy from
  5540. */
  5541. template <typename TypeToCreateFrom>
  5542. explicit Array (const TypeToCreateFrom* values)
  5543. : numUsed (0)
  5544. {
  5545. while (*values != TypeToCreateFrom())
  5546. add (*values++);
  5547. }
  5548. /** Initalises from a C array of values.
  5549. @param values the array to copy from
  5550. @param numValues the number of values in the array
  5551. */
  5552. template <typename TypeToCreateFrom>
  5553. Array (const TypeToCreateFrom* values, int numValues)
  5554. : numUsed (numValues)
  5555. {
  5556. data.setAllocatedSize (numValues);
  5557. for (int i = 0; i < numValues; ++i)
  5558. new (data.elements + i) ElementType (values[i]);
  5559. }
  5560. /** Destructor. */
  5561. ~Array()
  5562. {
  5563. for (int i = 0; i < numUsed; ++i)
  5564. data.elements[i].~ElementType();
  5565. }
  5566. /** Copies another array.
  5567. @param other the array to copy
  5568. */
  5569. Array& operator= (const Array& other)
  5570. {
  5571. if (this != &other)
  5572. {
  5573. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5574. swapWithArray (otherCopy);
  5575. }
  5576. return *this;
  5577. }
  5578. /** Compares this array to another one.
  5579. Two arrays are considered equal if they both contain the same set of
  5580. elements, in the same order.
  5581. @param other the other array to compare with
  5582. */
  5583. template <class OtherArrayType>
  5584. bool operator== (const OtherArrayType& other) const
  5585. {
  5586. const ScopedLockType lock (getLock());
  5587. if (numUsed != other.numUsed)
  5588. return false;
  5589. for (int i = numUsed; --i >= 0;)
  5590. if (! (data.elements [i] == other.data.elements [i]))
  5591. return false;
  5592. return true;
  5593. }
  5594. /** Compares this array to another one.
  5595. Two arrays are considered equal if they both contain the same set of
  5596. elements, in the same order.
  5597. @param other the other array to compare with
  5598. */
  5599. template <class OtherArrayType>
  5600. bool operator!= (const OtherArrayType& other) const
  5601. {
  5602. return ! operator== (other);
  5603. }
  5604. /** Removes all elements from the array.
  5605. This will remove all the elements, and free any storage that the array is
  5606. using. To clear the array without freeing the storage, use the clearQuick()
  5607. method instead.
  5608. @see clearQuick
  5609. */
  5610. void clear()
  5611. {
  5612. const ScopedLockType lock (getLock());
  5613. for (int i = 0; i < numUsed; ++i)
  5614. data.elements[i].~ElementType();
  5615. data.setAllocatedSize (0);
  5616. numUsed = 0;
  5617. }
  5618. /** Removes all elements from the array without freeing the array's allocated storage.
  5619. @see clear
  5620. */
  5621. void clearQuick()
  5622. {
  5623. const ScopedLockType lock (getLock());
  5624. for (int i = 0; i < numUsed; ++i)
  5625. data.elements[i].~ElementType();
  5626. numUsed = 0;
  5627. }
  5628. /** Returns the current number of elements in the array.
  5629. */
  5630. inline int size() const throw()
  5631. {
  5632. return numUsed;
  5633. }
  5634. /** Returns one of the elements in the array.
  5635. If the index passed in is beyond the range of valid elements, this
  5636. will return zero.
  5637. If you're certain that the index will always be a valid element, you
  5638. can call getUnchecked() instead, which is faster.
  5639. @param index the index of the element being requested (0 is the first element in the array)
  5640. @see getUnchecked, getFirst, getLast
  5641. */
  5642. inline ElementType operator[] (const int index) const
  5643. {
  5644. const ScopedLockType lock (getLock());
  5645. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5646. : ElementType();
  5647. }
  5648. /** Returns one of the elements in the array, without checking the index passed in.
  5649. Unlike the operator[] method, this will try to return an element without
  5650. checking that the index is within the bounds of the array, so should only
  5651. be used when you're confident that it will always be a valid index.
  5652. @param index the index of the element being requested (0 is the first element in the array)
  5653. @see operator[], getFirst, getLast
  5654. */
  5655. inline const ElementType getUnchecked (const int index) const
  5656. {
  5657. const ScopedLockType lock (getLock());
  5658. jassert (isPositiveAndBelow (index, numUsed));
  5659. return data.elements [index];
  5660. }
  5661. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5662. This is like getUnchecked, but returns a direct reference to the element, so that
  5663. you can alter it directly. Obviously this can be dangerous, so only use it when
  5664. absolutely necessary.
  5665. @param index the index of the element being requested (0 is the first element in the array)
  5666. @see operator[], getFirst, getLast
  5667. */
  5668. inline ElementType& getReference (const int index) const throw()
  5669. {
  5670. const ScopedLockType lock (getLock());
  5671. jassert (isPositiveAndBelow (index, numUsed));
  5672. return data.elements [index];
  5673. }
  5674. /** Returns the first element in the array, or 0 if the array is empty.
  5675. @see operator[], getUnchecked, getLast
  5676. */
  5677. inline ElementType getFirst() const
  5678. {
  5679. const ScopedLockType lock (getLock());
  5680. return (numUsed > 0) ? data.elements [0]
  5681. : ElementType();
  5682. }
  5683. /** Returns the last element in the array, or 0 if the array is empty.
  5684. @see operator[], getUnchecked, getFirst
  5685. */
  5686. inline ElementType getLast() const
  5687. {
  5688. const ScopedLockType lock (getLock());
  5689. return (numUsed > 0) ? data.elements [numUsed - 1]
  5690. : ElementType();
  5691. }
  5692. /** Returns a pointer to the actual array data.
  5693. This pointer will only be valid until the next time a non-const method
  5694. is called on the array.
  5695. */
  5696. inline ElementType* getRawDataPointer() throw()
  5697. {
  5698. return data.elements;
  5699. }
  5700. /** Finds the index of the first element which matches the value passed in.
  5701. This will search the array for the given object, and return the index
  5702. of its first occurrence. If the object isn't found, the method will return -1.
  5703. @param elementToLookFor the value or object to look for
  5704. @returns the index of the object, or -1 if it's not found
  5705. */
  5706. int indexOf (ParameterType elementToLookFor) const
  5707. {
  5708. const ScopedLockType lock (getLock());
  5709. const ElementType* e = data.elements.getData();
  5710. const ElementType* const end = e + numUsed;
  5711. for (; e != end; ++e)
  5712. if (elementToLookFor == *e)
  5713. return static_cast <int> (e - data.elements.getData());
  5714. return -1;
  5715. }
  5716. /** Returns true if the array contains at least one occurrence of an object.
  5717. @param elementToLookFor the value or object to look for
  5718. @returns true if the item is found
  5719. */
  5720. bool contains (ParameterType elementToLookFor) const
  5721. {
  5722. const ScopedLockType lock (getLock());
  5723. const ElementType* e = data.elements.getData();
  5724. const ElementType* const end = e + numUsed;
  5725. for (; e != end; ++e)
  5726. if (elementToLookFor == *e)
  5727. return true;
  5728. return false;
  5729. }
  5730. /** Appends a new element at the end of the array.
  5731. @param newElement the new object to add to the array
  5732. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5733. */
  5734. void add (ParameterType newElement)
  5735. {
  5736. const ScopedLockType lock (getLock());
  5737. data.ensureAllocatedSize (numUsed + 1);
  5738. new (data.elements + numUsed++) ElementType (newElement);
  5739. }
  5740. /** Inserts a new element into the array at a given position.
  5741. If the index is less than 0 or greater than the size of the array, the
  5742. element will be added to the end of the array.
  5743. Otherwise, it will be inserted into the array, moving all the later elements
  5744. along to make room.
  5745. @param indexToInsertAt the index at which the new element should be
  5746. inserted (pass in -1 to add it to the end)
  5747. @param newElement the new object to add to the array
  5748. @see add, addSorted, addUsingDefaultSort, set
  5749. */
  5750. void insert (int indexToInsertAt, ParameterType newElement)
  5751. {
  5752. const ScopedLockType lock (getLock());
  5753. data.ensureAllocatedSize (numUsed + 1);
  5754. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5755. {
  5756. ElementType* const insertPos = data.elements + indexToInsertAt;
  5757. const int numberToMove = numUsed - indexToInsertAt;
  5758. if (numberToMove > 0)
  5759. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5760. new (insertPos) ElementType (newElement);
  5761. ++numUsed;
  5762. }
  5763. else
  5764. {
  5765. new (data.elements + numUsed++) ElementType (newElement);
  5766. }
  5767. }
  5768. /** Inserts multiple copies of an element into the array at a given position.
  5769. If the index is less than 0 or greater than the size of the array, the
  5770. element will be added to the end of the array.
  5771. Otherwise, it will be inserted into the array, moving all the later elements
  5772. along to make room.
  5773. @param indexToInsertAt the index at which the new element should be inserted
  5774. @param newElement the new object to add to the array
  5775. @param numberOfTimesToInsertIt how many copies of the value to insert
  5776. @see insert, add, addSorted, set
  5777. */
  5778. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5779. int numberOfTimesToInsertIt)
  5780. {
  5781. if (numberOfTimesToInsertIt > 0)
  5782. {
  5783. const ScopedLockType lock (getLock());
  5784. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5785. ElementType* insertPos;
  5786. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5787. {
  5788. insertPos = data.elements + indexToInsertAt;
  5789. const int numberToMove = numUsed - indexToInsertAt;
  5790. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5791. }
  5792. else
  5793. {
  5794. insertPos = data.elements + numUsed;
  5795. }
  5796. numUsed += numberOfTimesToInsertIt;
  5797. while (--numberOfTimesToInsertIt >= 0)
  5798. new (insertPos++) ElementType (newElement);
  5799. }
  5800. }
  5801. /** Inserts an array of values into this array at a given position.
  5802. If the index is less than 0 or greater than the size of the array, the
  5803. new elements will be added to the end of the array.
  5804. Otherwise, they will be inserted into the array, moving all the later elements
  5805. along to make room.
  5806. @param indexToInsertAt the index at which the first new element should be inserted
  5807. @param newElements the new values to add to the array
  5808. @param numberOfElements how many items are in the array
  5809. @see insert, add, addSorted, set
  5810. */
  5811. void insertArray (int indexToInsertAt,
  5812. const ElementType* newElements,
  5813. int numberOfElements)
  5814. {
  5815. if (numberOfElements > 0)
  5816. {
  5817. const ScopedLockType lock (getLock());
  5818. data.ensureAllocatedSize (numUsed + numberOfElements);
  5819. ElementType* insertPos;
  5820. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5821. {
  5822. insertPos = data.elements + indexToInsertAt;
  5823. const int numberToMove = numUsed - indexToInsertAt;
  5824. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5825. }
  5826. else
  5827. {
  5828. insertPos = data.elements + numUsed;
  5829. }
  5830. numUsed += numberOfElements;
  5831. while (--numberOfElements >= 0)
  5832. new (insertPos++) ElementType (*newElements++);
  5833. }
  5834. }
  5835. /** Appends a new element at the end of the array as long as the array doesn't
  5836. already contain it.
  5837. If the array already contains an element that matches the one passed in, nothing
  5838. will be done.
  5839. @param newElement the new object to add to the array
  5840. */
  5841. void addIfNotAlreadyThere (ParameterType newElement)
  5842. {
  5843. const ScopedLockType lock (getLock());
  5844. if (! contains (newElement))
  5845. add (newElement);
  5846. }
  5847. /** Replaces an element with a new value.
  5848. If the index is less than zero, this method does nothing.
  5849. If the index is beyond the end of the array, the item is added to the end of the array.
  5850. @param indexToChange the index whose value you want to change
  5851. @param newValue the new value to set for this index.
  5852. @see add, insert
  5853. */
  5854. void set (const int indexToChange, ParameterType newValue)
  5855. {
  5856. jassert (indexToChange >= 0);
  5857. const ScopedLockType lock (getLock());
  5858. if (isPositiveAndBelow (indexToChange, numUsed))
  5859. {
  5860. data.elements [indexToChange] = newValue;
  5861. }
  5862. else if (indexToChange >= 0)
  5863. {
  5864. data.ensureAllocatedSize (numUsed + 1);
  5865. new (data.elements + numUsed++) ElementType (newValue);
  5866. }
  5867. }
  5868. /** Replaces an element with a new value without doing any bounds-checking.
  5869. This just sets a value directly in the array's internal storage, so you'd
  5870. better make sure it's in range!
  5871. @param indexToChange the index whose value you want to change
  5872. @param newValue the new value to set for this index.
  5873. @see set, getUnchecked
  5874. */
  5875. void setUnchecked (const int indexToChange, ParameterType newValue)
  5876. {
  5877. const ScopedLockType lock (getLock());
  5878. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5879. data.elements [indexToChange] = newValue;
  5880. }
  5881. /** Adds elements from an array to the end of this array.
  5882. @param elementsToAdd the array of elements to add
  5883. @param numElementsToAdd how many elements are in this other array
  5884. @see add
  5885. */
  5886. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5887. {
  5888. const ScopedLockType lock (getLock());
  5889. if (numElementsToAdd > 0)
  5890. {
  5891. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5892. while (--numElementsToAdd >= 0)
  5893. {
  5894. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5895. ++numUsed;
  5896. }
  5897. }
  5898. }
  5899. /** This swaps the contents of this array with those of another array.
  5900. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5901. because it just swaps their internal pointers.
  5902. */
  5903. void swapWithArray (Array& otherArray) throw()
  5904. {
  5905. const ScopedLockType lock1 (getLock());
  5906. const ScopedLockType lock2 (otherArray.getLock());
  5907. data.swapWith (otherArray.data);
  5908. swapVariables (numUsed, otherArray.numUsed);
  5909. }
  5910. /** Adds elements from another array to the end of this array.
  5911. @param arrayToAddFrom the array from which to copy the elements
  5912. @param startIndex the first element of the other array to start copying from
  5913. @param numElementsToAdd how many elements to add from the other array. If this
  5914. value is negative or greater than the number of available elements,
  5915. all available elements will be copied.
  5916. @see add
  5917. */
  5918. template <class OtherArrayType>
  5919. void addArray (const OtherArrayType& arrayToAddFrom,
  5920. int startIndex = 0,
  5921. int numElementsToAdd = -1)
  5922. {
  5923. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5924. {
  5925. const ScopedLockType lock2 (getLock());
  5926. if (startIndex < 0)
  5927. {
  5928. jassertfalse;
  5929. startIndex = 0;
  5930. }
  5931. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5932. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5933. while (--numElementsToAdd >= 0)
  5934. add (arrayToAddFrom.getUnchecked (startIndex++));
  5935. }
  5936. }
  5937. /** Inserts a new element into the array, assuming that the array is sorted.
  5938. This will use a comparator to find the position at which the new element
  5939. should go. If the array isn't sorted, the behaviour of this
  5940. method will be unpredictable.
  5941. @param comparator the comparator to use to compare the elements - see the sort()
  5942. method for details about the form this object should take
  5943. @param newElement the new element to insert to the array
  5944. @returns the index at which the new item was added
  5945. @see addUsingDefaultSort, add, sort
  5946. */
  5947. template <class ElementComparator>
  5948. int addSorted (ElementComparator& comparator, ParameterType newElement)
  5949. {
  5950. const ScopedLockType lock (getLock());
  5951. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed);
  5952. insert (index, newElement);
  5953. return index;
  5954. }
  5955. /** Inserts a new element into the array, assuming that the array is sorted.
  5956. This will use the DefaultElementComparator class for sorting, so your ElementType
  5957. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  5958. method will be unpredictable.
  5959. @param newElement the new element to insert to the array
  5960. @see addSorted, sort
  5961. */
  5962. void addUsingDefaultSort (ParameterType newElement)
  5963. {
  5964. DefaultElementComparator <ElementType> comparator;
  5965. addSorted (comparator, newElement);
  5966. }
  5967. /** Finds the index of an element in the array, assuming that the array is sorted.
  5968. This will use a comparator to do a binary-chop to find the index of the given
  5969. element, if it exists. If the array isn't sorted, the behaviour of this
  5970. method will be unpredictable.
  5971. @param comparator the comparator to use to compare the elements - see the sort()
  5972. method for details about the form this object should take
  5973. @param elementToLookFor the element to search for
  5974. @returns the index of the element, or -1 if it's not found
  5975. @see addSorted, sort
  5976. */
  5977. template <class ElementComparator>
  5978. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  5979. {
  5980. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5981. // avoids getting warning messages about the parameter being unused
  5982. const ScopedLockType lock (getLock());
  5983. int start = 0;
  5984. int end = numUsed;
  5985. for (;;)
  5986. {
  5987. if (start >= end)
  5988. {
  5989. return -1;
  5990. }
  5991. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  5992. {
  5993. return start;
  5994. }
  5995. else
  5996. {
  5997. const int halfway = (start + end) >> 1;
  5998. if (halfway == start)
  5999. return -1;
  6000. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  6001. start = halfway;
  6002. else
  6003. end = halfway;
  6004. }
  6005. }
  6006. }
  6007. /** Removes an element from the array.
  6008. This will remove the element at a given index, and move back
  6009. all the subsequent elements to close the gap.
  6010. If the index passed in is out-of-range, nothing will happen.
  6011. @param indexToRemove the index of the element to remove
  6012. @returns the element that has been removed
  6013. @see removeValue, removeRange
  6014. */
  6015. ElementType remove (const int indexToRemove)
  6016. {
  6017. const ScopedLockType lock (getLock());
  6018. if (isPositiveAndBelow (indexToRemove, numUsed))
  6019. {
  6020. --numUsed;
  6021. ElementType* const e = data.elements + indexToRemove;
  6022. ElementType removed (*e);
  6023. e->~ElementType();
  6024. const int numberToShift = numUsed - indexToRemove;
  6025. if (numberToShift > 0)
  6026. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  6027. if ((numUsed << 1) < data.numAllocated)
  6028. minimiseStorageOverheads();
  6029. return removed;
  6030. }
  6031. else
  6032. {
  6033. return ElementType();
  6034. }
  6035. }
  6036. /** Removes an item from the array.
  6037. This will remove the first occurrence of the given element from the array.
  6038. If the item isn't found, no action is taken.
  6039. @param valueToRemove the object to try to remove
  6040. @see remove, removeRange
  6041. */
  6042. void removeValue (ParameterType valueToRemove)
  6043. {
  6044. const ScopedLockType lock (getLock());
  6045. ElementType* const e = data.elements;
  6046. for (int i = 0; i < numUsed; ++i)
  6047. {
  6048. if (valueToRemove == e[i])
  6049. {
  6050. remove (i);
  6051. break;
  6052. }
  6053. }
  6054. }
  6055. /** Removes a range of elements from the array.
  6056. This will remove a set of elements, starting from the given index,
  6057. and move subsequent elements down to close the gap.
  6058. If the range extends beyond the bounds of the array, it will
  6059. be safely clipped to the size of the array.
  6060. @param startIndex the index of the first element to remove
  6061. @param numberToRemove how many elements should be removed
  6062. @see remove, removeValue
  6063. */
  6064. void removeRange (int startIndex, int numberToRemove)
  6065. {
  6066. const ScopedLockType lock (getLock());
  6067. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  6068. startIndex = jlimit (0, numUsed, startIndex);
  6069. if (endIndex > startIndex)
  6070. {
  6071. ElementType* const e = data.elements + startIndex;
  6072. numberToRemove = endIndex - startIndex;
  6073. for (int i = 0; i < numberToRemove; ++i)
  6074. e[i].~ElementType();
  6075. const int numToShift = numUsed - endIndex;
  6076. if (numToShift > 0)
  6077. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  6078. numUsed -= numberToRemove;
  6079. if ((numUsed << 1) < data.numAllocated)
  6080. minimiseStorageOverheads();
  6081. }
  6082. }
  6083. /** Removes the last n elements from the array.
  6084. @param howManyToRemove how many elements to remove from the end of the array
  6085. @see remove, removeValue, removeRange
  6086. */
  6087. void removeLast (int howManyToRemove = 1)
  6088. {
  6089. const ScopedLockType lock (getLock());
  6090. if (howManyToRemove > numUsed)
  6091. howManyToRemove = numUsed;
  6092. for (int i = 1; i <= howManyToRemove; ++i)
  6093. data.elements [numUsed - i].~ElementType();
  6094. numUsed -= howManyToRemove;
  6095. if ((numUsed << 1) < data.numAllocated)
  6096. minimiseStorageOverheads();
  6097. }
  6098. /** Removes any elements which are also in another array.
  6099. @param otherArray the other array in which to look for elements to remove
  6100. @see removeValuesNotIn, remove, removeValue, removeRange
  6101. */
  6102. template <class OtherArrayType>
  6103. void removeValuesIn (const OtherArrayType& otherArray)
  6104. {
  6105. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6106. const ScopedLockType lock2 (getLock());
  6107. if (this == &otherArray)
  6108. {
  6109. clear();
  6110. }
  6111. else
  6112. {
  6113. if (otherArray.size() > 0)
  6114. {
  6115. for (int i = numUsed; --i >= 0;)
  6116. if (otherArray.contains (data.elements [i]))
  6117. remove (i);
  6118. }
  6119. }
  6120. }
  6121. /** Removes any elements which are not found in another array.
  6122. Only elements which occur in this other array will be retained.
  6123. @param otherArray the array in which to look for elements NOT to remove
  6124. @see removeValuesIn, remove, removeValue, removeRange
  6125. */
  6126. template <class OtherArrayType>
  6127. void removeValuesNotIn (const OtherArrayType& otherArray)
  6128. {
  6129. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  6130. const ScopedLockType lock2 (getLock());
  6131. if (this != &otherArray)
  6132. {
  6133. if (otherArray.size() <= 0)
  6134. {
  6135. clear();
  6136. }
  6137. else
  6138. {
  6139. for (int i = numUsed; --i >= 0;)
  6140. if (! otherArray.contains (data.elements [i]))
  6141. remove (i);
  6142. }
  6143. }
  6144. }
  6145. /** Swaps over two elements in the array.
  6146. This swaps over the elements found at the two indexes passed in.
  6147. If either index is out-of-range, this method will do nothing.
  6148. @param index1 index of one of the elements to swap
  6149. @param index2 index of the other element to swap
  6150. */
  6151. void swap (const int index1,
  6152. const int index2)
  6153. {
  6154. const ScopedLockType lock (getLock());
  6155. if (isPositiveAndBelow (index1, numUsed)
  6156. && isPositiveAndBelow (index2, numUsed))
  6157. {
  6158. swapVariables (data.elements [index1],
  6159. data.elements [index2]);
  6160. }
  6161. }
  6162. /** Moves one of the values to a different position.
  6163. This will move the value to a specified index, shuffling along
  6164. any intervening elements as required.
  6165. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  6166. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  6167. @param currentIndex the index of the value to be moved. If this isn't a
  6168. valid index, then nothing will be done
  6169. @param newIndex the index at which you'd like this value to end up. If this
  6170. is less than zero, the value will be moved to the end
  6171. of the array
  6172. */
  6173. void move (const int currentIndex, int newIndex) throw()
  6174. {
  6175. if (currentIndex != newIndex)
  6176. {
  6177. const ScopedLockType lock (getLock());
  6178. if (isPositiveAndBelow (currentIndex, numUsed))
  6179. {
  6180. if (! isPositiveAndBelow (newIndex, numUsed))
  6181. newIndex = numUsed - 1;
  6182. char tempCopy [sizeof (ElementType)];
  6183. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  6184. if (newIndex > currentIndex)
  6185. {
  6186. memmove (data.elements + currentIndex,
  6187. data.elements + currentIndex + 1,
  6188. (newIndex - currentIndex) * sizeof (ElementType));
  6189. }
  6190. else
  6191. {
  6192. memmove (data.elements + newIndex + 1,
  6193. data.elements + newIndex,
  6194. (currentIndex - newIndex) * sizeof (ElementType));
  6195. }
  6196. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  6197. }
  6198. }
  6199. }
  6200. /** Reduces the amount of storage being used by the array.
  6201. Arrays typically allocate slightly more storage than they need, and after
  6202. removing elements, they may have quite a lot of unused space allocated.
  6203. This method will reduce the amount of allocated storage to a minimum.
  6204. */
  6205. void minimiseStorageOverheads()
  6206. {
  6207. const ScopedLockType lock (getLock());
  6208. data.shrinkToNoMoreThan (numUsed);
  6209. }
  6210. /** Increases the array's internal storage to hold a minimum number of elements.
  6211. Calling this before adding a large known number of elements means that
  6212. the array won't have to keep dynamically resizing itself as the elements
  6213. are added, and it'll therefore be more efficient.
  6214. */
  6215. void ensureStorageAllocated (const int minNumElements)
  6216. {
  6217. const ScopedLockType lock (getLock());
  6218. data.ensureAllocatedSize (minNumElements);
  6219. }
  6220. /** Sorts the elements in the array.
  6221. This will use a comparator object to sort the elements into order. The object
  6222. passed must have a method of the form:
  6223. @code
  6224. int compareElements (ElementType first, ElementType second);
  6225. @endcode
  6226. ..and this method must return:
  6227. - a value of < 0 if the first comes before the second
  6228. - a value of 0 if the two objects are equivalent
  6229. - a value of > 0 if the second comes before the first
  6230. To improve performance, the compareElements() method can be declared as static or const.
  6231. @param comparator the comparator to use for comparing elements.
  6232. @param retainOrderOfEquivalentItems if this is true, then items
  6233. which the comparator says are equivalent will be
  6234. kept in the order in which they currently appear
  6235. in the array. This is slower to perform, but may
  6236. be important in some cases. If it's false, a faster
  6237. algorithm is used, but equivalent elements may be
  6238. rearranged.
  6239. @see addSorted, indexOfSorted, sortArray
  6240. */
  6241. template <class ElementComparator>
  6242. void sort (ElementComparator& comparator,
  6243. const bool retainOrderOfEquivalentItems = false) const
  6244. {
  6245. const ScopedLockType lock (getLock());
  6246. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6247. // avoids getting warning messages about the parameter being unused
  6248. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6249. }
  6250. /** Returns the CriticalSection that locks this array.
  6251. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6252. an object of ScopedLockType as an RAII lock for it.
  6253. */
  6254. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  6255. /** Returns the type of scoped lock to use for locking this array */
  6256. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6257. private:
  6258. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  6259. int numUsed;
  6260. };
  6261. #endif // __JUCE_ARRAY_JUCEHEADER__
  6262. /*** End of inlined file: juce_Array.h ***/
  6263. #endif
  6264. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6265. #endif
  6266. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6267. /*** Start of inlined file: juce_DynamicObject.h ***/
  6268. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6269. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6270. /*** Start of inlined file: juce_NamedValueSet.h ***/
  6271. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  6272. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  6273. /*** Start of inlined file: juce_Variant.h ***/
  6274. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6275. #define __JUCE_VARIANT_JUCEHEADER__
  6276. /*** Start of inlined file: juce_Identifier.h ***/
  6277. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  6278. #define __JUCE_IDENTIFIER_JUCEHEADER__
  6279. /*** Start of inlined file: juce_StringPool.h ***/
  6280. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  6281. #define __JUCE_STRINGPOOL_JUCEHEADER__
  6282. /**
  6283. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  6284. comparison speed when dealing with many duplicate strings.
  6285. When you add a string to a pool using getPooledString, it'll return a character
  6286. array containing the same string. This array is owned by the pool, and the same array
  6287. is returned every time a matching string is asked for. This means that it's trivial to
  6288. compare two pooled strings for equality, as you can simply compare their pointers. It
  6289. also cuts down on storage if you're using many copies of the same string.
  6290. */
  6291. class JUCE_API StringPool
  6292. {
  6293. public:
  6294. /** Creates an empty pool. */
  6295. StringPool() throw();
  6296. /** Destructor */
  6297. ~StringPool();
  6298. /** Returns a pointer to a copy of the string that is passed in.
  6299. The pool will always return the same pointer when asked for a string that matches it.
  6300. The pool will own all the pointers that it returns, deleting them when the pool itself
  6301. is deleted.
  6302. */
  6303. const String::CharPointerType getPooledString (const String& original);
  6304. /** Returns a pointer to a copy of the string that is passed in.
  6305. The pool will always return the same pointer when asked for a string that matches it.
  6306. The pool will own all the pointers that it returns, deleting them when the pool itself
  6307. is deleted.
  6308. */
  6309. const String::CharPointerType getPooledString (const char* original);
  6310. /** Returns a pointer to a copy of the string that is passed in.
  6311. The pool will always return the same pointer when asked for a string that matches it.
  6312. The pool will own all the pointers that it returns, deleting them when the pool itself
  6313. is deleted.
  6314. */
  6315. const String::CharPointerType getPooledString (const wchar_t* original);
  6316. /** Returns the number of strings in the pool. */
  6317. int size() const throw();
  6318. /** Returns one of the strings in the pool, by index. */
  6319. const String::CharPointerType operator[] (int index) const throw();
  6320. private:
  6321. Array <String> strings;
  6322. };
  6323. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  6324. /*** End of inlined file: juce_StringPool.h ***/
  6325. /**
  6326. Represents a string identifier, designed for accessing properties by name.
  6327. Identifier objects are very light and fast to copy, but slower to initialise
  6328. from a string, so it's much faster to keep a static identifier object to refer
  6329. to frequently-used names, rather than constructing them each time you need it.
  6330. @see NamedPropertySet, ValueTree
  6331. */
  6332. class JUCE_API Identifier
  6333. {
  6334. public:
  6335. /** Creates a null identifier. */
  6336. Identifier() throw();
  6337. /** Creates an identifier with a specified name.
  6338. Because this name may need to be used in contexts such as script variables or XML
  6339. tags, it must only contain ascii letters and digits, or the underscore character.
  6340. */
  6341. Identifier (const char* name);
  6342. /** Creates an identifier with a specified name.
  6343. Because this name may need to be used in contexts such as script variables or XML
  6344. tags, it must only contain ascii letters and digits, or the underscore character.
  6345. */
  6346. Identifier (const String& name);
  6347. /** Creates a copy of another identifier. */
  6348. Identifier (const Identifier& other) throw();
  6349. /** Creates a copy of another identifier. */
  6350. Identifier& operator= (const Identifier& other) throw();
  6351. /** Destructor */
  6352. ~Identifier();
  6353. /** Compares two identifiers. This is a very fast operation. */
  6354. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  6355. /** Compares two identifiers. This is a very fast operation. */
  6356. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  6357. /** Returns this identifier as a string. */
  6358. const String toString() const { return name; }
  6359. /** Returns this identifier's raw string pointer. */
  6360. operator const String::CharPointerType() const throw() { return name; }
  6361. private:
  6362. String::CharPointerType name;
  6363. static StringPool& getPool();
  6364. };
  6365. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  6366. /*** End of inlined file: juce_Identifier.h ***/
  6367. /*** Start of inlined file: juce_OutputStream.h ***/
  6368. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6369. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6370. /*** Start of inlined file: juce_NewLine.h ***/
  6371. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  6372. #define __JUCE_NEWLINE_JUCEHEADER__
  6373. /** This class is used for represent a new-line character sequence.
  6374. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  6375. @code
  6376. myOutputStream << "Hello World" << newLine << newLine;
  6377. @endcode
  6378. The exact character sequence that will be used for the new-line can be set and
  6379. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  6380. */
  6381. class JUCE_API NewLine
  6382. {
  6383. public:
  6384. /** Returns the default new-line sequence that the library uses.
  6385. @see OutputStream::setNewLineString()
  6386. */
  6387. static const char* getDefault() throw() { return "\r\n"; }
  6388. /** Returns the default new-line sequence that the library uses.
  6389. @see getDefault()
  6390. */
  6391. operator const String() const { return getDefault(); }
  6392. };
  6393. /** An predefined object representing a new-line, which can be written to a string or stream.
  6394. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6395. @code
  6396. myOutputStream << "Hello World" << newLine << newLine;
  6397. @endcode
  6398. */
  6399. extern NewLine newLine;
  6400. /** Writes a new-line sequence to a string.
  6401. You can use the predefined object 'newLine' to invoke this, e.g.
  6402. @code
  6403. myString << "Hello World" << newLine << newLine;
  6404. @endcode
  6405. */
  6406. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6407. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6408. /*** End of inlined file: juce_NewLine.h ***/
  6409. /*** Start of inlined file: juce_InputStream.h ***/
  6410. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6411. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6412. /*** Start of inlined file: juce_MemoryBlock.h ***/
  6413. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6414. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  6415. /**
  6416. A class to hold a resizable block of raw data.
  6417. */
  6418. class JUCE_API MemoryBlock
  6419. {
  6420. public:
  6421. /** Create an uninitialised block with 0 size. */
  6422. MemoryBlock() throw();
  6423. /** Creates a memory block with a given initial size.
  6424. @param initialSize the size of block to create
  6425. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  6426. */
  6427. MemoryBlock (const size_t initialSize,
  6428. bool initialiseToZero = false);
  6429. /** Creates a copy of another memory block. */
  6430. MemoryBlock (const MemoryBlock& other);
  6431. /** Creates a memory block using a copy of a block of data.
  6432. @param dataToInitialiseFrom some data to copy into this block
  6433. @param sizeInBytes how much space to use
  6434. */
  6435. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  6436. /** Destructor. */
  6437. ~MemoryBlock() throw();
  6438. /** Copies another memory block onto this one.
  6439. This block will be resized and copied to exactly match the other one.
  6440. */
  6441. MemoryBlock& operator= (const MemoryBlock& other);
  6442. /** Compares two memory blocks.
  6443. @returns true only if the two blocks are the same size and have identical contents.
  6444. */
  6445. bool operator== (const MemoryBlock& other) const throw();
  6446. /** Compares two memory blocks.
  6447. @returns true if the two blocks are different sizes or have different contents.
  6448. */
  6449. bool operator!= (const MemoryBlock& other) const throw();
  6450. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  6451. */
  6452. bool matches (const void* data, size_t dataSize) const throw();
  6453. /** Returns a void pointer to the data.
  6454. Note that the pointer returned will probably become invalid when the
  6455. block is resized.
  6456. */
  6457. void* getData() const throw() { return data; }
  6458. /** Returns a byte from the memory block.
  6459. This returns a reference, so you can also use it to set a byte.
  6460. */
  6461. template <typename Type>
  6462. char& operator[] (const Type offset) const throw() { return data [offset]; }
  6463. /** Returns the block's current allocated size, in bytes. */
  6464. size_t getSize() const throw() { return size; }
  6465. /** Resizes the memory block.
  6466. This will try to keep as much of the block's current content as it can,
  6467. and can optionally be made to clear any new space that gets allocated at
  6468. the end of the block.
  6469. @param newSize the new desired size for the block
  6470. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6471. whether to clear the new section or just leave it
  6472. uninitialised
  6473. @see ensureSize
  6474. */
  6475. void setSize (const size_t newSize,
  6476. bool initialiseNewSpaceToZero = false);
  6477. /** Increases the block's size only if it's smaller than a given size.
  6478. @param minimumSize if the block is already bigger than this size, no action
  6479. will be taken; otherwise it will be increased to this size
  6480. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6481. whether to clear the new section or just leave it
  6482. uninitialised
  6483. @see setSize
  6484. */
  6485. void ensureSize (const size_t minimumSize,
  6486. bool initialiseNewSpaceToZero = false);
  6487. /** Fills the entire memory block with a repeated byte value.
  6488. This is handy for clearing a block of memory to zero.
  6489. */
  6490. void fillWith (uint8 valueToUse) throw();
  6491. /** Adds another block of data to the end of this one.
  6492. This block's size will be increased accordingly.
  6493. */
  6494. void append (const void* data, size_t numBytes);
  6495. /** Exchanges the contents of this and another memory block.
  6496. No actual copying is required for this, so it's very fast.
  6497. */
  6498. void swapWith (MemoryBlock& other) throw();
  6499. /** Copies data into this MemoryBlock from a memory address.
  6500. @param srcData the memory location of the data to copy into this block
  6501. @param destinationOffset the offset in this block at which the data being copied should begin
  6502. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  6503. it will be clipped so not to do anything nasty)
  6504. */
  6505. void copyFrom (const void* srcData,
  6506. int destinationOffset,
  6507. size_t numBytes) throw();
  6508. /** Copies data from this MemoryBlock to a memory address.
  6509. @param destData the memory location to write to
  6510. @param sourceOffset the offset within this block from which the copied data will be read
  6511. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  6512. zeros will be used for that portion of the data)
  6513. */
  6514. void copyTo (void* destData,
  6515. int sourceOffset,
  6516. size_t numBytes) const throw();
  6517. /** Chops out a section of the block.
  6518. This will remove a section of the memory block and close the gap around it,
  6519. shifting any subsequent data downwards and reducing the size of the block.
  6520. If the range specified goes beyond the size of the block, it will be clipped.
  6521. */
  6522. void removeSection (size_t startByte, size_t numBytesToRemove);
  6523. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  6524. characters in the system's default encoding. */
  6525. const String toString() const;
  6526. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  6527. The block will be resized to the number of valid bytes read from the string.
  6528. Non-hex characters in the string will be ignored.
  6529. @see String::toHexString()
  6530. */
  6531. void loadFromHexString (const String& sourceHexString);
  6532. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  6533. void setBitRange (size_t bitRangeStart,
  6534. size_t numBits,
  6535. int binaryNumberToApply) throw();
  6536. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  6537. int getBitRange (size_t bitRangeStart,
  6538. size_t numBitsToRead) const throw();
  6539. /** Returns a string of characters that represent the binary contents of this block.
  6540. Uses a 64-bit encoding system to allow binary data to be turned into a string
  6541. of simple non-extended characters, e.g. for storage in XML.
  6542. @see fromBase64Encoding
  6543. */
  6544. const String toBase64Encoding() const;
  6545. /** Takes a string of encoded characters and turns it into binary data.
  6546. The string passed in must have been created by to64BitEncoding(), and this
  6547. block will be resized to recreate the original data block.
  6548. @see toBase64Encoding
  6549. */
  6550. bool fromBase64Encoding (const String& encodedString);
  6551. private:
  6552. HeapBlock <char> data;
  6553. size_t size;
  6554. static const char* const encodingTable;
  6555. JUCE_LEAK_DETECTOR (MemoryBlock);
  6556. };
  6557. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  6558. /*** End of inlined file: juce_MemoryBlock.h ***/
  6559. /** The base class for streams that read data.
  6560. Input and output streams are used throughout the library - subclasses can override
  6561. some or all of the virtual functions to implement their behaviour.
  6562. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6563. */
  6564. class JUCE_API InputStream
  6565. {
  6566. public:
  6567. /** Destructor. */
  6568. virtual ~InputStream() {}
  6569. /** Returns the total number of bytes available for reading in this stream.
  6570. Note that this is the number of bytes available from the start of the
  6571. stream, not from the current position.
  6572. If the size of the stream isn't actually known, this may return -1.
  6573. */
  6574. virtual int64 getTotalLength() = 0;
  6575. /** Returns true if the stream has no more data to read. */
  6576. virtual bool isExhausted() = 0;
  6577. /** Reads a set of bytes from the stream into a memory buffer.
  6578. This is the only read method that subclasses actually need to implement, as the
  6579. InputStream base class implements the other read methods in terms of this one (although
  6580. it's often more efficient for subclasses to implement them directly).
  6581. @param destBuffer the destination buffer for the data
  6582. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6583. memory block passed in is big enough to contain this
  6584. many bytes.
  6585. @returns the actual number of bytes that were read, which may be less than
  6586. maxBytesToRead if the stream is exhausted before it gets that far
  6587. */
  6588. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6589. /** Reads a byte from the stream.
  6590. If the stream is exhausted, this will return zero.
  6591. @see OutputStream::writeByte
  6592. */
  6593. virtual char readByte();
  6594. /** Reads a boolean from the stream.
  6595. The bool is encoded as a single byte - 1 for true, 0 for false.
  6596. If the stream is exhausted, this will return false.
  6597. @see OutputStream::writeBool
  6598. */
  6599. virtual bool readBool();
  6600. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6601. If the next two bytes read are byte1 and byte2, this returns
  6602. (byte1 | (byte2 << 8)).
  6603. If the stream is exhausted partway through reading the bytes, this will return zero.
  6604. @see OutputStream::writeShort, readShortBigEndian
  6605. */
  6606. virtual short readShort();
  6607. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6608. If the next two bytes read are byte1 and byte2, this returns
  6609. (byte2 | (byte1 << 8)).
  6610. If the stream is exhausted partway through reading the bytes, this will return zero.
  6611. @see OutputStream::writeShortBigEndian, readShort
  6612. */
  6613. virtual short readShortBigEndian();
  6614. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6615. If the next four bytes are byte1 to byte4, this returns
  6616. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6617. If the stream is exhausted partway through reading the bytes, this will return zero.
  6618. @see OutputStream::writeInt, readIntBigEndian
  6619. */
  6620. virtual int readInt();
  6621. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6622. If the next four bytes are byte1 to byte4, this returns
  6623. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6624. If the stream is exhausted partway through reading the bytes, this will return zero.
  6625. @see OutputStream::writeIntBigEndian, readInt
  6626. */
  6627. virtual int readIntBigEndian();
  6628. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6629. If the next eight bytes are byte1 to byte8, this returns
  6630. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6631. If the stream is exhausted partway through reading the bytes, this will return zero.
  6632. @see OutputStream::writeInt64, readInt64BigEndian
  6633. */
  6634. virtual int64 readInt64();
  6635. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6636. If the next eight bytes are byte1 to byte8, this returns
  6637. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6638. If the stream is exhausted partway through reading the bytes, this will return zero.
  6639. @see OutputStream::writeInt64BigEndian, readInt64
  6640. */
  6641. virtual int64 readInt64BigEndian();
  6642. /** Reads four bytes as a 32-bit floating point value.
  6643. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6644. If the stream is exhausted partway through reading the bytes, this will return zero.
  6645. @see OutputStream::writeFloat, readDouble
  6646. */
  6647. virtual float readFloat();
  6648. /** Reads four bytes as a 32-bit floating point value.
  6649. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6650. If the stream is exhausted partway through reading the bytes, this will return zero.
  6651. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6652. */
  6653. virtual float readFloatBigEndian();
  6654. /** Reads eight bytes as a 64-bit floating point value.
  6655. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6656. If the stream is exhausted partway through reading the bytes, this will return zero.
  6657. @see OutputStream::writeDouble, readFloat
  6658. */
  6659. virtual double readDouble();
  6660. /** Reads eight bytes as a 64-bit floating point value.
  6661. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6662. If the stream is exhausted partway through reading the bytes, this will return zero.
  6663. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6664. */
  6665. virtual double readDoubleBigEndian();
  6666. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6667. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6668. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6669. @see OutputStream::writeCompressedInt()
  6670. */
  6671. virtual int readCompressedInt();
  6672. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6673. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6674. After this call, the stream's position will be left pointing to the next character
  6675. following the line-feed, but the linefeeds aren't included in the string that
  6676. is returned.
  6677. */
  6678. virtual const String readNextLine();
  6679. /** Reads a zero-terminated UTF8 string from the stream.
  6680. This will read characters from the stream until it hits a zero character or
  6681. end-of-stream.
  6682. @see OutputStream::writeString, readEntireStreamAsString
  6683. */
  6684. virtual const String readString();
  6685. /** Tries to read the whole stream and turn it into a string.
  6686. This will read from the stream's current position until the end-of-stream, and
  6687. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6688. */
  6689. virtual const String readEntireStreamAsString();
  6690. /** Reads from the stream and appends the data to a MemoryBlock.
  6691. @param destBlock the block to append the data onto
  6692. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6693. of bytes that will be read - if it's negative, data
  6694. will be read until the stream is exhausted.
  6695. @returns the number of bytes that were added to the memory block
  6696. */
  6697. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6698. int maxNumBytesToRead = -1);
  6699. /** Returns the offset of the next byte that will be read from the stream.
  6700. @see setPosition
  6701. */
  6702. virtual int64 getPosition() = 0;
  6703. /** Tries to move the current read position of the stream.
  6704. The position is an absolute number of bytes from the stream's start.
  6705. Some streams might not be able to do this, in which case they should do
  6706. nothing and return false. Others might be able to manage it by resetting
  6707. themselves and skipping to the correct position, although this is
  6708. obviously a bit slow.
  6709. @returns true if the stream manages to reposition itself correctly
  6710. @see getPosition
  6711. */
  6712. virtual bool setPosition (int64 newPosition) = 0;
  6713. /** Reads and discards a number of bytes from the stream.
  6714. Some input streams might implement this efficiently, but the base
  6715. class will just keep reading data until the requisite number of bytes
  6716. have been done.
  6717. */
  6718. virtual void skipNextBytes (int64 numBytesToSkip);
  6719. protected:
  6720. InputStream() throw() {}
  6721. private:
  6722. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6723. };
  6724. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6725. /*** End of inlined file: juce_InputStream.h ***/
  6726. class File;
  6727. /**
  6728. The base class for streams that write data to some kind of destination.
  6729. Input and output streams are used throughout the library - subclasses can override
  6730. some or all of the virtual functions to implement their behaviour.
  6731. @see InputStream, MemoryOutputStream, FileOutputStream
  6732. */
  6733. class JUCE_API OutputStream
  6734. {
  6735. protected:
  6736. OutputStream();
  6737. public:
  6738. /** Destructor.
  6739. Some subclasses might want to do things like call flush() during their
  6740. destructors.
  6741. */
  6742. virtual ~OutputStream();
  6743. /** If the stream is using a buffer, this will ensure it gets written
  6744. out to the destination. */
  6745. virtual void flush() = 0;
  6746. /** Tries to move the stream's output position.
  6747. Not all streams will be able to seek to a new position - this will return
  6748. false if it fails to work.
  6749. @see getPosition
  6750. */
  6751. virtual bool setPosition (int64 newPosition) = 0;
  6752. /** Returns the stream's current position.
  6753. @see setPosition
  6754. */
  6755. virtual int64 getPosition() = 0;
  6756. /** Writes a block of data to the stream.
  6757. When creating a subclass of OutputStream, this is the only write method
  6758. that needs to be overloaded - the base class has methods for writing other
  6759. types of data which use this to do the work.
  6760. @returns false if the write operation fails for some reason
  6761. */
  6762. virtual bool write (const void* dataToWrite,
  6763. int howManyBytes) = 0;
  6764. /** Writes a single byte to the stream.
  6765. @see InputStream::readByte
  6766. */
  6767. virtual void writeByte (char byte);
  6768. /** Writes a boolean to the stream as a single byte.
  6769. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6770. @see InputStream::readBool
  6771. */
  6772. virtual void writeBool (bool boolValue);
  6773. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6774. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6775. @see InputStream::readShort
  6776. */
  6777. virtual void writeShort (short value);
  6778. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6779. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6780. @see InputStream::readShortBigEndian
  6781. */
  6782. virtual void writeShortBigEndian (short value);
  6783. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6784. @see InputStream::readInt
  6785. */
  6786. virtual void writeInt (int value);
  6787. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6788. @see InputStream::readIntBigEndian
  6789. */
  6790. virtual void writeIntBigEndian (int value);
  6791. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6792. @see InputStream::readInt64
  6793. */
  6794. virtual void writeInt64 (int64 value);
  6795. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6796. @see InputStream::readInt64BigEndian
  6797. */
  6798. virtual void writeInt64BigEndian (int64 value);
  6799. /** Writes a 32-bit floating point value to the stream in a binary format.
  6800. The binary 32-bit encoding of the float is written as a little-endian int.
  6801. @see InputStream::readFloat
  6802. */
  6803. virtual void writeFloat (float value);
  6804. /** Writes a 32-bit floating point value to the stream in a binary format.
  6805. The binary 32-bit encoding of the float is written as a big-endian int.
  6806. @see InputStream::readFloatBigEndian
  6807. */
  6808. virtual void writeFloatBigEndian (float value);
  6809. /** Writes a 64-bit floating point value to the stream in a binary format.
  6810. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6811. @see InputStream::readDouble
  6812. */
  6813. virtual void writeDouble (double value);
  6814. /** Writes a 64-bit floating point value to the stream in a binary format.
  6815. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6816. @see InputStream::readDoubleBigEndian
  6817. */
  6818. virtual void writeDoubleBigEndian (double value);
  6819. /** Writes a byte to the output stream a given number of times. */
  6820. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6821. /** Writes a condensed binary encoding of a 32-bit integer.
  6822. If you're storing a lot of integers which are unlikely to have very large values,
  6823. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6824. under 0xffff only 3 bytes, etc.
  6825. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6826. @see InputStream::readCompressedInt
  6827. */
  6828. virtual void writeCompressedInt (int value);
  6829. /** Stores a string in the stream in a binary format.
  6830. This isn't the method to use if you're trying to append text to the end of a
  6831. text-file! It's intended for storing a string so that it can be retrieved later
  6832. by InputStream::readString().
  6833. It writes the string to the stream as UTF8, including the null termination character.
  6834. For appending text to a file, instead use writeText, or operator<<
  6835. @see InputStream::readString, writeText, operator<<
  6836. */
  6837. virtual void writeString (const String& text);
  6838. /** Writes a string of text to the stream.
  6839. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6840. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6841. of a file).
  6842. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6843. */
  6844. virtual void writeText (const String& text,
  6845. bool asUTF16,
  6846. bool writeUTF16ByteOrderMark);
  6847. /** Reads data from an input stream and writes it to this stream.
  6848. @param source the stream to read from
  6849. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6850. less than zero, it will keep reading until the input
  6851. is exhausted)
  6852. */
  6853. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6854. /** Sets the string that will be written to the stream when the writeNewLine()
  6855. method is called.
  6856. By default this will be set the the value of NewLine::getDefault().
  6857. */
  6858. void setNewLineString (const String& newLineString);
  6859. /** Returns the current new-line string that was set by setNewLineString(). */
  6860. const String& getNewLineString() const throw() { return newLineString; }
  6861. private:
  6862. String newLineString;
  6863. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6864. };
  6865. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6866. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6867. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6868. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6869. /** Writes a character to a stream. */
  6870. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6871. /** Writes a null-terminated text string to a stream. */
  6872. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6873. /** Writes a block of data from a MemoryBlock to a stream. */
  6874. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6875. /** Writes the contents of a file to a stream. */
  6876. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6877. /** Writes a new-line to a stream.
  6878. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6879. @code
  6880. myOutputStream << "Hello World" << newLine << newLine;
  6881. @endcode
  6882. @see OutputStream::setNewLineString
  6883. */
  6884. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6885. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6886. /*** End of inlined file: juce_OutputStream.h ***/
  6887. #ifndef DOXYGEN
  6888. class DynamicObject;
  6889. #endif
  6890. /**
  6891. A variant class, that can be used to hold a range of primitive values.
  6892. A var object can hold a range of simple primitive values, strings, or
  6893. a reference-counted pointer to a DynamicObject. The var class is intended
  6894. to act like the values used in dynamic scripting languages.
  6895. @see DynamicObject
  6896. */
  6897. class JUCE_API var
  6898. {
  6899. public:
  6900. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6901. typedef Identifier identifier;
  6902. /** Creates a void variant. */
  6903. var() throw();
  6904. /** Destructor. */
  6905. ~var() throw();
  6906. /** A static var object that can be used where you need an empty variant object. */
  6907. static const var null;
  6908. var (const var& valueToCopy);
  6909. var (int value) throw();
  6910. var (int64 value) throw();
  6911. var (bool value) throw();
  6912. var (double value) throw();
  6913. var (const char* value);
  6914. var (const wchar_t* value);
  6915. var (const String& value);
  6916. var (DynamicObject* object);
  6917. var (MethodFunction method) throw();
  6918. var& operator= (const var& valueToCopy);
  6919. var& operator= (int value);
  6920. var& operator= (int64 value);
  6921. var& operator= (bool value);
  6922. var& operator= (double value);
  6923. var& operator= (const char* value);
  6924. var& operator= (const wchar_t* value);
  6925. var& operator= (const String& value);
  6926. var& operator= (DynamicObject* object);
  6927. var& operator= (MethodFunction method);
  6928. void swapWith (var& other) throw();
  6929. operator int() const;
  6930. operator int64() const;
  6931. operator bool() const;
  6932. operator float() const;
  6933. operator double() const;
  6934. operator const String() const;
  6935. const String toString() const;
  6936. DynamicObject* getObject() const;
  6937. bool isVoid() const throw();
  6938. bool isInt() const throw();
  6939. bool isInt64() const throw();
  6940. bool isBool() const throw();
  6941. bool isDouble() const throw();
  6942. bool isString() const throw();
  6943. bool isObject() const throw();
  6944. bool isMethod() const throw();
  6945. /** Writes a binary representation of this value to a stream.
  6946. The data can be read back later using readFromStream().
  6947. */
  6948. void writeToStream (OutputStream& output) const;
  6949. /** Reads back a stored binary representation of a value.
  6950. The data in the stream must have been written using writeToStream(), or this
  6951. will have unpredictable results.
  6952. */
  6953. static const var readFromStream (InputStream& input);
  6954. /** If this variant is an object, this returns one of its properties. */
  6955. const var operator[] (const Identifier& propertyName) const;
  6956. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6957. const var call (const Identifier& method) const;
  6958. /** If this variant is an object, this invokes one of its methods with one argument. */
  6959. const var call (const Identifier& method, const var& arg1) const;
  6960. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6961. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6962. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6963. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6964. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6965. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6966. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6967. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  6968. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  6969. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  6970. /** If this variant is a method pointer, this invokes it on a target object. */
  6971. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  6972. /** Returns true if this var has the same value as the one supplied. */
  6973. bool equals (const var& other) const throw();
  6974. /** Returns true if this var has the same value and type as the one supplied.
  6975. This differs from equals() because e.g. "0" and 0 will be considered different.
  6976. */
  6977. bool equalsWithSameType (const var& other) const throw();
  6978. private:
  6979. class VariantType;
  6980. friend class VariantType;
  6981. class VariantType_Void;
  6982. friend class VariantType_Void;
  6983. class VariantType_Int;
  6984. friend class VariantType_Int;
  6985. class VariantType_Int64;
  6986. friend class VariantType_Int64;
  6987. class VariantType_Double;
  6988. friend class VariantType_Double;
  6989. class VariantType_Float;
  6990. friend class VariantType_Float;
  6991. class VariantType_Bool;
  6992. friend class VariantType_Bool;
  6993. class VariantType_String;
  6994. friend class VariantType_String;
  6995. class VariantType_Object;
  6996. friend class VariantType_Object;
  6997. class VariantType_Method;
  6998. friend class VariantType_Method;
  6999. union ValueUnion
  7000. {
  7001. int intValue;
  7002. int64 int64Value;
  7003. bool boolValue;
  7004. double doubleValue;
  7005. String* stringValue;
  7006. DynamicObject* objectValue;
  7007. MethodFunction methodValue;
  7008. };
  7009. const VariantType* type;
  7010. ValueUnion value;
  7011. };
  7012. bool operator== (const var& v1, const var& v2) throw();
  7013. bool operator!= (const var& v1, const var& v2) throw();
  7014. bool operator== (const var& v1, const String& v2) throw();
  7015. bool operator!= (const var& v1, const String& v2) throw();
  7016. #endif // __JUCE_VARIANT_JUCEHEADER__
  7017. /*** End of inlined file: juce_Variant.h ***/
  7018. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  7019. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7020. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7021. /**
  7022. Helps to manipulate singly-linked lists of objects.
  7023. For objects that are designed to contain a pointer to the subsequent item in the
  7024. list, this class contains methods to deal with the list. To use it, the ObjectType
  7025. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  7026. @code
  7027. struct MyObject
  7028. {
  7029. int x, y, z;
  7030. // A linkable object must contain a member with this name and type, which must be
  7031. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  7032. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  7033. LinkedListPointer<MyObject> nextListItem;
  7034. };
  7035. LinkedListPointer<MyObject> myList;
  7036. myList.append (new MyObject());
  7037. myList.append (new MyObject());
  7038. int numItems = myList.size(); // returns 2
  7039. MyObject* lastInList = myList.getLast();
  7040. @endcode
  7041. */
  7042. template <class ObjectType>
  7043. class LinkedListPointer
  7044. {
  7045. public:
  7046. /** Creates a null pointer to an empty list. */
  7047. LinkedListPointer() throw()
  7048. : item (0)
  7049. {
  7050. }
  7051. /** Creates a pointer to a list whose head is the item provided. */
  7052. explicit LinkedListPointer (ObjectType* const headItem) throw()
  7053. : item (headItem)
  7054. {
  7055. }
  7056. /** Sets this pointer to point to a new list. */
  7057. LinkedListPointer& operator= (ObjectType* const newItem) throw()
  7058. {
  7059. item = newItem;
  7060. return *this;
  7061. }
  7062. /** Returns the item which this pointer points to. */
  7063. inline operator ObjectType*() const throw()
  7064. {
  7065. return item;
  7066. }
  7067. /** Returns the item which this pointer points to. */
  7068. inline ObjectType* get() const throw()
  7069. {
  7070. return item;
  7071. }
  7072. /** Returns the last item in the list which this pointer points to.
  7073. This will iterate the list and return the last item found. Obviously the speed
  7074. of this operation will be proportional to the size of the list. If the list is
  7075. empty the return value will be this object.
  7076. If you're planning on appending a number of items to your list, it's much more
  7077. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  7078. */
  7079. LinkedListPointer& getLast() throw()
  7080. {
  7081. LinkedListPointer* l = this;
  7082. while (l->item != 0)
  7083. l = &(l->item->nextListItem);
  7084. return *l;
  7085. }
  7086. /** Returns the number of items in the list.
  7087. Obviously with a simple linked list, getting the size involves iterating the list, so
  7088. this can be a lengthy operation - be careful when using this method in your code.
  7089. */
  7090. int size() const throw()
  7091. {
  7092. int total = 0;
  7093. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  7094. ++total;
  7095. return total;
  7096. }
  7097. /** Returns the item at a given index in the list.
  7098. Since the only way to find an item is to iterate the list, this operation can obviously
  7099. be slow, depending on its size, so you should be careful when using this in algorithms.
  7100. */
  7101. LinkedListPointer& operator[] (int index) throw()
  7102. {
  7103. LinkedListPointer* l = this;
  7104. while (--index >= 0 && l->item != 0)
  7105. l = &(l->item->nextListItem);
  7106. return *l;
  7107. }
  7108. /** Returns the item at a given index in the list.
  7109. Since the only way to find an item is to iterate the list, this operation can obviously
  7110. be slow, depending on its size, so you should be careful when using this in algorithms.
  7111. */
  7112. const LinkedListPointer& operator[] (int index) const throw()
  7113. {
  7114. const LinkedListPointer* l = this;
  7115. while (--index >= 0 && l->item != 0)
  7116. l = &(l->item->nextListItem);
  7117. return *l;
  7118. }
  7119. /** Returns true if the list contains the given item. */
  7120. bool contains (const ObjectType* const itemToLookFor) const throw()
  7121. {
  7122. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  7123. if (itemToLookFor == i)
  7124. return true;
  7125. return false;
  7126. }
  7127. /** Inserts an item into the list, placing it before the item that this pointer
  7128. currently points to.
  7129. */
  7130. void insertNext (ObjectType* const newItem)
  7131. {
  7132. jassert (newItem != 0);
  7133. jassert (newItem->nextListItem == 0);
  7134. newItem->nextListItem = item;
  7135. item = newItem;
  7136. }
  7137. /** Inserts an item at a numeric index in the list.
  7138. Obviously this will involve iterating the list to find the item at the given index,
  7139. so be careful about the impact this may have on execution time.
  7140. */
  7141. void insertAtIndex (int index, ObjectType* newItem)
  7142. {
  7143. jassert (newItem != 0);
  7144. LinkedListPointer* l = this;
  7145. while (index != 0 && l->item != 0)
  7146. {
  7147. l = &(l->item->nextListItem);
  7148. --index;
  7149. }
  7150. l->insertNext (newItem);
  7151. }
  7152. /** Replaces the object that this pointer points to, appending the rest of the list to
  7153. the new object, and returning the old one.
  7154. */
  7155. ObjectType* replaceNext (ObjectType* const newItem) throw()
  7156. {
  7157. jassert (newItem != 0);
  7158. jassert (newItem->nextListItem == 0);
  7159. ObjectType* const oldItem = item;
  7160. item = newItem;
  7161. item->nextListItem = oldItem->nextListItem.item;
  7162. oldItem->nextListItem = (ObjectType*) 0;
  7163. return oldItem;
  7164. }
  7165. /** Adds an item to the end of the list.
  7166. This operation involves iterating the whole list, so can be slow - if you need to
  7167. append a number of items to your list, it's much more efficient to use the Appender
  7168. class than to repeatedly call append().
  7169. */
  7170. void append (ObjectType* const newItem)
  7171. {
  7172. getLast().item = newItem;
  7173. }
  7174. /** Creates copies of all the items in another list and adds them to this one.
  7175. This will use the ObjectType's copy constructor to try to create copies of each
  7176. item in the other list, and appends them to this list.
  7177. */
  7178. void addCopyOfList (const LinkedListPointer& other)
  7179. {
  7180. LinkedListPointer* insertPoint = this;
  7181. for (ObjectType* i = other.item; i != 0; i = i->nextListItem)
  7182. {
  7183. insertPoint->insertNext (new ObjectType (*i));
  7184. insertPoint = &(insertPoint->item->nextListItem);
  7185. }
  7186. }
  7187. /** Removes the head item from the list.
  7188. This won't delete the object that is removed, but returns it, so the caller can
  7189. delete it if necessary.
  7190. */
  7191. ObjectType* removeNext() throw()
  7192. {
  7193. ObjectType* const oldItem = item;
  7194. if (oldItem != 0)
  7195. {
  7196. item = oldItem->nextListItem;
  7197. oldItem->nextListItem = (ObjectType*) 0;
  7198. }
  7199. return oldItem;
  7200. }
  7201. /** Removes a specific item from the list.
  7202. Note that this will not delete the item, it simply unlinks it from the list.
  7203. */
  7204. void remove (ObjectType* const itemToRemove)
  7205. {
  7206. LinkedListPointer* const l = findPointerTo (itemToRemove);
  7207. if (l != 0)
  7208. l->removeNext();
  7209. }
  7210. /** Iterates the list, calling the delete operator on all of its elements and
  7211. leaving this pointer empty.
  7212. */
  7213. void deleteAll()
  7214. {
  7215. while (item != 0)
  7216. {
  7217. ObjectType* const oldItem = item;
  7218. item = oldItem->nextListItem;
  7219. delete oldItem;
  7220. }
  7221. }
  7222. /** Finds a pointer to a given item.
  7223. If the item is found in the list, this returns the pointer that points to it. If
  7224. the item isn't found, this returns null.
  7225. */
  7226. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) throw()
  7227. {
  7228. LinkedListPointer* l = this;
  7229. while (l->item != 0)
  7230. {
  7231. if (l->item == itemToLookFor)
  7232. return l;
  7233. l = &(l->item->nextListItem);
  7234. }
  7235. return 0;
  7236. }
  7237. /** Copies the items in the list to an array.
  7238. The destArray must contain enough elements to hold the entire list - no checks are
  7239. made for this!
  7240. */
  7241. void copyToArray (ObjectType** destArray) const throw()
  7242. {
  7243. jassert (destArray != 0);
  7244. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  7245. *destArray++ = i;
  7246. }
  7247. /**
  7248. Allows efficient repeated insertions into a list.
  7249. You can create an Appender object which points to the last element in your
  7250. list, and then repeatedly call Appender::append() to add items to the end
  7251. of the list in O(1) time.
  7252. */
  7253. class Appender
  7254. {
  7255. public:
  7256. /** Creates an appender which will add items to the given list.
  7257. */
  7258. Appender (LinkedListPointer& endOfListPointer) throw()
  7259. : endOfList (&endOfListPointer)
  7260. {
  7261. // This can only be used to add to the end of a list.
  7262. jassert (endOfListPointer.item == 0);
  7263. }
  7264. /** Appends an item to the list. */
  7265. void append (ObjectType* const newItem) throw()
  7266. {
  7267. *endOfList = newItem;
  7268. endOfList = &(newItem->nextListItem);
  7269. }
  7270. private:
  7271. LinkedListPointer* endOfList;
  7272. JUCE_DECLARE_NON_COPYABLE (Appender);
  7273. };
  7274. private:
  7275. ObjectType* item;
  7276. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  7277. };
  7278. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7279. /*** End of inlined file: juce_LinkedListPointer.h ***/
  7280. class XmlElement;
  7281. /** Holds a set of named var objects.
  7282. This can be used as a basic structure to hold a set of var object, which can
  7283. be retrieved by using their identifier.
  7284. */
  7285. class JUCE_API NamedValueSet
  7286. {
  7287. public:
  7288. /** Creates an empty set. */
  7289. NamedValueSet() throw();
  7290. /** Creates a copy of another set. */
  7291. NamedValueSet (const NamedValueSet& other);
  7292. /** Replaces this set with a copy of another set. */
  7293. NamedValueSet& operator= (const NamedValueSet& other);
  7294. /** Destructor. */
  7295. ~NamedValueSet();
  7296. bool operator== (const NamedValueSet& other) const;
  7297. bool operator!= (const NamedValueSet& other) const;
  7298. /** Returns the total number of values that the set contains. */
  7299. int size() const throw();
  7300. /** Returns the value of a named item.
  7301. If the name isn't found, this will return a void variant.
  7302. @see getProperty
  7303. */
  7304. const var& operator[] (const Identifier& name) const;
  7305. /** Tries to return the named value, but if no such value is found, this will
  7306. instead return the supplied default value.
  7307. */
  7308. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  7309. /** Changes or adds a named value.
  7310. @returns true if a value was changed or added; false if the
  7311. value was already set the the value passed-in.
  7312. */
  7313. bool set (const Identifier& name, const var& newValue);
  7314. /** Returns true if the set contains an item with the specified name. */
  7315. bool contains (const Identifier& name) const;
  7316. /** Removes a value from the set.
  7317. @returns true if a value was removed; false if there was no value
  7318. with the name that was given.
  7319. */
  7320. bool remove (const Identifier& name);
  7321. /** Returns the name of the value at a given index.
  7322. The index must be between 0 and size() - 1.
  7323. */
  7324. const Identifier getName (int index) const;
  7325. /** Returns the value of the item at a given index.
  7326. The index must be between 0 and size() - 1.
  7327. */
  7328. const var getValueAt (int index) const;
  7329. /** Removes all values. */
  7330. void clear();
  7331. /** Returns a pointer to the var that holds a named value, or null if there is
  7332. no value with this name.
  7333. Do not use this method unless you really need access to the internal var object
  7334. for some reason - for normal reading and writing always prefer operator[]() and set().
  7335. */
  7336. var* getVarPointer (const Identifier& name) const;
  7337. /** Sets properties to the values of all of an XML element's attributes. */
  7338. void setFromXmlAttributes (const XmlElement& xml);
  7339. /** Sets attributes in an XML element corresponding to each of this object's
  7340. properties.
  7341. */
  7342. void copyToXmlAttributes (XmlElement& xml) const;
  7343. private:
  7344. class NamedValue
  7345. {
  7346. public:
  7347. NamedValue() throw();
  7348. NamedValue (const NamedValue&);
  7349. NamedValue (const Identifier& name, const var& value);
  7350. NamedValue& operator= (const NamedValue&);
  7351. bool operator== (const NamedValue& other) const throw();
  7352. LinkedListPointer<NamedValue> nextListItem;
  7353. Identifier name;
  7354. var value;
  7355. private:
  7356. JUCE_LEAK_DETECTOR (NamedValue);
  7357. };
  7358. friend class LinkedListPointer<NamedValue>;
  7359. LinkedListPointer<NamedValue> values;
  7360. };
  7361. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  7362. /*** End of inlined file: juce_NamedValueSet.h ***/
  7363. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  7364. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7365. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7366. /**
  7367. Adds reference-counting to an object.
  7368. To add reference-counting to a class, derive it from this class, and
  7369. use the ReferenceCountedObjectPtr class to point to it.
  7370. e.g. @code
  7371. class MyClass : public ReferenceCountedObject
  7372. {
  7373. void foo();
  7374. // This is a neat way of declaring a typedef for a pointer class,
  7375. // rather than typing out the full templated name each time..
  7376. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7377. };
  7378. MyClass::Ptr p = new MyClass();
  7379. MyClass::Ptr p2 = p;
  7380. p = 0;
  7381. p2->foo();
  7382. @endcode
  7383. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7384. careful not to delete the object manually.
  7385. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7386. */
  7387. class JUCE_API ReferenceCountedObject
  7388. {
  7389. public:
  7390. /** Increments the object's reference count.
  7391. This is done automatically by the smart pointer, but is public just
  7392. in case it's needed for nefarious purposes.
  7393. */
  7394. inline void incReferenceCount() throw()
  7395. {
  7396. ++refCount;
  7397. }
  7398. /** Decreases the object's reference count.
  7399. If the count gets to zero, the object will be deleted.
  7400. */
  7401. inline void decReferenceCount() throw()
  7402. {
  7403. jassert (getReferenceCount() > 0);
  7404. if (--refCount == 0)
  7405. delete this;
  7406. }
  7407. /** Returns the object's current reference count. */
  7408. inline int getReferenceCount() const throw()
  7409. {
  7410. return refCount.get();
  7411. }
  7412. protected:
  7413. /** Creates the reference-counted object (with an initial ref count of zero). */
  7414. ReferenceCountedObject()
  7415. {
  7416. }
  7417. /** Destructor. */
  7418. virtual ~ReferenceCountedObject()
  7419. {
  7420. // it's dangerous to delete an object that's still referenced by something else!
  7421. jassert (getReferenceCount() == 0);
  7422. }
  7423. private:
  7424. Atomic <int> refCount;
  7425. };
  7426. /**
  7427. A smart-pointer class which points to a reference-counted object.
  7428. The template parameter specifies the class of the object you want to point to - the easiest
  7429. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject,
  7430. but if you need to, you could roll your own reference-countable class by implementing a pair of
  7431. mathods called incReferenceCount() and decReferenceCount().
  7432. When using this class, you'll probably want to create a typedef to abbreviate the full
  7433. templated name - e.g.
  7434. @code typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;@endcode
  7435. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7436. */
  7437. template <class ReferenceCountedObjectClass>
  7438. class ReferenceCountedObjectPtr
  7439. {
  7440. public:
  7441. /** Creates a pointer to a null object. */
  7442. inline ReferenceCountedObjectPtr() throw()
  7443. : referencedObject (0)
  7444. {
  7445. }
  7446. /** Creates a pointer to an object.
  7447. This will increment the object's reference-count if it is non-null.
  7448. */
  7449. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7450. : referencedObject (refCountedObject)
  7451. {
  7452. if (refCountedObject != 0)
  7453. refCountedObject->incReferenceCount();
  7454. }
  7455. /** Copies another pointer.
  7456. This will increment the object's reference-count (if it is non-null).
  7457. */
  7458. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7459. : referencedObject (other.referencedObject)
  7460. {
  7461. if (referencedObject != 0)
  7462. referencedObject->incReferenceCount();
  7463. }
  7464. /** Changes this pointer to point at a different object.
  7465. The reference count of the old object is decremented, and it might be
  7466. deleted if it hits zero. The new object's count is incremented.
  7467. */
  7468. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7469. {
  7470. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7471. if (newObject != referencedObject)
  7472. {
  7473. if (newObject != 0)
  7474. newObject->incReferenceCount();
  7475. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7476. referencedObject = newObject;
  7477. if (oldObject != 0)
  7478. oldObject->decReferenceCount();
  7479. }
  7480. return *this;
  7481. }
  7482. /** Changes this pointer to point at a different object.
  7483. The reference count of the old object is decremented, and it might be
  7484. deleted if it hits zero. The new object's count is incremented.
  7485. */
  7486. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7487. {
  7488. if (referencedObject != newObject)
  7489. {
  7490. if (newObject != 0)
  7491. newObject->incReferenceCount();
  7492. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7493. referencedObject = newObject;
  7494. if (oldObject != 0)
  7495. oldObject->decReferenceCount();
  7496. }
  7497. return *this;
  7498. }
  7499. /** Destructor.
  7500. This will decrement the object's reference-count, and may delete it if it
  7501. gets to zero.
  7502. */
  7503. inline ~ReferenceCountedObjectPtr()
  7504. {
  7505. if (referencedObject != 0)
  7506. referencedObject->decReferenceCount();
  7507. }
  7508. /** Returns the object that this pointer references.
  7509. The pointer returned may be zero, of course.
  7510. */
  7511. inline operator ReferenceCountedObjectClass*() const throw()
  7512. {
  7513. return referencedObject;
  7514. }
  7515. // the -> operator is called on the referenced object
  7516. inline ReferenceCountedObjectClass* operator->() const throw()
  7517. {
  7518. return referencedObject;
  7519. }
  7520. /** Returns the object that this pointer references.
  7521. The pointer returned may be zero, of course.
  7522. */
  7523. inline ReferenceCountedObjectClass* getObject() const throw()
  7524. {
  7525. return referencedObject;
  7526. }
  7527. private:
  7528. ReferenceCountedObjectClass* referencedObject;
  7529. };
  7530. /** Compares two ReferenceCountedObjectPointers. */
  7531. template <class ReferenceCountedObjectClass>
  7532. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) throw()
  7533. {
  7534. return object1.getObject() == object2;
  7535. }
  7536. /** Compares two ReferenceCountedObjectPointers. */
  7537. template <class ReferenceCountedObjectClass>
  7538. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7539. {
  7540. return object1.getObject() == object2.getObject();
  7541. }
  7542. /** Compares two ReferenceCountedObjectPointers. */
  7543. template <class ReferenceCountedObjectClass>
  7544. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7545. {
  7546. return object1 == object2.getObject();
  7547. }
  7548. /** Compares two ReferenceCountedObjectPointers. */
  7549. template <class ReferenceCountedObjectClass>
  7550. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) throw()
  7551. {
  7552. return object1.getObject() != object2;
  7553. }
  7554. /** Compares two ReferenceCountedObjectPointers. */
  7555. template <class ReferenceCountedObjectClass>
  7556. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7557. {
  7558. return object1.getObject() != object2.getObject();
  7559. }
  7560. /** Compares two ReferenceCountedObjectPointers. */
  7561. template <class ReferenceCountedObjectClass>
  7562. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7563. {
  7564. return object1 != object2.getObject();
  7565. }
  7566. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7567. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7568. /**
  7569. Represents a dynamically implemented object.
  7570. This class is primarily intended for wrapping scripting language objects,
  7571. but could be used for other purposes.
  7572. An instance of a DynamicObject can be used to store named properties, and
  7573. by subclassing hasMethod() and invokeMethod(), you can give your object
  7574. methods.
  7575. */
  7576. class JUCE_API DynamicObject : public ReferenceCountedObject
  7577. {
  7578. public:
  7579. DynamicObject();
  7580. /** Destructor. */
  7581. virtual ~DynamicObject();
  7582. /** Returns true if the object has a property with this name.
  7583. Note that if the property is actually a method, this will return false.
  7584. */
  7585. virtual bool hasProperty (const Identifier& propertyName) const;
  7586. /** Returns a named property.
  7587. This returns a void if no such property exists.
  7588. */
  7589. virtual const var getProperty (const Identifier& propertyName) const;
  7590. /** Sets a named property. */
  7591. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7592. /** Removes a named property. */
  7593. virtual void removeProperty (const Identifier& propertyName);
  7594. /** Checks whether this object has the specified method.
  7595. The default implementation of this just checks whether there's a property
  7596. with this name that's actually a method, but this can be overridden for
  7597. building objects with dynamic invocation.
  7598. */
  7599. virtual bool hasMethod (const Identifier& methodName) const;
  7600. /** Invokes a named method on this object.
  7601. The default implementation looks up the named property, and if it's a method
  7602. call, then it invokes it.
  7603. This method is virtual to allow more dynamic invocation to used for objects
  7604. where the methods may not already be set as properies.
  7605. */
  7606. virtual const var invokeMethod (const Identifier& methodName,
  7607. const var* parameters,
  7608. int numParameters);
  7609. /** Sets up a method.
  7610. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7611. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7612. the code easier to read,
  7613. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7614. @code
  7615. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7616. @endcode
  7617. */
  7618. void setMethod (const Identifier& methodName,
  7619. var::MethodFunction methodFunction);
  7620. /** Removes all properties and methods from the object. */
  7621. void clear();
  7622. private:
  7623. NamedValueSet properties;
  7624. JUCE_LEAK_DETECTOR (DynamicObject);
  7625. };
  7626. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7627. /*** End of inlined file: juce_DynamicObject.h ***/
  7628. #endif
  7629. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7630. #endif
  7631. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7632. /*** Start of inlined file: juce_HashMap.h ***/
  7633. #ifndef __JUCE_HASHMAP_JUCEHEADER__
  7634. #define __JUCE_HASHMAP_JUCEHEADER__
  7635. /*** Start of inlined file: juce_OwnedArray.h ***/
  7636. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7637. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7638. /** An array designed for holding objects.
  7639. This holds a list of pointers to objects, and will automatically
  7640. delete the objects when they are removed from the array, or when the
  7641. array is itself deleted.
  7642. Declare it in the form: OwnedArray<MyObjectClass>
  7643. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7644. After adding objects, they are 'owned' by the array and will be deleted when
  7645. removed or replaced.
  7646. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7647. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7648. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7649. */
  7650. template <class ObjectClass,
  7651. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7652. class OwnedArray
  7653. {
  7654. public:
  7655. /** Creates an empty array. */
  7656. OwnedArray() throw()
  7657. : numUsed (0)
  7658. {
  7659. }
  7660. /** Deletes the array and also deletes any objects inside it.
  7661. To get rid of the array without deleting its objects, use its
  7662. clear (false) method before deleting it.
  7663. */
  7664. ~OwnedArray()
  7665. {
  7666. clear (true);
  7667. }
  7668. /** Clears the array, optionally deleting the objects inside it first. */
  7669. void clear (const bool deleteObjects = true)
  7670. {
  7671. const ScopedLockType lock (getLock());
  7672. if (deleteObjects)
  7673. {
  7674. while (numUsed > 0)
  7675. delete data.elements [--numUsed];
  7676. }
  7677. data.setAllocatedSize (0);
  7678. numUsed = 0;
  7679. }
  7680. /** Returns the number of items currently in the array.
  7681. @see operator[]
  7682. */
  7683. inline int size() const throw()
  7684. {
  7685. return numUsed;
  7686. }
  7687. /** Returns a pointer to the object at this index in the array.
  7688. If the index is out-of-range, this will return a null pointer, (and
  7689. it could be null anyway, because it's ok for the array to hold null
  7690. pointers as well as objects).
  7691. @see getUnchecked
  7692. */
  7693. inline ObjectClass* operator[] (const int index) const throw()
  7694. {
  7695. const ScopedLockType lock (getLock());
  7696. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7697. : static_cast <ObjectClass*> (0);
  7698. }
  7699. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7700. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7701. it can be used when you're sure the index if always going to be legal.
  7702. */
  7703. inline ObjectClass* getUnchecked (const int index) const throw()
  7704. {
  7705. const ScopedLockType lock (getLock());
  7706. jassert (isPositiveAndBelow (index, numUsed));
  7707. return data.elements [index];
  7708. }
  7709. /** Returns a pointer to the first object in the array.
  7710. This will return a null pointer if the array's empty.
  7711. @see getLast
  7712. */
  7713. inline ObjectClass* getFirst() const throw()
  7714. {
  7715. const ScopedLockType lock (getLock());
  7716. return numUsed > 0 ? data.elements [0]
  7717. : static_cast <ObjectClass*> (0);
  7718. }
  7719. /** Returns a pointer to the last object in the array.
  7720. This will return a null pointer if the array's empty.
  7721. @see getFirst
  7722. */
  7723. inline ObjectClass* getLast() const throw()
  7724. {
  7725. const ScopedLockType lock (getLock());
  7726. return numUsed > 0 ? data.elements [numUsed - 1]
  7727. : static_cast <ObjectClass*> (0);
  7728. }
  7729. /** Returns a pointer to the actual array data.
  7730. This pointer will only be valid until the next time a non-const method
  7731. is called on the array.
  7732. */
  7733. inline ObjectClass** getRawDataPointer() throw()
  7734. {
  7735. return data.elements;
  7736. }
  7737. /** Finds the index of an object which might be in the array.
  7738. @param objectToLookFor the object to look for
  7739. @returns the index at which the object was found, or -1 if it's not found
  7740. */
  7741. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7742. {
  7743. const ScopedLockType lock (getLock());
  7744. ObjectClass* const* e = data.elements.getData();
  7745. ObjectClass* const* const end = e + numUsed;
  7746. for (; e != end; ++e)
  7747. if (objectToLookFor == *e)
  7748. return static_cast <int> (e - data.elements.getData());
  7749. return -1;
  7750. }
  7751. /** Returns true if the array contains a specified object.
  7752. @param objectToLookFor the object to look for
  7753. @returns true if the object is in the array
  7754. */
  7755. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7756. {
  7757. const ScopedLockType lock (getLock());
  7758. ObjectClass* const* e = data.elements.getData();
  7759. ObjectClass* const* const end = e + numUsed;
  7760. for (; e != end; ++e)
  7761. if (objectToLookFor == *e)
  7762. return true;
  7763. return false;
  7764. }
  7765. /** Appends a new object to the end of the array.
  7766. Note that the this object will be deleted by the OwnedArray when it
  7767. is removed, so be careful not to delete it somewhere else.
  7768. Also be careful not to add the same object to the array more than once,
  7769. as this will obviously cause deletion of dangling pointers.
  7770. @param newObject the new object to add to the array
  7771. @see set, insert, addIfNotAlreadyThere, addSorted
  7772. */
  7773. void add (const ObjectClass* const newObject) throw()
  7774. {
  7775. const ScopedLockType lock (getLock());
  7776. data.ensureAllocatedSize (numUsed + 1);
  7777. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7778. }
  7779. /** Inserts a new object into the array at the given index.
  7780. Note that the this object will be deleted by the OwnedArray when it
  7781. is removed, so be careful not to delete it somewhere else.
  7782. If the index is less than 0 or greater than the size of the array, the
  7783. element will be added to the end of the array.
  7784. Otherwise, it will be inserted into the array, moving all the later elements
  7785. along to make room.
  7786. Be careful not to add the same object to the array more than once,
  7787. as this will obviously cause deletion of dangling pointers.
  7788. @param indexToInsertAt the index at which the new element should be inserted
  7789. @param newObject the new object to add to the array
  7790. @see add, addSorted, addIfNotAlreadyThere, set
  7791. */
  7792. void insert (int indexToInsertAt,
  7793. const ObjectClass* const newObject) throw()
  7794. {
  7795. if (indexToInsertAt >= 0)
  7796. {
  7797. const ScopedLockType lock (getLock());
  7798. if (indexToInsertAt > numUsed)
  7799. indexToInsertAt = numUsed;
  7800. data.ensureAllocatedSize (numUsed + 1);
  7801. ObjectClass** const e = data.elements + indexToInsertAt;
  7802. const int numToMove = numUsed - indexToInsertAt;
  7803. if (numToMove > 0)
  7804. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7805. *e = const_cast <ObjectClass*> (newObject);
  7806. ++numUsed;
  7807. }
  7808. else
  7809. {
  7810. add (newObject);
  7811. }
  7812. }
  7813. /** Appends a new object at the end of the array as long as the array doesn't
  7814. already contain it.
  7815. If the array already contains a matching object, nothing will be done.
  7816. @param newObject the new object to add to the array
  7817. */
  7818. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  7819. {
  7820. const ScopedLockType lock (getLock());
  7821. if (! contains (newObject))
  7822. add (newObject);
  7823. }
  7824. /** Replaces an object in the array with a different one.
  7825. If the index is less than zero, this method does nothing.
  7826. If the index is beyond the end of the array, the new object is added to the end of the array.
  7827. Be careful not to add the same object to the array more than once,
  7828. as this will obviously cause deletion of dangling pointers.
  7829. @param indexToChange the index whose value you want to change
  7830. @param newObject the new value to set for this index.
  7831. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7832. @see add, insert, remove
  7833. */
  7834. void set (const int indexToChange,
  7835. const ObjectClass* const newObject,
  7836. const bool deleteOldElement = true)
  7837. {
  7838. if (indexToChange >= 0)
  7839. {
  7840. ObjectClass* toDelete = 0;
  7841. {
  7842. const ScopedLockType lock (getLock());
  7843. if (indexToChange < numUsed)
  7844. {
  7845. if (deleteOldElement)
  7846. {
  7847. toDelete = data.elements [indexToChange];
  7848. if (toDelete == newObject)
  7849. toDelete = 0;
  7850. }
  7851. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7852. }
  7853. else
  7854. {
  7855. data.ensureAllocatedSize (numUsed + 1);
  7856. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7857. }
  7858. }
  7859. delete toDelete; // don't want to use a ScopedPointer here because if the
  7860. // object has a private destructor, both OwnedArray and
  7861. // ScopedPointer would need to be friend classes..
  7862. }
  7863. else
  7864. {
  7865. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7866. // any effect - but since the object is not being added, it may be leaking..
  7867. }
  7868. }
  7869. /** Adds elements from another array to the end of this array.
  7870. @param arrayToAddFrom the array from which to copy the elements
  7871. @param startIndex the first element of the other array to start copying from
  7872. @param numElementsToAdd how many elements to add from the other array. If this
  7873. value is negative or greater than the number of available elements,
  7874. all available elements will be copied.
  7875. @see add
  7876. */
  7877. template <class OtherArrayType>
  7878. void addArray (const OtherArrayType& arrayToAddFrom,
  7879. int startIndex = 0,
  7880. int numElementsToAdd = -1)
  7881. {
  7882. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7883. const ScopedLockType lock2 (getLock());
  7884. if (startIndex < 0)
  7885. {
  7886. jassertfalse;
  7887. startIndex = 0;
  7888. }
  7889. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7890. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7891. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7892. while (--numElementsToAdd >= 0)
  7893. {
  7894. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7895. ++numUsed;
  7896. }
  7897. }
  7898. /** Adds copies of the elements in another array to the end of this array.
  7899. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7900. containing pointers to the same kind of object. The objects involved must provide
  7901. a copy constructor, and this will be used to create new copies of each element, and
  7902. add them to this array.
  7903. @param arrayToAddFrom the array from which to copy the elements
  7904. @param startIndex the first element of the other array to start copying from
  7905. @param numElementsToAdd how many elements to add from the other array. If this
  7906. value is negative or greater than the number of available elements,
  7907. all available elements will be copied.
  7908. @see add
  7909. */
  7910. template <class OtherArrayType>
  7911. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7912. int startIndex = 0,
  7913. int numElementsToAdd = -1)
  7914. {
  7915. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7916. const ScopedLockType lock2 (getLock());
  7917. if (startIndex < 0)
  7918. {
  7919. jassertfalse;
  7920. startIndex = 0;
  7921. }
  7922. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7923. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7924. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7925. while (--numElementsToAdd >= 0)
  7926. {
  7927. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7928. ++numUsed;
  7929. }
  7930. }
  7931. /** Inserts a new object into the array assuming that the array is sorted.
  7932. This will use a comparator to find the position at which the new object
  7933. should go. If the array isn't sorted, the behaviour of this
  7934. method will be unpredictable.
  7935. @param comparator the comparator to use to compare the elements - see the sort method
  7936. for details about this object's structure
  7937. @param newObject the new object to insert to the array
  7938. @returns the index at which the new object was added
  7939. @see add, sort, indexOfSorted
  7940. */
  7941. template <class ElementComparator>
  7942. int addSorted (ElementComparator& comparator, ObjectClass* const newObject) throw()
  7943. {
  7944. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7945. // avoids getting warning messages about the parameter being unused
  7946. const ScopedLockType lock (getLock());
  7947. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  7948. insert (index, newObject);
  7949. return index;
  7950. }
  7951. /** Finds the index of an object in the array, assuming that the array is sorted.
  7952. This will use a comparator to do a binary-chop to find the index of the given
  7953. element, if it exists. If the array isn't sorted, the behaviour of this
  7954. method will be unpredictable.
  7955. @param comparator the comparator to use to compare the elements - see the sort()
  7956. method for details about the form this object should take
  7957. @param objectToLookFor the object to search for
  7958. @returns the index of the element, or -1 if it's not found
  7959. @see addSorted, sort
  7960. */
  7961. template <class ElementComparator>
  7962. int indexOfSorted (ElementComparator& comparator,
  7963. const ObjectClass* const objectToLookFor) const throw()
  7964. {
  7965. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7966. // avoids getting warning messages about the parameter being unused
  7967. const ScopedLockType lock (getLock());
  7968. int start = 0;
  7969. int end = numUsed;
  7970. for (;;)
  7971. {
  7972. if (start >= end)
  7973. {
  7974. return -1;
  7975. }
  7976. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  7977. {
  7978. return start;
  7979. }
  7980. else
  7981. {
  7982. const int halfway = (start + end) >> 1;
  7983. if (halfway == start)
  7984. return -1;
  7985. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  7986. start = halfway;
  7987. else
  7988. end = halfway;
  7989. }
  7990. }
  7991. }
  7992. /** Removes an object from the array.
  7993. This will remove the object at a given index (optionally also
  7994. deleting it) and move back all the subsequent objects to close the gap.
  7995. If the index passed in is out-of-range, nothing will happen.
  7996. @param indexToRemove the index of the element to remove
  7997. @param deleteObject whether to delete the object that is removed
  7998. @see removeObject, removeRange
  7999. */
  8000. void remove (const int indexToRemove,
  8001. const bool deleteObject = true)
  8002. {
  8003. ObjectClass* toDelete = 0;
  8004. {
  8005. const ScopedLockType lock (getLock());
  8006. if (isPositiveAndBelow (indexToRemove, numUsed))
  8007. {
  8008. ObjectClass** const e = data.elements + indexToRemove;
  8009. if (deleteObject)
  8010. toDelete = *e;
  8011. --numUsed;
  8012. const int numToShift = numUsed - indexToRemove;
  8013. if (numToShift > 0)
  8014. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8015. }
  8016. }
  8017. delete toDelete; // don't want to use a ScopedPointer here because if the
  8018. // object has a private destructor, both OwnedArray and
  8019. // ScopedPointer would need to be friend classes..
  8020. if ((numUsed << 1) < data.numAllocated)
  8021. minimiseStorageOverheads();
  8022. }
  8023. /** Removes and returns an object from the array without deleting it.
  8024. This will remove the object at a given index and return it, moving back all
  8025. the subsequent objects to close the gap. If the index passed in is out-of-range,
  8026. nothing will happen.
  8027. @param indexToRemove the index of the element to remove
  8028. @see remove, removeObject, removeRange
  8029. */
  8030. ObjectClass* removeAndReturn (const int indexToRemove)
  8031. {
  8032. ObjectClass* removedItem = 0;
  8033. const ScopedLockType lock (getLock());
  8034. if (isPositiveAndBelow (indexToRemove, numUsed))
  8035. {
  8036. ObjectClass** const e = data.elements + indexToRemove;
  8037. removedItem = *e;
  8038. --numUsed;
  8039. const int numToShift = numUsed - indexToRemove;
  8040. if (numToShift > 0)
  8041. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  8042. if ((numUsed << 1) < data.numAllocated)
  8043. minimiseStorageOverheads();
  8044. }
  8045. return removedItem;
  8046. }
  8047. /** Removes a specified object from the array.
  8048. If the item isn't found, no action is taken.
  8049. @param objectToRemove the object to try to remove
  8050. @param deleteObject whether to delete the object (if it's found)
  8051. @see remove, removeRange
  8052. */
  8053. void removeObject (const ObjectClass* const objectToRemove,
  8054. const bool deleteObject = true)
  8055. {
  8056. const ScopedLockType lock (getLock());
  8057. ObjectClass** const e = data.elements.getData();
  8058. for (int i = 0; i < numUsed; ++i)
  8059. {
  8060. if (objectToRemove == e[i])
  8061. {
  8062. remove (i, deleteObject);
  8063. break;
  8064. }
  8065. }
  8066. }
  8067. /** Removes a range of objects from the array.
  8068. This will remove a set of objects, starting from the given index,
  8069. and move any subsequent elements down to close the gap.
  8070. If the range extends beyond the bounds of the array, it will
  8071. be safely clipped to the size of the array.
  8072. @param startIndex the index of the first object to remove
  8073. @param numberToRemove how many objects should be removed
  8074. @param deleteObjects whether to delete the objects that get removed
  8075. @see remove, removeObject
  8076. */
  8077. void removeRange (int startIndex,
  8078. const int numberToRemove,
  8079. const bool deleteObjects = true)
  8080. {
  8081. const ScopedLockType lock (getLock());
  8082. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  8083. startIndex = jlimit (0, numUsed, startIndex);
  8084. if (endIndex > startIndex)
  8085. {
  8086. if (deleteObjects)
  8087. {
  8088. for (int i = startIndex; i < endIndex; ++i)
  8089. {
  8090. delete data.elements [i];
  8091. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8092. }
  8093. }
  8094. const int rangeSize = endIndex - startIndex;
  8095. ObjectClass** e = data.elements + startIndex;
  8096. int numToShift = numUsed - endIndex;
  8097. numUsed -= rangeSize;
  8098. while (--numToShift >= 0)
  8099. {
  8100. *e = e [rangeSize];
  8101. ++e;
  8102. }
  8103. if ((numUsed << 1) < data.numAllocated)
  8104. minimiseStorageOverheads();
  8105. }
  8106. }
  8107. /** Removes the last n objects from the array.
  8108. @param howManyToRemove how many objects to remove from the end of the array
  8109. @param deleteObjects whether to also delete the objects that are removed
  8110. @see remove, removeObject, removeRange
  8111. */
  8112. void removeLast (int howManyToRemove = 1,
  8113. const bool deleteObjects = true)
  8114. {
  8115. const ScopedLockType lock (getLock());
  8116. if (howManyToRemove >= numUsed)
  8117. clear (deleteObjects);
  8118. else
  8119. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  8120. }
  8121. /** Swaps a pair of objects in the array.
  8122. If either of the indexes passed in is out-of-range, nothing will happen,
  8123. otherwise the two objects at these positions will be exchanged.
  8124. */
  8125. void swap (const int index1,
  8126. const int index2) throw()
  8127. {
  8128. const ScopedLockType lock (getLock());
  8129. if (isPositiveAndBelow (index1, numUsed)
  8130. && isPositiveAndBelow (index2, numUsed))
  8131. {
  8132. swapVariables (data.elements [index1],
  8133. data.elements [index2]);
  8134. }
  8135. }
  8136. /** Moves one of the objects to a different position.
  8137. This will move the object to a specified index, shuffling along
  8138. any intervening elements as required.
  8139. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8140. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8141. @param currentIndex the index of the object to be moved. If this isn't a
  8142. valid index, then nothing will be done
  8143. @param newIndex the index at which you'd like this object to end up. If this
  8144. is less than zero, it will be moved to the end of the array
  8145. */
  8146. void move (const int currentIndex,
  8147. int newIndex) throw()
  8148. {
  8149. if (currentIndex != newIndex)
  8150. {
  8151. const ScopedLockType lock (getLock());
  8152. if (isPositiveAndBelow (currentIndex, numUsed))
  8153. {
  8154. if (! isPositiveAndBelow (newIndex, numUsed))
  8155. newIndex = numUsed - 1;
  8156. ObjectClass* const value = data.elements [currentIndex];
  8157. if (newIndex > currentIndex)
  8158. {
  8159. memmove (data.elements + currentIndex,
  8160. data.elements + currentIndex + 1,
  8161. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8162. }
  8163. else
  8164. {
  8165. memmove (data.elements + newIndex + 1,
  8166. data.elements + newIndex,
  8167. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8168. }
  8169. data.elements [newIndex] = value;
  8170. }
  8171. }
  8172. }
  8173. /** This swaps the contents of this array with those of another array.
  8174. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8175. because it just swaps their internal pointers.
  8176. */
  8177. void swapWithArray (OwnedArray& otherArray) throw()
  8178. {
  8179. const ScopedLockType lock1 (getLock());
  8180. const ScopedLockType lock2 (otherArray.getLock());
  8181. data.swapWith (otherArray.data);
  8182. swapVariables (numUsed, otherArray.numUsed);
  8183. }
  8184. /** Reduces the amount of storage being used by the array.
  8185. Arrays typically allocate slightly more storage than they need, and after
  8186. removing elements, they may have quite a lot of unused space allocated.
  8187. This method will reduce the amount of allocated storage to a minimum.
  8188. */
  8189. void minimiseStorageOverheads() throw()
  8190. {
  8191. const ScopedLockType lock (getLock());
  8192. data.shrinkToNoMoreThan (numUsed);
  8193. }
  8194. /** Increases the array's internal storage to hold a minimum number of elements.
  8195. Calling this before adding a large known number of elements means that
  8196. the array won't have to keep dynamically resizing itself as the elements
  8197. are added, and it'll therefore be more efficient.
  8198. */
  8199. void ensureStorageAllocated (const int minNumElements) throw()
  8200. {
  8201. const ScopedLockType lock (getLock());
  8202. data.ensureAllocatedSize (minNumElements);
  8203. }
  8204. /** Sorts the elements in the array.
  8205. This will use a comparator object to sort the elements into order. The object
  8206. passed must have a method of the form:
  8207. @code
  8208. int compareElements (ElementType first, ElementType second);
  8209. @endcode
  8210. ..and this method must return:
  8211. - a value of < 0 if the first comes before the second
  8212. - a value of 0 if the two objects are equivalent
  8213. - a value of > 0 if the second comes before the first
  8214. To improve performance, the compareElements() method can be declared as static or const.
  8215. @param comparator the comparator to use for comparing elements.
  8216. @param retainOrderOfEquivalentItems if this is true, then items
  8217. which the comparator says are equivalent will be
  8218. kept in the order in which they currently appear
  8219. in the array. This is slower to perform, but may
  8220. be important in some cases. If it's false, a faster
  8221. algorithm is used, but equivalent elements may be
  8222. rearranged.
  8223. @see sortArray, indexOfSorted
  8224. */
  8225. template <class ElementComparator>
  8226. void sort (ElementComparator& comparator,
  8227. const bool retainOrderOfEquivalentItems = false) const throw()
  8228. {
  8229. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8230. // avoids getting warning messages about the parameter being unused
  8231. const ScopedLockType lock (getLock());
  8232. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8233. }
  8234. /** Returns the CriticalSection that locks this array.
  8235. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8236. an object of ScopedLockType as an RAII lock for it.
  8237. */
  8238. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8239. /** Returns the type of scoped lock to use for locking this array */
  8240. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8241. private:
  8242. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8243. int numUsed;
  8244. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  8245. };
  8246. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  8247. /*** End of inlined file: juce_OwnedArray.h ***/
  8248. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8249. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8250. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8251. /**
  8252. This class holds a pointer which is automatically deleted when this object goes
  8253. out of scope.
  8254. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8255. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8256. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8257. created objects.
  8258. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8259. to an object. If you use the assignment operator to assign a different object to a
  8260. ScopedPointer, the old one will be automatically deleted.
  8261. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8262. object to which it points during its lifetime. This means that making a copy of a const
  8263. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8264. old one.
  8265. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8266. can use the release() method.
  8267. */
  8268. template <class ObjectType>
  8269. class ScopedPointer
  8270. {
  8271. public:
  8272. /** Creates a ScopedPointer containing a null pointer. */
  8273. inline ScopedPointer() throw() : object (0)
  8274. {
  8275. }
  8276. /** Creates a ScopedPointer that owns the specified object. */
  8277. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  8278. : object (objectToTakePossessionOf)
  8279. {
  8280. }
  8281. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8282. Because a pointer can only belong to one ScopedPointer, this transfers
  8283. the pointer from the other object to this one, and the other object is reset to
  8284. be a null pointer.
  8285. */
  8286. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  8287. : object (objectToTransferFrom.object)
  8288. {
  8289. objectToTransferFrom.object = 0;
  8290. }
  8291. /** Destructor.
  8292. This will delete the object that this ScopedPointer currently refers to.
  8293. */
  8294. inline ~ScopedPointer() { delete object; }
  8295. /** Changes this ScopedPointer to point to a new object.
  8296. Because a pointer can only belong to one ScopedPointer, this transfers
  8297. the pointer from the other object to this one, and the other object is reset to
  8298. be a null pointer.
  8299. If this ScopedPointer already points to an object, that object
  8300. will first be deleted.
  8301. */
  8302. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8303. {
  8304. if (this != objectToTransferFrom.getAddress())
  8305. {
  8306. // Two ScopedPointers should never be able to refer to the same object - if
  8307. // this happens, you must have done something dodgy!
  8308. jassert (object == 0 || object != objectToTransferFrom.object);
  8309. ObjectType* const oldObject = object;
  8310. object = objectToTransferFrom.object;
  8311. objectToTransferFrom.object = 0;
  8312. delete oldObject;
  8313. }
  8314. return *this;
  8315. }
  8316. /** Changes this ScopedPointer to point to a new object.
  8317. If this ScopedPointer already points to an object, that object
  8318. will first be deleted.
  8319. The pointer that you pass is may be null.
  8320. */
  8321. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8322. {
  8323. if (object != newObjectToTakePossessionOf)
  8324. {
  8325. ObjectType* const oldObject = object;
  8326. object = newObjectToTakePossessionOf;
  8327. delete oldObject;
  8328. }
  8329. return *this;
  8330. }
  8331. /** Returns the object that this ScopedPointer refers to. */
  8332. inline operator ObjectType*() const throw() { return object; }
  8333. /** Returns the object that this ScopedPointer refers to. */
  8334. inline ObjectType& operator*() const throw() { return *object; }
  8335. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8336. inline ObjectType* operator->() const throw() { return object; }
  8337. /** Removes the current object from this ScopedPointer without deleting it.
  8338. This will return the current object, and set the ScopedPointer to a null pointer.
  8339. */
  8340. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  8341. /** Swaps this object with that of another ScopedPointer.
  8342. The two objects simply exchange their pointers.
  8343. */
  8344. void swapWith (ScopedPointer <ObjectType>& other) throw()
  8345. {
  8346. // Two ScopedPointers should never be able to refer to the same object - if
  8347. // this happens, you must have done something dodgy!
  8348. jassert (object != other.object);
  8349. swapVariables (object, other.object);
  8350. }
  8351. private:
  8352. ObjectType* object;
  8353. // (Required as an alternative to the overloaded & operator).
  8354. const ScopedPointer* getAddress() const throw() { return this; }
  8355. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8356. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8357. would let you do so by implicitly casting the source to its raw object pointer).
  8358. A side effect of this is that you may hit a puzzling compiler error when you write something
  8359. like this:
  8360. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8361. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8362. copy constructor is private. It's very easy to fis though - just write it like this:
  8363. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8364. It's good practice to always use the latter form when writing your object declarations anyway,
  8365. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8366. smart enough to replace your construction + assignment with a single constructor.
  8367. */
  8368. ScopedPointer (const ScopedPointer&);
  8369. #endif
  8370. };
  8371. /** Compares a ScopedPointer with another pointer.
  8372. This can be handy for checking whether this is a null pointer.
  8373. */
  8374. template <class ObjectType>
  8375. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  8376. {
  8377. return static_cast <ObjectType*> (pointer1) == pointer2;
  8378. }
  8379. /** Compares a ScopedPointer with another pointer.
  8380. This can be handy for checking whether this is a null pointer.
  8381. */
  8382. template <class ObjectType>
  8383. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  8384. {
  8385. return static_cast <ObjectType*> (pointer1) != pointer2;
  8386. }
  8387. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8388. /*** End of inlined file: juce_ScopedPointer.h ***/
  8389. /**
  8390. A simple class to generate hash functions for some primitive types, intended for
  8391. use with the HashMap class.
  8392. @see HashMap
  8393. */
  8394. class DefaultHashFunctions
  8395. {
  8396. public:
  8397. /** Generates a simple hash from an integer. */
  8398. static int generateHash (const int key, const int upperLimit) throw() { return std::abs (key) % upperLimit; }
  8399. /** Generates a simple hash from a string. */
  8400. static int generateHash (const String& key, const int upperLimit) throw() { return key.hashCode() % upperLimit; }
  8401. /** Generates a simple hash from a variant. */
  8402. static int generateHash (const var& key, const int upperLimit) throw() { return generateHash (key.toString(), upperLimit); }
  8403. };
  8404. /**
  8405. Holds a set of mappings between some key/value pairs.
  8406. The types of the key and value objects are set as template parameters.
  8407. You can also specify a class to supply a hash function that converts a key value
  8408. into an hashed integer. This class must have the form:
  8409. @code
  8410. struct MyHashGenerator
  8411. {
  8412. static int generateHash (MyKeyType key, int upperLimit)
  8413. {
  8414. // The function must return a value 0 <= x < upperLimit
  8415. return someFunctionOfMyKeyType (key) % upperLimit;
  8416. }
  8417. };
  8418. @endcode
  8419. Like the Array class, the key and value types are expected to be copy-by-value types, so
  8420. if you define them to be pointer types, this class won't delete the objects that they
  8421. point to.
  8422. If you don't supply a class for the HashFunctionToUse template parameter, the
  8423. default one provides some simple mappings for strings and ints.
  8424. @code
  8425. HashMap<int, String> hash;
  8426. hash.set (1, "item1");
  8427. hash.set (2, "item2");
  8428. DBG (hash [1]); // prints "item1"
  8429. DBG (hash [2]); // prints "item2"
  8430. // This iterates the map, printing all of its key -> value pairs..
  8431. for (HashMap<int, String>::Iterator i (hash); i.next();)
  8432. DBG (i.getKey() << " -> " << i.getValue());
  8433. @endcode
  8434. @see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
  8435. */
  8436. template <typename KeyType,
  8437. typename ValueType,
  8438. class HashFunctionToUse = DefaultHashFunctions,
  8439. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8440. class HashMap
  8441. {
  8442. private:
  8443. typedef PARAMETER_TYPE (KeyType) KeyTypeParameter;
  8444. typedef PARAMETER_TYPE (ValueType) ValueTypeParameter;
  8445. public:
  8446. /** Creates an empty hash-map.
  8447. The numberOfSlots parameter specifies the number of hash entries the map will use. This
  8448. will be the "upperLimit" parameter that is passed to your generateHash() function. The number
  8449. of hash slots will grow automatically if necessary, or it can be remapped manually using remapTable().
  8450. */
  8451. HashMap (const int numberOfSlots = defaultHashTableSize)
  8452. : totalNumItems (0)
  8453. {
  8454. slots.insertMultiple (0, 0, numberOfSlots);
  8455. }
  8456. /** Destructor. */
  8457. ~HashMap()
  8458. {
  8459. clear();
  8460. }
  8461. /** Removes all values from the map.
  8462. Note that this will clear the content, but won't affect the number of slots (see
  8463. remapTable and getNumSlots).
  8464. */
  8465. void clear()
  8466. {
  8467. const ScopedLockType sl (getLock());
  8468. for (int i = slots.size(); --i >= 0;)
  8469. {
  8470. HashEntry* h = slots.getUnchecked(i);
  8471. while (h != 0)
  8472. {
  8473. const ScopedPointer<HashEntry> deleter (h);
  8474. h = h->nextEntry;
  8475. }
  8476. slots.set (i, 0);
  8477. }
  8478. totalNumItems = 0;
  8479. }
  8480. /** Returns the current number of items in the map. */
  8481. inline int size() const throw()
  8482. {
  8483. return totalNumItems;
  8484. }
  8485. /** Returns the value corresponding to a given key.
  8486. If the map doesn't contain the key, a default instance of the value type is returned.
  8487. @param keyToLookFor the key of the item being requested
  8488. */
  8489. inline const ValueType operator[] (KeyTypeParameter keyToLookFor) const
  8490. {
  8491. const ScopedLockType sl (getLock());
  8492. for (const HashEntry* entry = slots [generateHashFor (keyToLookFor)]; entry != 0; entry = entry->nextEntry)
  8493. if (entry->key == keyToLookFor)
  8494. return entry->value;
  8495. return ValueType();
  8496. }
  8497. /** Returns true if the map contains an item with the specied key. */
  8498. bool contains (KeyTypeParameter keyToLookFor) const
  8499. {
  8500. const ScopedLockType sl (getLock());
  8501. for (const HashEntry* entry = slots [generateHashFor (keyToLookFor)]; entry != 0; entry = entry->nextEntry)
  8502. if (entry->key == keyToLookFor)
  8503. return true;
  8504. return false;
  8505. }
  8506. /** Returns true if the hash contains at least one occurrence of a given value. */
  8507. bool containsValue (ValueTypeParameter valueToLookFor) const
  8508. {
  8509. const ScopedLockType sl (getLock());
  8510. for (int i = getNumSlots(); --i >= 0;)
  8511. for (const HashEntry* entry = slots.getUnchecked(i); entry != 0; entry = entry->nextEntry)
  8512. if (entry->value == valueToLookFor)
  8513. return true;
  8514. return false;
  8515. }
  8516. /** Adds or replaces an element in the hash-map.
  8517. If there's already an item with the given key, this will replace its value. Otherwise, a new item
  8518. will be added to the map.
  8519. */
  8520. void set (KeyTypeParameter newKey, ValueTypeParameter newValue)
  8521. {
  8522. const ScopedLockType sl (getLock());
  8523. const int hashIndex = generateHashFor (newKey);
  8524. if (isPositiveAndBelow (hashIndex, getNumSlots()))
  8525. {
  8526. HashEntry* const firstEntry = slots.getUnchecked (hashIndex);
  8527. for (HashEntry* entry = firstEntry; entry != 0; entry = entry->nextEntry)
  8528. {
  8529. if (entry->key == newKey)
  8530. {
  8531. entry->value = newValue;
  8532. return;
  8533. }
  8534. }
  8535. slots.set (hashIndex, new HashEntry (newKey, newValue, firstEntry));
  8536. ++totalNumItems;
  8537. if (totalNumItems > (getNumSlots() * 3) / 2)
  8538. remapTable (getNumSlots() * 2);
  8539. }
  8540. }
  8541. /** Removes an item with the given key. */
  8542. void remove (KeyTypeParameter keyToRemove)
  8543. {
  8544. const ScopedLockType sl (getLock());
  8545. const int hashIndex = generateHashFor (keyToRemove);
  8546. HashEntry* entry = slots [hashIndex];
  8547. HashEntry* previous = 0;
  8548. while (entry != 0)
  8549. {
  8550. if (entry->key == keyToRemove)
  8551. {
  8552. const ScopedPointer<HashEntry> deleter (entry);
  8553. entry = entry->nextEntry;
  8554. if (previous != 0)
  8555. previous->nextEntry = entry;
  8556. else
  8557. slots.set (hashIndex, entry);
  8558. --totalNumItems;
  8559. }
  8560. else
  8561. {
  8562. previous = entry;
  8563. entry = entry->nextEntry;
  8564. }
  8565. }
  8566. }
  8567. /** Removes all items with the given value. */
  8568. void removeValue (ValueTypeParameter valueToRemove)
  8569. {
  8570. const ScopedLockType sl (getLock());
  8571. for (int i = getNumSlots(); --i >= 0;)
  8572. {
  8573. HashEntry* entry = slots.getUnchecked(i);
  8574. HashEntry* previous = 0;
  8575. while (entry != 0)
  8576. {
  8577. if (entry->value == valueToRemove)
  8578. {
  8579. const ScopedPointer<HashEntry> deleter (entry);
  8580. entry = entry->nextEntry;
  8581. if (previous != 0)
  8582. previous->nextEntry = entry;
  8583. else
  8584. slots.set (i, entry);
  8585. --totalNumItems;
  8586. }
  8587. else
  8588. {
  8589. previous = entry;
  8590. entry = entry->nextEntry;
  8591. }
  8592. }
  8593. }
  8594. }
  8595. /** Remaps the hash-map to use a different number of slots for its hash function.
  8596. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8597. @see getNumSlots()
  8598. */
  8599. void remapTable (int newNumberOfSlots)
  8600. {
  8601. HashMap newTable (newNumberOfSlots);
  8602. for (int i = getNumSlots(); --i >= 0;)
  8603. for (const HashEntry* entry = slots.getUnchecked(i); entry != 0; entry = entry->nextEntry)
  8604. newTable.set (entry->key, entry->value);
  8605. swapWith (newTable);
  8606. }
  8607. /** Returns the number of slots which are available for hashing.
  8608. Each slot corresponds to a single hash-code, and each one can contain multiple items.
  8609. @see getNumSlots()
  8610. */
  8611. inline int getNumSlots() const throw()
  8612. {
  8613. return slots.size();
  8614. }
  8615. /** Efficiently swaps the contents of two hash-maps. */
  8616. void swapWith (HashMap& otherHashMap) throw()
  8617. {
  8618. const ScopedLockType lock1 (getLock());
  8619. const ScopedLockType lock2 (otherHashMap.getLock());
  8620. slots.swapWithArray (otherHashMap.slots);
  8621. swapVariables (totalNumItems, otherHashMap.totalNumItems);
  8622. }
  8623. /** Returns the CriticalSection that locks this structure.
  8624. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8625. an object of ScopedLockType as an RAII lock for it.
  8626. */
  8627. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return lock; }
  8628. /** Returns the type of scoped lock to use for locking this array */
  8629. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8630. private:
  8631. class HashEntry
  8632. {
  8633. public:
  8634. HashEntry (KeyTypeParameter key_, ValueTypeParameter value_, HashEntry* const nextEntry_)
  8635. : key (key_), value (value_), nextEntry (nextEntry_)
  8636. {}
  8637. const KeyType key;
  8638. ValueType value;
  8639. HashEntry* nextEntry;
  8640. JUCE_DECLARE_NON_COPYABLE (HashEntry);
  8641. };
  8642. public:
  8643. /** Iterates over the items in a HashMap.
  8644. To use it, repeatedly call next() until it returns false, e.g.
  8645. @code
  8646. HashMap <String, String> myMap;
  8647. HashMap<String, String>::Iterator i (myMap);
  8648. while (i.next())
  8649. {
  8650. DBG (i.getKey() << " -> " << i.getValue());
  8651. }
  8652. @endcode
  8653. The order in which items are iterated bears no resemblence to the order in which
  8654. they were originally added!
  8655. Obviously as soon as you call any non-const methods on the original hash-map, any
  8656. iterators that were created beforehand will cease to be valid, and should not be used.
  8657. @see HashMap
  8658. */
  8659. class Iterator
  8660. {
  8661. public:
  8662. Iterator (const HashMap& hashMapToIterate)
  8663. : hashMap (hashMapToIterate), entry (0), index (0)
  8664. {}
  8665. /** Moves to the next item, if one is available.
  8666. When this returns true, you can get the item's key and value using getKey() and
  8667. getValue(). If it returns false, the iteration has finished and you should stop.
  8668. */
  8669. bool next()
  8670. {
  8671. if (entry != 0)
  8672. entry = entry->nextEntry;
  8673. while (entry == 0)
  8674. {
  8675. if (index >= hashMap.getNumSlots())
  8676. return false;
  8677. entry = hashMap.slots.getUnchecked (index++);
  8678. }
  8679. return true;
  8680. }
  8681. /** Returns the current item's key.
  8682. This should only be called when a call to next() has just returned true.
  8683. */
  8684. const KeyType getKey() const
  8685. {
  8686. return entry != 0 ? entry->key : KeyType();
  8687. }
  8688. /** Returns the current item's value.
  8689. This should only be called when a call to next() has just returned true.
  8690. */
  8691. const ValueType getValue() const
  8692. {
  8693. return entry != 0 ? entry->value : ValueType();
  8694. }
  8695. private:
  8696. const HashMap& hashMap;
  8697. HashEntry* entry;
  8698. int index;
  8699. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Iterator);
  8700. };
  8701. private:
  8702. enum { defaultHashTableSize = 101 };
  8703. friend class Iterator;
  8704. Array <HashEntry*> slots;
  8705. int totalNumItems;
  8706. TypeOfCriticalSectionToUse lock;
  8707. int generateHashFor (KeyTypeParameter key) const
  8708. {
  8709. const int hash = HashFunctionToUse::generateHash (key, getNumSlots());
  8710. jassert (isPositiveAndBelow (hash, getNumSlots())); // your hash function is generating out-of-range numbers!
  8711. return hash;
  8712. }
  8713. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap);
  8714. };
  8715. #endif // __JUCE_HASHMAP_JUCEHEADER__
  8716. /*** End of inlined file: juce_HashMap.h ***/
  8717. #endif
  8718. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  8719. #endif
  8720. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  8721. #endif
  8722. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  8723. #endif
  8724. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8725. /*** Start of inlined file: juce_PropertySet.h ***/
  8726. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8727. #define __JUCE_PROPERTYSET_JUCEHEADER__
  8728. /*** Start of inlined file: juce_StringPairArray.h ***/
  8729. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8730. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8731. /*** Start of inlined file: juce_StringArray.h ***/
  8732. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  8733. #define __JUCE_STRINGARRAY_JUCEHEADER__
  8734. /**
  8735. A special array for holding a list of strings.
  8736. @see String, StringPairArray
  8737. */
  8738. class JUCE_API StringArray
  8739. {
  8740. public:
  8741. /** Creates an empty string array */
  8742. StringArray() throw();
  8743. /** Creates a copy of another string array */
  8744. StringArray (const StringArray& other);
  8745. /** Creates an array containing a single string. */
  8746. explicit StringArray (const String& firstValue);
  8747. /** Creates a copy of an array of string literals.
  8748. @param strings an array of strings to add. Null pointers in the array will be
  8749. treated as empty strings
  8750. @param numberOfStrings how many items there are in the array
  8751. */
  8752. StringArray (const char* const* strings, int numberOfStrings);
  8753. /** Creates a copy of a null-terminated array of string literals.
  8754. Each item from the array passed-in is added, until it encounters a null pointer,
  8755. at which point it stops.
  8756. */
  8757. explicit StringArray (const char* const* strings);
  8758. /** Creates a copy of a null-terminated array of string literals.
  8759. Each item from the array passed-in is added, until it encounters a null pointer,
  8760. at which point it stops.
  8761. */
  8762. explicit StringArray (const wchar_t* const* strings);
  8763. /** Creates a copy of an array of string literals.
  8764. @param strings an array of strings to add. Null pointers in the array will be
  8765. treated as empty strings
  8766. @param numberOfStrings how many items there are in the array
  8767. */
  8768. StringArray (const wchar_t* const* strings, int numberOfStrings);
  8769. /** Destructor. */
  8770. ~StringArray();
  8771. /** Copies the contents of another string array into this one */
  8772. StringArray& operator= (const StringArray& other);
  8773. /** Compares two arrays.
  8774. Comparisons are case-sensitive.
  8775. @returns true only if the other array contains exactly the same strings in the same order
  8776. */
  8777. bool operator== (const StringArray& other) const throw();
  8778. /** Compares two arrays.
  8779. Comparisons are case-sensitive.
  8780. @returns false if the other array contains exactly the same strings in the same order
  8781. */
  8782. bool operator!= (const StringArray& other) const throw();
  8783. /** Returns the number of strings in the array */
  8784. inline int size() const throw() { return strings.size(); };
  8785. /** Returns one of the strings from the array.
  8786. If the index is out-of-range, an empty string is returned.
  8787. Obviously the reference returned shouldn't be stored for later use, as the
  8788. string it refers to may disappear when the array changes.
  8789. */
  8790. const String& operator[] (int index) const throw();
  8791. /** Returns a reference to one of the strings in the array.
  8792. This lets you modify a string in-place in the array, but you must be sure that
  8793. the index is in-range.
  8794. */
  8795. String& getReference (int index) throw();
  8796. /** Searches for a string in the array.
  8797. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8798. @returns true if the string is found inside the array
  8799. */
  8800. bool contains (const String& stringToLookFor,
  8801. bool ignoreCase = false) const;
  8802. /** Searches for a string in the array.
  8803. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8804. @param stringToLookFor the string to try to find
  8805. @param ignoreCase whether the comparison should be case-insensitive
  8806. @param startIndex the first index to start searching from
  8807. @returns the index of the first occurrence of the string in this array,
  8808. or -1 if it isn't found.
  8809. */
  8810. int indexOf (const String& stringToLookFor,
  8811. bool ignoreCase = false,
  8812. int startIndex = 0) const;
  8813. /** Appends a string at the end of the array. */
  8814. void add (const String& stringToAdd);
  8815. /** Inserts a string into the array.
  8816. This will insert a string into the array at the given index, moving
  8817. up the other elements to make room for it.
  8818. If the index is less than zero or greater than the size of the array,
  8819. the new string will be added to the end of the array.
  8820. */
  8821. void insert (int index, const String& stringToAdd);
  8822. /** Adds a string to the array as long as it's not already in there.
  8823. The search can optionally be case-insensitive.
  8824. */
  8825. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  8826. /** Replaces one of the strings in the array with another one.
  8827. If the index is higher than the array's size, the new string will be
  8828. added to the end of the array; if it's less than zero nothing happens.
  8829. */
  8830. void set (int index, const String& newString);
  8831. /** Appends some strings from another array to the end of this one.
  8832. @param other the array to add
  8833. @param startIndex the first element of the other array to add
  8834. @param numElementsToAdd the maximum number of elements to add (if this is
  8835. less than zero, they are all added)
  8836. */
  8837. void addArray (const StringArray& other,
  8838. int startIndex = 0,
  8839. int numElementsToAdd = -1);
  8840. /** Breaks up a string into tokens and adds them to this array.
  8841. This will tokenise the given string using whitespace characters as the
  8842. token delimiters, and will add these tokens to the end of the array.
  8843. @returns the number of tokens added
  8844. */
  8845. int addTokens (const String& stringToTokenise,
  8846. bool preserveQuotedStrings);
  8847. /** Breaks up a string into tokens and adds them to this array.
  8848. This will tokenise the given string (using the string passed in to define the
  8849. token delimiters), and will add these tokens to the end of the array.
  8850. @param stringToTokenise the string to tokenise
  8851. @param breakCharacters a string of characters, any of which will be considered
  8852. to be a token delimiter.
  8853. @param quoteCharacters if this string isn't empty, it defines a set of characters
  8854. which are treated as quotes. Any text occurring
  8855. between quotes is not broken up into tokens.
  8856. @returns the number of tokens added
  8857. */
  8858. int addTokens (const String& stringToTokenise,
  8859. const String& breakCharacters,
  8860. const String& quoteCharacters);
  8861. /** Breaks up a string into lines and adds them to this array.
  8862. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  8863. to the array. Line-break characters are omitted from the strings that are added to
  8864. the array.
  8865. */
  8866. int addLines (const String& stringToBreakUp);
  8867. /** Removes all elements from the array. */
  8868. void clear();
  8869. /** Removes a string from the array.
  8870. If the index is out-of-range, no action will be taken.
  8871. */
  8872. void remove (int index);
  8873. /** Finds a string in the array and removes it.
  8874. This will remove the first occurrence of the given string from the array. The
  8875. comparison may be case-insensitive depending on the ignoreCase parameter.
  8876. */
  8877. void removeString (const String& stringToRemove,
  8878. bool ignoreCase = false);
  8879. /** Removes a range of elements from the array.
  8880. This will remove a set of elements, starting from the given index,
  8881. and move subsequent elements down to close the gap.
  8882. If the range extends beyond the bounds of the array, it will
  8883. be safely clipped to the size of the array.
  8884. @param startIndex the index of the first element to remove
  8885. @param numberToRemove how many elements should be removed
  8886. */
  8887. void removeRange (int startIndex, int numberToRemove);
  8888. /** Removes any duplicated elements from the array.
  8889. If any string appears in the array more than once, only the first occurrence of
  8890. it will be retained.
  8891. @param ignoreCase whether to use a case-insensitive comparison
  8892. */
  8893. void removeDuplicates (bool ignoreCase);
  8894. /** Removes empty strings from the array.
  8895. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8896. characters will also be removed
  8897. */
  8898. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8899. /** Moves one of the strings to a different position.
  8900. This will move the string to a specified index, shuffling along
  8901. any intervening elements as required.
  8902. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8903. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8904. @param currentIndex the index of the value to be moved. If this isn't a
  8905. valid index, then nothing will be done
  8906. @param newIndex the index at which you'd like this value to end up. If this
  8907. is less than zero, the value will be moved to the end
  8908. of the array
  8909. */
  8910. void move (int currentIndex, int newIndex) throw();
  8911. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8912. void trim();
  8913. /** Adds numbers to the strings in the array, to make each string unique.
  8914. This will add numbers to the ends of groups of similar strings.
  8915. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8916. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8917. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8918. also has a number appended to it.
  8919. @param preNumberString when adding a number, this string is added before the number.
  8920. If you pass 0, a default string will be used, which adds
  8921. brackets around the number.
  8922. @param postNumberString this string is appended after any numbers that are added.
  8923. If you pass 0, a default string will be used, which adds
  8924. brackets around the number.
  8925. */
  8926. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8927. bool appendNumberToFirstInstance,
  8928. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (0),
  8929. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (0));
  8930. /** Joins the strings in the array together into one string.
  8931. This will join a range of elements from the array into a string, separating
  8932. them with a given string.
  8933. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8934. @param separatorString the string to insert between all the strings
  8935. @param startIndex the first element to join
  8936. @param numberOfElements how many elements to join together. If this is less
  8937. than zero, all available elements will be used.
  8938. */
  8939. const String joinIntoString (const String& separatorString,
  8940. int startIndex = 0,
  8941. int numberOfElements = -1) const;
  8942. /** Sorts the array into alphabetical order.
  8943. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8944. */
  8945. void sort (bool ignoreCase);
  8946. /** Reduces the amount of storage being used by the array.
  8947. Arrays typically allocate slightly more storage than they need, and after
  8948. removing elements, they may have quite a lot of unused space allocated.
  8949. This method will reduce the amount of allocated storage to a minimum.
  8950. */
  8951. void minimiseStorageOverheads();
  8952. private:
  8953. Array <String> strings;
  8954. JUCE_LEAK_DETECTOR (StringArray);
  8955. };
  8956. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  8957. /*** End of inlined file: juce_StringArray.h ***/
  8958. /**
  8959. A container for holding a set of strings which are keyed by another string.
  8960. @see StringArray
  8961. */
  8962. class JUCE_API StringPairArray
  8963. {
  8964. public:
  8965. /** Creates an empty array */
  8966. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  8967. /** Creates a copy of another array */
  8968. StringPairArray (const StringPairArray& other);
  8969. /** Destructor. */
  8970. ~StringPairArray();
  8971. /** Copies the contents of another string array into this one */
  8972. StringPairArray& operator= (const StringPairArray& other);
  8973. /** Compares two arrays.
  8974. Comparisons are case-sensitive.
  8975. @returns true only if the other array contains exactly the same strings with the same keys
  8976. */
  8977. bool operator== (const StringPairArray& other) const;
  8978. /** Compares two arrays.
  8979. Comparisons are case-sensitive.
  8980. @returns false if the other array contains exactly the same strings with the same keys
  8981. */
  8982. bool operator!= (const StringPairArray& other) const;
  8983. /** Finds the value corresponding to a key string.
  8984. If no such key is found, this will just return an empty string. To check whether
  8985. a given key actually exists (because it might actually be paired with an empty string), use
  8986. the getAllKeys() method to obtain a list.
  8987. Obviously the reference returned shouldn't be stored for later use, as the
  8988. string it refers to may disappear when the array changes.
  8989. @see getValue
  8990. */
  8991. const String& operator[] (const String& key) const;
  8992. /** Finds the value corresponding to a key string.
  8993. If no such key is found, this will just return the value provided as a default.
  8994. @see operator[]
  8995. */
  8996. const String getValue (const String& key, const String& defaultReturnValue) const;
  8997. /** Returns a list of all keys in the array. */
  8998. const StringArray& getAllKeys() const throw() { return keys; }
  8999. /** Returns a list of all values in the array. */
  9000. const StringArray& getAllValues() const throw() { return values; }
  9001. /** Returns the number of strings in the array */
  9002. inline int size() const throw() { return keys.size(); };
  9003. /** Adds or amends a key/value pair.
  9004. If a value already exists with this key, its value will be overwritten,
  9005. otherwise the key/value pair will be added to the array.
  9006. */
  9007. void set (const String& key, const String& value);
  9008. /** Adds the items from another array to this one.
  9009. This is equivalent to using set() to add each of the pairs from the other array.
  9010. */
  9011. void addArray (const StringPairArray& other);
  9012. /** Removes all elements from the array. */
  9013. void clear();
  9014. /** Removes a string from the array based on its key.
  9015. If the key isn't found, nothing will happen.
  9016. */
  9017. void remove (const String& key);
  9018. /** Removes a string from the array based on its index.
  9019. If the index is out-of-range, no action will be taken.
  9020. */
  9021. void remove (int index);
  9022. /** Indicates whether to use a case-insensitive search when looking up a key string.
  9023. */
  9024. void setIgnoresCase (bool shouldIgnoreCase);
  9025. /** Returns a descriptive string containing the items.
  9026. This is handy for dumping the contents of an array.
  9027. */
  9028. const String getDescription() const;
  9029. /** Reduces the amount of storage being used by the array.
  9030. Arrays typically allocate slightly more storage than they need, and after
  9031. removing elements, they may have quite a lot of unused space allocated.
  9032. This method will reduce the amount of allocated storage to a minimum.
  9033. */
  9034. void minimiseStorageOverheads();
  9035. private:
  9036. StringArray keys, values;
  9037. bool ignoreCase;
  9038. JUCE_LEAK_DETECTOR (StringPairArray);
  9039. };
  9040. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  9041. /*** End of inlined file: juce_StringPairArray.h ***/
  9042. /*** Start of inlined file: juce_XmlElement.h ***/
  9043. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  9044. #define __JUCE_XMLELEMENT_JUCEHEADER__
  9045. /*** Start of inlined file: juce_File.h ***/
  9046. #ifndef __JUCE_FILE_JUCEHEADER__
  9047. #define __JUCE_FILE_JUCEHEADER__
  9048. /*** Start of inlined file: juce_Time.h ***/
  9049. #ifndef __JUCE_TIME_JUCEHEADER__
  9050. #define __JUCE_TIME_JUCEHEADER__
  9051. /*** Start of inlined file: juce_RelativeTime.h ***/
  9052. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  9053. #define __JUCE_RELATIVETIME_JUCEHEADER__
  9054. /** A relative measure of time.
  9055. The time is stored as a number of seconds, at double-precision floating
  9056. point accuracy, and may be positive or negative.
  9057. If you need an absolute time, (i.e. a date + time), see the Time class.
  9058. */
  9059. class JUCE_API RelativeTime
  9060. {
  9061. public:
  9062. /** Creates a RelativeTime.
  9063. @param seconds the number of seconds, which may be +ve or -ve.
  9064. @see milliseconds, minutes, hours, days, weeks
  9065. */
  9066. explicit RelativeTime (double seconds = 0.0) throw();
  9067. /** Copies another relative time. */
  9068. RelativeTime (const RelativeTime& other) throw();
  9069. /** Copies another relative time. */
  9070. RelativeTime& operator= (const RelativeTime& other) throw();
  9071. /** Destructor. */
  9072. ~RelativeTime() throw();
  9073. /** Creates a new RelativeTime object representing a number of milliseconds.
  9074. @see minutes, hours, days, weeks
  9075. */
  9076. static const RelativeTime milliseconds (int milliseconds) throw();
  9077. /** Creates a new RelativeTime object representing a number of milliseconds.
  9078. @see minutes, hours, days, weeks
  9079. */
  9080. static const RelativeTime milliseconds (int64 milliseconds) throw();
  9081. /** Creates a new RelativeTime object representing a number of minutes.
  9082. @see milliseconds, hours, days, weeks
  9083. */
  9084. static const RelativeTime minutes (double numberOfMinutes) throw();
  9085. /** Creates a new RelativeTime object representing a number of hours.
  9086. @see milliseconds, minutes, days, weeks
  9087. */
  9088. static const RelativeTime hours (double numberOfHours) throw();
  9089. /** Creates a new RelativeTime object representing a number of days.
  9090. @see milliseconds, minutes, hours, weeks
  9091. */
  9092. static const RelativeTime days (double numberOfDays) throw();
  9093. /** Creates a new RelativeTime object representing a number of weeks.
  9094. @see milliseconds, minutes, hours, days
  9095. */
  9096. static const RelativeTime weeks (double numberOfWeeks) throw();
  9097. /** Returns the number of milliseconds this time represents.
  9098. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9099. */
  9100. int64 inMilliseconds() const throw();
  9101. /** Returns the number of seconds this time represents.
  9102. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  9103. */
  9104. double inSeconds() const throw() { return seconds; }
  9105. /** Returns the number of minutes this time represents.
  9106. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  9107. */
  9108. double inMinutes() const throw();
  9109. /** Returns the number of hours this time represents.
  9110. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  9111. */
  9112. double inHours() const throw();
  9113. /** Returns the number of days this time represents.
  9114. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  9115. */
  9116. double inDays() const throw();
  9117. /** Returns the number of weeks this time represents.
  9118. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  9119. */
  9120. double inWeeks() const throw();
  9121. /** Returns a readable textual description of the time.
  9122. The exact format of the string returned will depend on
  9123. the magnitude of the time - e.g.
  9124. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  9125. so that only the two most significant units are printed.
  9126. The returnValueForZeroTime value is the result that is returned if the
  9127. length is zero. Depending on your application you might want to use this
  9128. to return something more relevant like "empty" or "0 secs", etc.
  9129. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  9130. */
  9131. const String getDescription (const String& returnValueForZeroTime = "0") const;
  9132. /** Adds another RelativeTime to this one. */
  9133. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  9134. /** Subtracts another RelativeTime from this one. */
  9135. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  9136. /** Adds a number of seconds to this time. */
  9137. const RelativeTime& operator+= (double secondsToAdd) throw();
  9138. /** Subtracts a number of seconds from this time. */
  9139. const RelativeTime& operator-= (double secondsToSubtract) throw();
  9140. private:
  9141. double seconds;
  9142. };
  9143. /** Compares two RelativeTimes. */
  9144. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw();
  9145. /** Compares two RelativeTimes. */
  9146. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw();
  9147. /** Compares two RelativeTimes. */
  9148. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw();
  9149. /** Compares two RelativeTimes. */
  9150. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw();
  9151. /** Compares two RelativeTimes. */
  9152. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw();
  9153. /** Compares two RelativeTimes. */
  9154. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw();
  9155. /** Adds two RelativeTimes together. */
  9156. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw();
  9157. /** Subtracts two RelativeTimes. */
  9158. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw();
  9159. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  9160. /*** End of inlined file: juce_RelativeTime.h ***/
  9161. /**
  9162. Holds an absolute date and time.
  9163. Internally, the time is stored at millisecond precision.
  9164. @see RelativeTime
  9165. */
  9166. class JUCE_API Time
  9167. {
  9168. public:
  9169. /** Creates a Time object.
  9170. This default constructor creates a time of 1st January 1970, (which is
  9171. represented internally as 0ms).
  9172. To create a time object representing the current time, use getCurrentTime().
  9173. @see getCurrentTime
  9174. */
  9175. Time() throw();
  9176. /** Creates a time based on a number of milliseconds.
  9177. The internal millisecond count is set to 0 (1st January 1970). To create a
  9178. time object set to the current time, use getCurrentTime().
  9179. @param millisecondsSinceEpoch the number of milliseconds since the unix
  9180. 'epoch' (midnight Jan 1st 1970).
  9181. @see getCurrentTime, currentTimeMillis
  9182. */
  9183. explicit Time (int64 millisecondsSinceEpoch) throw();
  9184. /** Creates a time from a set of date components.
  9185. The timezone is assumed to be whatever the system is using as its locale.
  9186. @param year the year, in 4-digit format, e.g. 2004
  9187. @param month the month, in the range 0 to 11
  9188. @param day the day of the month, in the range 1 to 31
  9189. @param hours hours in 24-hour clock format, 0 to 23
  9190. @param minutes minutes 0 to 59
  9191. @param seconds seconds 0 to 59
  9192. @param milliseconds milliseconds 0 to 999
  9193. @param useLocalTime if true, encode using the current machine's local time; if
  9194. false, it will always work in GMT.
  9195. */
  9196. Time (int year,
  9197. int month,
  9198. int day,
  9199. int hours,
  9200. int minutes,
  9201. int seconds = 0,
  9202. int milliseconds = 0,
  9203. bool useLocalTime = true) throw();
  9204. /** Creates a copy of another Time object. */
  9205. Time (const Time& other) throw();
  9206. /** Destructor. */
  9207. ~Time() throw();
  9208. /** Copies this time from another one. */
  9209. Time& operator= (const Time& other) throw();
  9210. /** Returns a Time object that is set to the current system time.
  9211. @see currentTimeMillis
  9212. */
  9213. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  9214. /** Returns the time as a number of milliseconds.
  9215. @returns the number of milliseconds this Time object represents, since
  9216. midnight jan 1st 1970.
  9217. @see getMilliseconds
  9218. */
  9219. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  9220. /** Returns the year.
  9221. A 4-digit format is used, e.g. 2004.
  9222. */
  9223. int getYear() const throw();
  9224. /** Returns the number of the month.
  9225. The value returned is in the range 0 to 11.
  9226. @see getMonthName
  9227. */
  9228. int getMonth() const throw();
  9229. /** Returns the name of the month.
  9230. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9231. it'll return the long form, e.g. "January"
  9232. @see getMonth
  9233. */
  9234. const String getMonthName (bool threeLetterVersion) const;
  9235. /** Returns the day of the month.
  9236. The value returned is in the range 1 to 31.
  9237. */
  9238. int getDayOfMonth() const throw();
  9239. /** Returns the number of the day of the week.
  9240. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  9241. */
  9242. int getDayOfWeek() const throw();
  9243. /** Returns the name of the weekday.
  9244. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9245. false, it'll return the full version, e.g. "Tuesday".
  9246. */
  9247. const String getWeekdayName (bool threeLetterVersion) const;
  9248. /** Returns the number of hours since midnight.
  9249. This is in 24-hour clock format, in the range 0 to 23.
  9250. @see getHoursInAmPmFormat, isAfternoon
  9251. */
  9252. int getHours() const throw();
  9253. /** Returns true if the time is in the afternoon.
  9254. So it returns true for "PM", false for "AM".
  9255. @see getHoursInAmPmFormat, getHours
  9256. */
  9257. bool isAfternoon() const throw();
  9258. /** Returns the hours in 12-hour clock format.
  9259. This will return a value 1 to 12 - use isAfternoon() to find out
  9260. whether this is in the afternoon or morning.
  9261. @see getHours, isAfternoon
  9262. */
  9263. int getHoursInAmPmFormat() const throw();
  9264. /** Returns the number of minutes, 0 to 59. */
  9265. int getMinutes() const throw();
  9266. /** Returns the number of seconds, 0 to 59. */
  9267. int getSeconds() const throw();
  9268. /** Returns the number of milliseconds, 0 to 999.
  9269. Unlike toMilliseconds(), this just returns the position within the
  9270. current second rather than the total number since the epoch.
  9271. @see toMilliseconds
  9272. */
  9273. int getMilliseconds() const throw();
  9274. /** Returns true if the local timezone uses a daylight saving correction. */
  9275. bool isDaylightSavingTime() const throw();
  9276. /** Returns a 3-character string to indicate the local timezone. */
  9277. const String getTimeZone() const throw();
  9278. /** Quick way of getting a string version of a date and time.
  9279. For a more powerful way of formatting the date and time, see the formatted() method.
  9280. @param includeDate whether to include the date in the string
  9281. @param includeTime whether to include the time in the string
  9282. @param includeSeconds if the time is being included, this provides an option not to include
  9283. the seconds in it
  9284. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  9285. hour notation.
  9286. @see formatted
  9287. */
  9288. const String toString (bool includeDate,
  9289. bool includeTime,
  9290. bool includeSeconds = true,
  9291. bool use24HourClock = false) const throw();
  9292. /** Converts this date/time to a string with a user-defined format.
  9293. This uses the C strftime() function to format this time as a string. To save you
  9294. looking it up, these are the escape codes that strftime uses (other codes might
  9295. work on some platforms and not others, but these are the common ones):
  9296. %a is replaced by the locale's abbreviated weekday name.
  9297. %A is replaced by the locale's full weekday name.
  9298. %b is replaced by the locale's abbreviated month name.
  9299. %B is replaced by the locale's full month name.
  9300. %c is replaced by the locale's appropriate date and time representation.
  9301. %d is replaced by the day of the month as a decimal number [01,31].
  9302. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  9303. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  9304. %j is replaced by the day of the year as a decimal number [001,366].
  9305. %m is replaced by the month as a decimal number [01,12].
  9306. %M is replaced by the minute as a decimal number [00,59].
  9307. %p is replaced by the locale's equivalent of either a.m. or p.m.
  9308. %S is replaced by the second as a decimal number [00,61].
  9309. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  9310. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  9311. %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.
  9312. %x is replaced by the locale's appropriate date representation.
  9313. %X is replaced by the locale's appropriate time representation.
  9314. %y is replaced by the year without century as a decimal number [00,99].
  9315. %Y is replaced by the year with century as a decimal number.
  9316. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  9317. %% is replaced by %.
  9318. @see toString
  9319. */
  9320. const String formatted (const String& format) const;
  9321. /** Adds a RelativeTime to this time. */
  9322. Time& operator+= (const RelativeTime& delta);
  9323. /** Subtracts a RelativeTime from this time. */
  9324. Time& operator-= (const RelativeTime& delta);
  9325. /** Tries to set the computer's clock.
  9326. @returns true if this succeeds, although depending on the system, the
  9327. application might not have sufficient privileges to do this.
  9328. */
  9329. bool setSystemTimeToThisTime() const;
  9330. /** Returns the name of a day of the week.
  9331. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  9332. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  9333. false, it'll return the full version, e.g. "Tuesday".
  9334. */
  9335. static const String getWeekdayName (int dayNumber,
  9336. bool threeLetterVersion);
  9337. /** Returns the name of one of the months.
  9338. @param monthNumber the month, 0 to 11
  9339. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  9340. it'll return the long form, e.g. "January"
  9341. */
  9342. static const String getMonthName (int monthNumber,
  9343. bool threeLetterVersion);
  9344. // Static methods for getting system timers directly..
  9345. /** Returns the current system time.
  9346. Returns the number of milliseconds since midnight jan 1st 1970.
  9347. Should be accurate to within a few millisecs, depending on platform,
  9348. hardware, etc.
  9349. */
  9350. static int64 currentTimeMillis() throw();
  9351. /** Returns the number of millisecs since a fixed event (usually system startup).
  9352. This returns a monotonically increasing value which it unaffected by changes to the
  9353. system clock. It should be accurate to within a few millisecs, depending on platform,
  9354. hardware, etc.
  9355. @see getApproximateMillisecondCounter
  9356. */
  9357. static uint32 getMillisecondCounter() throw();
  9358. /** Returns the number of millisecs since a fixed event (usually system startup).
  9359. This has the same function as getMillisecondCounter(), but returns a more accurate
  9360. value, using a higher-resolution timer if one is available.
  9361. @see getMillisecondCounter
  9362. */
  9363. static double getMillisecondCounterHiRes() throw();
  9364. /** Waits until the getMillisecondCounter() reaches a given value.
  9365. This will make the thread sleep as efficiently as it can while it's waiting.
  9366. */
  9367. static void waitForMillisecondCounter (uint32 targetTime) throw();
  9368. /** Less-accurate but faster version of getMillisecondCounter().
  9369. This will return the last value that getMillisecondCounter() returned, so doesn't
  9370. need to make a system call, but is less accurate - it shouldn't be more than
  9371. 100ms away from the correct time, though, so is still accurate enough for a
  9372. lot of purposes.
  9373. @see getMillisecondCounter
  9374. */
  9375. static uint32 getApproximateMillisecondCounter() throw();
  9376. // High-resolution timers..
  9377. /** Returns the current high-resolution counter's tick-count.
  9378. This is a similar idea to getMillisecondCounter(), but with a higher
  9379. resolution.
  9380. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  9381. secondsToHighResolutionTicks
  9382. */
  9383. static int64 getHighResolutionTicks() throw();
  9384. /** Returns the resolution of the high-resolution counter in ticks per second.
  9385. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  9386. secondsToHighResolutionTicks
  9387. */
  9388. static int64 getHighResolutionTicksPerSecond() throw();
  9389. /** Converts a number of high-resolution ticks into seconds.
  9390. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9391. secondsToHighResolutionTicks
  9392. */
  9393. static double highResolutionTicksToSeconds (int64 ticks) throw();
  9394. /** Converts a number seconds into high-resolution ticks.
  9395. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  9396. highResolutionTicksToSeconds
  9397. */
  9398. static int64 secondsToHighResolutionTicks (double seconds) throw();
  9399. private:
  9400. int64 millisSinceEpoch;
  9401. };
  9402. /** Adds a RelativeTime to a Time. */
  9403. JUCE_API const Time operator+ (const Time& time, const RelativeTime& delta);
  9404. /** Adds a RelativeTime to a Time. */
  9405. JUCE_API const Time operator+ (const RelativeTime& delta, const Time& time);
  9406. /** Subtracts a RelativeTime from a Time. */
  9407. JUCE_API const Time operator- (const Time& time, const RelativeTime& delta);
  9408. /** Returns the relative time difference between two times. */
  9409. JUCE_API const RelativeTime operator- (const Time& time1, const Time& time2);
  9410. /** Compares two Time objects. */
  9411. JUCE_API bool operator== (const Time& time1, const Time& time2);
  9412. /** Compares two Time objects. */
  9413. JUCE_API bool operator!= (const Time& time1, const Time& time2);
  9414. /** Compares two Time objects. */
  9415. JUCE_API bool operator< (const Time& time1, const Time& time2);
  9416. /** Compares two Time objects. */
  9417. JUCE_API bool operator<= (const Time& time1, const Time& time2);
  9418. /** Compares two Time objects. */
  9419. JUCE_API bool operator> (const Time& time1, const Time& time2);
  9420. /** Compares two Time objects. */
  9421. JUCE_API bool operator>= (const Time& time1, const Time& time2);
  9422. #endif // __JUCE_TIME_JUCEHEADER__
  9423. /*** End of inlined file: juce_Time.h ***/
  9424. class FileInputStream;
  9425. class FileOutputStream;
  9426. /**
  9427. Represents a local file or directory.
  9428. This class encapsulates the absolute pathname of a file or directory, and
  9429. has methods for finding out about the file and changing its properties.
  9430. To read or write to the file, there are methods for returning an input or
  9431. output stream.
  9432. @see FileInputStream, FileOutputStream
  9433. */
  9434. class JUCE_API File
  9435. {
  9436. public:
  9437. /** Creates an (invalid) file object.
  9438. The file is initially set to an empty path, so getFullPath() will return
  9439. an empty string, and comparing the file to File::nonexistent will return
  9440. true.
  9441. You can use its operator= method to point it at a proper file.
  9442. */
  9443. File() {}
  9444. /** Creates a file from an absolute path.
  9445. If the path supplied is a relative path, it is taken to be relative
  9446. to the current working directory (see File::getCurrentWorkingDirectory()),
  9447. but this isn't a recommended way of creating a file, because you
  9448. never know what the CWD is going to be.
  9449. On the Mac/Linux, the path can include "~" notation for referring to
  9450. user home directories.
  9451. */
  9452. File (const String& path);
  9453. /** Creates a copy of another file object. */
  9454. File (const File& other);
  9455. /** Destructor. */
  9456. ~File() {}
  9457. /** Sets the file based on an absolute pathname.
  9458. If the path supplied is a relative path, it is taken to be relative
  9459. to the current working directory (see File::getCurrentWorkingDirectory()),
  9460. but this isn't a recommended way of creating a file, because you
  9461. never know what the CWD is going to be.
  9462. On the Mac/Linux, the path can include "~" notation for referring to
  9463. user home directories.
  9464. */
  9465. File& operator= (const String& newFilePath);
  9466. /** Copies from another file object. */
  9467. File& operator= (const File& otherFile);
  9468. /** This static constant is used for referring to an 'invalid' file. */
  9469. static const File nonexistent;
  9470. /** Checks whether the file actually exists.
  9471. @returns true if the file exists, either as a file or a directory.
  9472. @see existsAsFile, isDirectory
  9473. */
  9474. bool exists() const;
  9475. /** Checks whether the file exists and is a file rather than a directory.
  9476. @returns true only if this is a real file, false if it's a directory
  9477. or doesn't exist
  9478. @see exists, isDirectory
  9479. */
  9480. bool existsAsFile() const;
  9481. /** Checks whether the file is a directory that exists.
  9482. @returns true only if the file is a directory which actually exists, so
  9483. false if it's a file or doesn't exist at all
  9484. @see exists, existsAsFile
  9485. */
  9486. bool isDirectory() const;
  9487. /** Returns the size of the file in bytes.
  9488. @returns the number of bytes in the file, or 0 if it doesn't exist.
  9489. */
  9490. int64 getSize() const;
  9491. /** Utility function to convert a file size in bytes to a neat string description.
  9492. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  9493. 2000000 would produce "2 MB", etc.
  9494. */
  9495. static const String descriptionOfSizeInBytes (int64 bytes);
  9496. /** Returns the complete, absolute path of this file.
  9497. This includes the filename and all its parent folders. On Windows it'll
  9498. also include the drive letter prefix; on Mac or Linux it'll be a complete
  9499. path starting from the root folder.
  9500. If you just want the file's name, you should use getFileName() or
  9501. getFileNameWithoutExtension().
  9502. @see getFileName, getRelativePathFrom
  9503. */
  9504. const String& getFullPathName() const throw() { return fullPath; }
  9505. /** Returns the last section of the pathname.
  9506. Returns just the final part of the path - e.g. if the whole path
  9507. is "/moose/fish/foo.txt" this will return "foo.txt".
  9508. For a directory, it returns the final part of the path - e.g. for the
  9509. directory "/moose/fish" it'll return "fish".
  9510. If the filename begins with a dot, it'll return the whole filename, e.g. for
  9511. "/moose/.fish", it'll return ".fish"
  9512. @see getFullPathName, getFileNameWithoutExtension
  9513. */
  9514. const String getFileName() const;
  9515. /** Creates a relative path that refers to a file relatively to a given directory.
  9516. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  9517. would return "../../foo.txt".
  9518. If it's not possible to navigate from one file to the other, an absolute
  9519. path is returned. If the paths are invalid, an empty string may also be
  9520. returned.
  9521. @param directoryToBeRelativeTo the directory which the resultant string will
  9522. be relative to. If this is actually a file rather than
  9523. a directory, its parent directory will be used instead.
  9524. If it doesn't exist, it's assumed to be a directory.
  9525. @see getChildFile, isAbsolutePath
  9526. */
  9527. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  9528. /** Returns the file's extension.
  9529. Returns the file extension of this file, also including the dot.
  9530. e.g. "/moose/fish/foo.txt" would return ".txt"
  9531. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  9532. */
  9533. const String getFileExtension() const;
  9534. /** Checks whether the file has a given extension.
  9535. @param extensionToTest the extension to look for - it doesn't matter whether or
  9536. not this string has a dot at the start, so ".wav" and "wav"
  9537. will have the same effect. The comparison used is
  9538. case-insensitve. To compare with multiple extensions, this
  9539. parameter can contain multiple strings, separated by semi-colons -
  9540. so, for example: hasFileExtension (".jpeg;png;gif") would return
  9541. true if the file has any of those three extensions.
  9542. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  9543. */
  9544. bool hasFileExtension (const String& extensionToTest) const;
  9545. /** Returns a version of this file with a different file extension.
  9546. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  9547. @param newExtension the new extension, either with or without a dot at the start (this
  9548. doesn't make any difference). To get remove a file's extension altogether,
  9549. pass an empty string into this function.
  9550. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  9551. */
  9552. const File withFileExtension (const String& newExtension) const;
  9553. /** Returns the last part of the filename, without its file extension.
  9554. e.g. for "/moose/fish/foo.txt" this will return "foo".
  9555. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  9556. */
  9557. const String getFileNameWithoutExtension() const;
  9558. /** Returns a 32-bit hash-code that identifies this file.
  9559. This is based on the filename. Obviously it's possible, although unlikely, that
  9560. two files will have the same hash-code.
  9561. */
  9562. int hashCode() const;
  9563. /** Returns a 64-bit hash-code that identifies this file.
  9564. This is based on the filename. Obviously it's possible, although unlikely, that
  9565. two files will have the same hash-code.
  9566. */
  9567. int64 hashCode64() const;
  9568. /** Returns a file based on a relative path.
  9569. This will find a child file or directory of the current object.
  9570. e.g.
  9571. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  9572. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  9573. If the string is actually an absolute path, it will be treated as such, e.g.
  9574. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  9575. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  9576. */
  9577. const File getChildFile (String relativePath) const;
  9578. /** Returns a file which is in the same directory as this one.
  9579. This is equivalent to getParentDirectory().getChildFile (name).
  9580. @see getChildFile, getParentDirectory
  9581. */
  9582. const File getSiblingFile (const String& siblingFileName) const;
  9583. /** Returns the directory that contains this file or directory.
  9584. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  9585. */
  9586. const File getParentDirectory() const;
  9587. /** Checks whether a file is somewhere inside a directory.
  9588. Returns true if this file is somewhere inside a subdirectory of the directory
  9589. that is passed in. Neither file actually has to exist, because the function
  9590. just checks the paths for similarities.
  9591. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  9592. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  9593. */
  9594. bool isAChildOf (const File& potentialParentDirectory) const;
  9595. /** Chooses a filename relative to this one that doesn't already exist.
  9596. If this file is a directory, this will return a child file of this
  9597. directory that doesn't exist, by adding numbers to a prefix and suffix until
  9598. it finds one that isn't already there.
  9599. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  9600. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  9601. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  9602. @param prefix the string to use for the filename before the number
  9603. @param suffix the string to add to the filename after the number
  9604. @param putNumbersInBrackets if true, this will create filenames in the
  9605. format "prefix(number)suffix", if false, it will leave the
  9606. brackets out.
  9607. */
  9608. const File getNonexistentChildFile (const String& prefix,
  9609. const String& suffix,
  9610. bool putNumbersInBrackets = true) const;
  9611. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  9612. If this file doesn't exist, this will just return itself, otherwise it
  9613. will return an appropriate sibling that doesn't exist, e.g. if a file
  9614. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  9615. @param putNumbersInBrackets whether to add brackets around the numbers that
  9616. get appended to the new filename.
  9617. */
  9618. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  9619. /** Compares the pathnames for two files. */
  9620. bool operator== (const File& otherFile) const;
  9621. /** Compares the pathnames for two files. */
  9622. bool operator!= (const File& otherFile) const;
  9623. /** Compares the pathnames for two files. */
  9624. bool operator< (const File& otherFile) const;
  9625. /** Compares the pathnames for two files. */
  9626. bool operator> (const File& otherFile) const;
  9627. /** Checks whether a file can be created or written to.
  9628. @returns true if it's possible to create and write to this file. If the file
  9629. doesn't already exist, this will check its parent directory to
  9630. see if writing is allowed.
  9631. @see setReadOnly
  9632. */
  9633. bool hasWriteAccess() const;
  9634. /** Changes the write-permission of a file or directory.
  9635. @param shouldBeReadOnly whether to add or remove write-permission
  9636. @param applyRecursively if the file is a directory and this is true, it will
  9637. recurse through all the subfolders changing the permissions
  9638. of all files
  9639. @returns true if it manages to change the file's permissions.
  9640. @see hasWriteAccess
  9641. */
  9642. bool setReadOnly (bool shouldBeReadOnly,
  9643. bool applyRecursively = false) const;
  9644. /** Returns true if this file is a hidden or system file.
  9645. The criteria for deciding whether a file is hidden are platform-dependent.
  9646. */
  9647. bool isHidden() const;
  9648. /** If this file is a link, this returns the file that it points to.
  9649. If this file isn't actually link, it'll just return itself.
  9650. */
  9651. const File getLinkedTarget() const;
  9652. /** Returns the last modification time of this file.
  9653. @returns the time, or an invalid time if the file doesn't exist.
  9654. @see setLastModificationTime, getLastAccessTime, getCreationTime
  9655. */
  9656. const Time getLastModificationTime() const;
  9657. /** Returns the last time this file was accessed.
  9658. @returns the time, or an invalid time if the file doesn't exist.
  9659. @see setLastAccessTime, getLastModificationTime, getCreationTime
  9660. */
  9661. const Time getLastAccessTime() const;
  9662. /** Returns the time that this file was created.
  9663. @returns the time, or an invalid time if the file doesn't exist.
  9664. @see getLastModificationTime, getLastAccessTime
  9665. */
  9666. const Time getCreationTime() const;
  9667. /** Changes the modification time for this file.
  9668. @param newTime the time to apply to the file
  9669. @returns true if it manages to change the file's time.
  9670. @see getLastModificationTime, setLastAccessTime, setCreationTime
  9671. */
  9672. bool setLastModificationTime (const Time& newTime) const;
  9673. /** Changes the last-access time for this file.
  9674. @param newTime the time to apply to the file
  9675. @returns true if it manages to change the file's time.
  9676. @see getLastAccessTime, setLastModificationTime, setCreationTime
  9677. */
  9678. bool setLastAccessTime (const Time& newTime) const;
  9679. /** Changes the creation date for this file.
  9680. @param newTime the time to apply to the file
  9681. @returns true if it manages to change the file's time.
  9682. @see getCreationTime, setLastModificationTime, setLastAccessTime
  9683. */
  9684. bool setCreationTime (const Time& newTime) const;
  9685. /** If possible, this will try to create a version string for the given file.
  9686. The OS may be able to look at the file and give a version for it - e.g. with
  9687. executables, bundles, dlls, etc. If no version is available, this will
  9688. return an empty string.
  9689. */
  9690. const String getVersion() const;
  9691. /** Creates an empty file if it doesn't already exist.
  9692. If the file that this object refers to doesn't exist, this will create a file
  9693. of zero size.
  9694. If it already exists or is a directory, this method will do nothing.
  9695. @returns true if the file has been created (or if it already existed).
  9696. @see createDirectory
  9697. */
  9698. bool create() const;
  9699. /** Creates a new directory for this filename.
  9700. This will try to create the file as a directory, and fill also create
  9701. any parent directories it needs in order to complete the operation.
  9702. @returns true if the directory has been created successfully, (or if it
  9703. already existed beforehand).
  9704. @see create
  9705. */
  9706. bool createDirectory() const;
  9707. /** Deletes a file.
  9708. If this file is actually a directory, it may not be deleted correctly if it
  9709. contains files. See deleteRecursively() as a better way of deleting directories.
  9710. @returns true if the file has been successfully deleted (or if it didn't exist to
  9711. begin with).
  9712. @see deleteRecursively
  9713. */
  9714. bool deleteFile() const;
  9715. /** Deletes a file or directory and all its subdirectories.
  9716. If this file is a directory, this will try to delete it and all its subfolders. If
  9717. it's just a file, it will just try to delete the file.
  9718. @returns true if the file and all its subfolders have been successfully deleted
  9719. (or if it didn't exist to begin with).
  9720. @see deleteFile
  9721. */
  9722. bool deleteRecursively() const;
  9723. /** Moves this file or folder to the trash.
  9724. @returns true if the operation succeeded. It could fail if the trash is full, or
  9725. if the file is write-protected, so you should check the return value
  9726. and act appropriately.
  9727. */
  9728. bool moveToTrash() const;
  9729. /** Moves or renames a file.
  9730. Tries to move a file to a different location.
  9731. If the target file already exists, this will attempt to delete it first, and
  9732. will fail if this can't be done.
  9733. Note that the destination file isn't the directory to put it in, it's the actual
  9734. filename that you want the new file to have.
  9735. @returns true if the operation succeeds
  9736. */
  9737. bool moveFileTo (const File& targetLocation) const;
  9738. /** Copies a file.
  9739. Tries to copy a file to a different location.
  9740. If the target file already exists, this will attempt to delete it first, and
  9741. will fail if this can't be done.
  9742. @returns true if the operation succeeds
  9743. */
  9744. bool copyFileTo (const File& targetLocation) const;
  9745. /** Copies a directory.
  9746. Tries to copy an entire directory, recursively.
  9747. If this file isn't a directory or if any target files can't be created, this
  9748. will return false.
  9749. @param newDirectory the directory that this one should be copied to. Note that this
  9750. is the name of the actual directory to create, not the directory
  9751. into which the new one should be placed, so there must be enough
  9752. write privileges to create it if it doesn't exist. Any files inside
  9753. it will be overwritten by similarly named ones that are copied.
  9754. */
  9755. bool copyDirectoryTo (const File& newDirectory) const;
  9756. /** Used in file searching, to specify whether to return files, directories, or both.
  9757. */
  9758. enum TypesOfFileToFind
  9759. {
  9760. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9761. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9762. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9763. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9764. };
  9765. /** Searches inside a directory for files matching a wildcard pattern.
  9766. Assuming that this file is a directory, this method will search it
  9767. for either files or subdirectories whose names match a filename pattern.
  9768. @param results an array to which File objects will be added for the
  9769. files that the search comes up with
  9770. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9771. return files, directories, or both. If the ignoreHiddenFiles flag
  9772. is also added to this value, hidden files won't be returned
  9773. @param searchRecursively if true, all subdirectories will be recursed into to do
  9774. an exhaustive search
  9775. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9776. @returns the number of results that have been found
  9777. @see getNumberOfChildFiles, DirectoryIterator
  9778. */
  9779. int findChildFiles (Array<File>& results,
  9780. int whatToLookFor,
  9781. bool searchRecursively,
  9782. const String& wildCardPattern = "*") const;
  9783. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9784. Assuming that this file is a directory, this method will search it
  9785. for either files or subdirectories whose names match a filename pattern,
  9786. and will return the number of matches found.
  9787. This isn't a recursive call, and will only search this directory, not
  9788. its children.
  9789. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9790. count files, directories, or both. If the ignoreHiddenFiles flag
  9791. is also added to this value, hidden files won't be counted
  9792. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9793. @returns the number of matches found
  9794. @see findChildFiles, DirectoryIterator
  9795. */
  9796. int getNumberOfChildFiles (int whatToLookFor,
  9797. const String& wildCardPattern = "*") const;
  9798. /** Returns true if this file is a directory that contains one or more subdirectories.
  9799. @see isDirectory, findChildFiles
  9800. */
  9801. bool containsSubDirectories() const;
  9802. /** Creates a stream to read from this file.
  9803. @returns a stream that will read from this file (initially positioned at the
  9804. start of the file), or 0 if the file can't be opened for some reason
  9805. @see createOutputStream, loadFileAsData
  9806. */
  9807. FileInputStream* createInputStream() const;
  9808. /** Creates a stream to write to this file.
  9809. If the file exists, the stream that is returned will be positioned ready for
  9810. writing at the end of the file, so you might want to use deleteFile() first
  9811. to write to an empty file.
  9812. @returns a stream that will write to this file (initially positioned at the
  9813. end of the file), or 0 if the file can't be opened for some reason
  9814. @see createInputStream, appendData, appendText
  9815. */
  9816. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  9817. /** Loads a file's contents into memory as a block of binary data.
  9818. Of course, trying to load a very large file into memory will blow up, so
  9819. it's better to check first.
  9820. @param result the data block to which the file's contents should be appended - note
  9821. that if the memory block might already contain some data, you
  9822. might want to clear it first
  9823. @returns true if the file could all be read into memory
  9824. */
  9825. bool loadFileAsData (MemoryBlock& result) const;
  9826. /** Reads a file into memory as a string.
  9827. Attempts to load the entire file as a zero-terminated string.
  9828. This makes use of InputStream::readEntireStreamAsString, which should
  9829. automatically cope with unicode/acsii file formats.
  9830. */
  9831. const String loadFileAsString() const;
  9832. /** Appends a block of binary data to the end of the file.
  9833. This will try to write the given buffer to the end of the file.
  9834. @returns false if it can't write to the file for some reason
  9835. */
  9836. bool appendData (const void* dataToAppend,
  9837. int numberOfBytes) const;
  9838. /** Replaces this file's contents with a given block of data.
  9839. This will delete the file and replace it with the given data.
  9840. A nice feature of this method is that it's safe - instead of deleting
  9841. the file first and then re-writing it, it creates a new temporary file,
  9842. writes the data to that, and then moves the new file to replace the existing
  9843. file. This means that if the power gets pulled out or something crashes,
  9844. you're a lot less likely to end up with a corrupted or unfinished file..
  9845. Returns true if the operation succeeds, or false if it fails.
  9846. @see appendText
  9847. */
  9848. bool replaceWithData (const void* dataToWrite,
  9849. int numberOfBytes) const;
  9850. /** Appends a string to the end of the file.
  9851. This will try to append a text string to the file, as either 16-bit unicode
  9852. or 8-bit characters in the default system encoding.
  9853. It can also write the 'ff fe' unicode header bytes before the text to indicate
  9854. the endianness of the file.
  9855. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  9856. @see replaceWithText
  9857. */
  9858. bool appendText (const String& textToAppend,
  9859. bool asUnicode = false,
  9860. bool writeUnicodeHeaderBytes = false) const;
  9861. /** Replaces this file's contents with a given text string.
  9862. This will delete the file and replace it with the given text.
  9863. A nice feature of this method is that it's safe - instead of deleting
  9864. the file first and then re-writing it, it creates a new temporary file,
  9865. writes the text to that, and then moves the new file to replace the existing
  9866. file. This means that if the power gets pulled out or something crashes,
  9867. you're a lot less likely to end up with an empty file..
  9868. For an explanation of the parameters here, see the appendText() method.
  9869. Returns true if the operation succeeds, or false if it fails.
  9870. @see appendText
  9871. */
  9872. bool replaceWithText (const String& textToWrite,
  9873. bool asUnicode = false,
  9874. bool writeUnicodeHeaderBytes = false) const;
  9875. /** Attempts to scan the contents of this file and compare it to another file, returning
  9876. true if this is possible and they match byte-for-byte.
  9877. */
  9878. bool hasIdenticalContentTo (const File& other) const;
  9879. /** Creates a set of files to represent each file root.
  9880. e.g. on Windows this will create files for "c:\", "d:\" etc according
  9881. to which ones are available. On the Mac/Linux, this will probably
  9882. just add a single entry for "/".
  9883. */
  9884. static void findFileSystemRoots (Array<File>& results);
  9885. /** Finds the name of the drive on which this file lives.
  9886. @returns the volume label of the drive, or an empty string if this isn't possible
  9887. */
  9888. const String getVolumeLabel() const;
  9889. /** Returns the serial number of the volume on which this file lives.
  9890. @returns the serial number, or zero if there's a problem doing this
  9891. */
  9892. int getVolumeSerialNumber() const;
  9893. /** Returns the number of bytes free on the drive that this file lives on.
  9894. @returns the number of bytes free, or 0 if there's a problem finding this out
  9895. @see getVolumeTotalSize
  9896. */
  9897. int64 getBytesFreeOnVolume() const;
  9898. /** Returns the total size of the drive that contains this file.
  9899. @returns the total number of bytes that the volume can hold
  9900. @see getBytesFreeOnVolume
  9901. */
  9902. int64 getVolumeTotalSize() const;
  9903. /** Returns true if this file is on a CD or DVD drive. */
  9904. bool isOnCDRomDrive() const;
  9905. /** Returns true if this file is on a hard disk.
  9906. This will fail if it's a network drive, but will still be true for
  9907. removable hard-disks.
  9908. */
  9909. bool isOnHardDisk() const;
  9910. /** Returns true if this file is on a removable disk drive.
  9911. This might be a usb-drive, a CD-rom, or maybe a network drive.
  9912. */
  9913. bool isOnRemovableDrive() const;
  9914. /** Launches the file as a process.
  9915. - if the file is executable, this will run it.
  9916. - if it's a document of some kind, it will launch the document with its
  9917. default viewer application.
  9918. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  9919. @see revealToUser
  9920. */
  9921. bool startAsProcess (const String& parameters = String::empty) const;
  9922. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  9923. @see startAsProcess
  9924. */
  9925. void revealToUser() const;
  9926. /** A set of types of location that can be passed to the getSpecialLocation() method.
  9927. */
  9928. enum SpecialLocationType
  9929. {
  9930. /** The user's home folder. This is the same as using File ("~"). */
  9931. userHomeDirectory,
  9932. /** The user's default documents folder. On Windows, this might be the user's
  9933. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  9934. doesn't tend to have one of these, so it might just return their home folder.
  9935. */
  9936. userDocumentsDirectory,
  9937. /** The folder that contains the user's desktop objects. */
  9938. userDesktopDirectory,
  9939. /** The folder in which applications store their persistent user-specific settings.
  9940. On Windows, this might be "\Documents and Settings\username\Application Data".
  9941. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  9942. always create your own sub-folder to put them in, to avoid making a mess.
  9943. */
  9944. userApplicationDataDirectory,
  9945. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  9946. of the computer, rather than just the current user.
  9947. On the Mac it'll be "/Library", on Windows, it could be something like
  9948. "\Documents and Settings\All Users\Application Data".
  9949. Depending on the setup, this folder may be read-only.
  9950. */
  9951. commonApplicationDataDirectory,
  9952. /** The folder that should be used for temporary files.
  9953. Always delete them when you're finished, to keep the user's computer tidy!
  9954. */
  9955. tempDirectory,
  9956. /** Returns this application's executable file.
  9957. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9958. host app.
  9959. On the mac this will return the unix binary, not the package folder - see
  9960. currentApplicationFile for that.
  9961. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  9962. file link, invokedExecutableFile will return the name of the link.
  9963. */
  9964. currentExecutableFile,
  9965. /** Returns this application's location.
  9966. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9967. host app.
  9968. On the mac this will return the package folder (if it's in one), not the unix binary
  9969. that's inside it - compare with currentExecutableFile.
  9970. */
  9971. currentApplicationFile,
  9972. /** Returns the file that was invoked to launch this executable.
  9973. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  9974. will return the name of the link that was used, whereas currentExecutableFile will return
  9975. the actual location of the target executable.
  9976. */
  9977. invokedExecutableFile,
  9978. /** In a plugin, this will return the path of the host executable. */
  9979. hostApplicationPath,
  9980. /** The directory in which applications normally get installed.
  9981. So on windows, this would be something like "c:\program files", on the
  9982. Mac "/Applications", or "/usr" on linux.
  9983. */
  9984. globalApplicationsDirectory,
  9985. /** The most likely place where a user might store their music files.
  9986. */
  9987. userMusicDirectory,
  9988. /** The most likely place where a user might store their movie files.
  9989. */
  9990. userMoviesDirectory,
  9991. };
  9992. /** Finds the location of a special type of file or directory, such as a home folder or
  9993. documents folder.
  9994. @see SpecialLocationType
  9995. */
  9996. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  9997. /** Returns a temporary file in the system's temp directory.
  9998. This will try to return the name of a non-existent temp file.
  9999. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  10000. */
  10001. static const File createTempFile (const String& fileNameEnding);
  10002. /** Returns the current working directory.
  10003. @see setAsCurrentWorkingDirectory
  10004. */
  10005. static const File getCurrentWorkingDirectory();
  10006. /** Sets the current working directory to be this file.
  10007. For this to work the file must point to a valid directory.
  10008. @returns true if the current directory has been changed.
  10009. @see getCurrentWorkingDirectory
  10010. */
  10011. bool setAsCurrentWorkingDirectory() const;
  10012. /** The system-specific file separator character.
  10013. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10014. */
  10015. static const juce_wchar separator;
  10016. /** The system-specific file separator character, as a string.
  10017. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  10018. */
  10019. static const String separatorString;
  10020. /** Removes illegal characters from a filename.
  10021. This will return a copy of the given string after removing characters
  10022. that are not allowed in a legal filename, and possibly shortening the
  10023. string if it's too long.
  10024. Because this will remove slashes, don't use it on an absolute pathname.
  10025. @see createLegalPathName
  10026. */
  10027. static const String createLegalFileName (const String& fileNameToFix);
  10028. /** Removes illegal characters from a pathname.
  10029. Similar to createLegalFileName(), but this won't remove slashes, so can
  10030. be used on a complete pathname.
  10031. @see createLegalFileName
  10032. */
  10033. static const String createLegalPathName (const String& pathNameToFix);
  10034. /** Indicates whether filenames are case-sensitive on the current operating system.
  10035. */
  10036. static bool areFileNamesCaseSensitive();
  10037. /** Returns true if the string seems to be a fully-specified absolute path.
  10038. */
  10039. static bool isAbsolutePath (const String& path);
  10040. /** Creates a file that simply contains this string, without doing the sanity-checking
  10041. that the normal constructors do.
  10042. Best to avoid this unless you really know what you're doing.
  10043. */
  10044. static const File createFileWithoutCheckingPath (const String& path);
  10045. /** Adds a separator character to the end of a path if it doesn't already have one. */
  10046. static const String addTrailingSeparator (const String& path);
  10047. private:
  10048. String fullPath;
  10049. // internal way of contructing a file without checking the path
  10050. friend class DirectoryIterator;
  10051. File (const String&, int);
  10052. const String getPathUpToLastSlash() const;
  10053. void createDirectoryInternal (const String& fileName) const;
  10054. bool copyInternal (const File& dest) const;
  10055. bool moveInternal (const File& dest) const;
  10056. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  10057. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  10058. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  10059. static const String parseAbsolutePath (const String& path);
  10060. JUCE_LEAK_DETECTOR (File);
  10061. };
  10062. #endif // __JUCE_FILE_JUCEHEADER__
  10063. /*** End of inlined file: juce_File.h ***/
  10064. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  10065. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10066. will be the name of a pointer to each child element.
  10067. E.g. @code
  10068. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10069. forEachXmlChildElement (*myParentXml, child)
  10070. {
  10071. if (child->hasTagName ("FOO"))
  10072. doSomethingWithXmlElement (child);
  10073. }
  10074. @endcode
  10075. @see forEachXmlChildElementWithTagName
  10076. */
  10077. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  10078. \
  10079. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  10080. childElementVariableName != 0; \
  10081. childElementVariableName = childElementVariableName->getNextElement())
  10082. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  10083. which have a specified tag.
  10084. This does the same job as the forEachXmlChildElement macro, but only for those
  10085. elements that have a particular tag name.
  10086. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  10087. will be the name of a pointer to each child element. The requiredTagName is the
  10088. tag name to match.
  10089. E.g. @code
  10090. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  10091. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  10092. {
  10093. // the child object is now guaranteed to be a <MYTAG> element..
  10094. doSomethingWithMYTAGElement (child);
  10095. }
  10096. @endcode
  10097. @see forEachXmlChildElement
  10098. */
  10099. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  10100. \
  10101. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  10102. childElementVariableName != 0; \
  10103. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  10104. /** Used to build a tree of elements representing an XML document.
  10105. An XML document can be parsed into a tree of XmlElements, each of which
  10106. represents an XML tag structure, and which may itself contain other
  10107. nested elements.
  10108. An XmlElement can also be converted back into a text document, and has
  10109. lots of useful methods for manipulating its attributes and sub-elements,
  10110. so XmlElements can actually be used as a handy general-purpose data
  10111. structure.
  10112. Here's an example of parsing some elements: @code
  10113. // check we're looking at the right kind of document..
  10114. if (myElement->hasTagName ("ANIMALS"))
  10115. {
  10116. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  10117. forEachXmlChildElement (*myElement, e)
  10118. {
  10119. if (e->hasTagName ("GIRAFFE"))
  10120. {
  10121. // found a giraffe, so use some of its attributes..
  10122. String giraffeName = e->getStringAttribute ("name");
  10123. int giraffeAge = e->getIntAttribute ("age");
  10124. bool isFriendly = e->getBoolAttribute ("friendly");
  10125. }
  10126. }
  10127. }
  10128. @endcode
  10129. And here's an example of how to create an XML document from scratch: @code
  10130. // create an outer node called "ANIMALS"
  10131. XmlElement animalsList ("ANIMALS");
  10132. for (int i = 0; i < numAnimals; ++i)
  10133. {
  10134. // create an inner element..
  10135. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  10136. giraffe->setAttribute ("name", "nigel");
  10137. giraffe->setAttribute ("age", 10);
  10138. giraffe->setAttribute ("friendly", true);
  10139. // ..and add our new element to the parent node
  10140. animalsList.addChildElement (giraffe);
  10141. }
  10142. // now we can turn the whole thing into a text document..
  10143. String myXmlDoc = animalsList.createDocument (String::empty);
  10144. @endcode
  10145. @see XmlDocument
  10146. */
  10147. class JUCE_API XmlElement
  10148. {
  10149. public:
  10150. /** Creates an XmlElement with this tag name. */
  10151. explicit XmlElement (const String& tagName) throw();
  10152. /** Creates a (deep) copy of another element. */
  10153. XmlElement (const XmlElement& other);
  10154. /** Creates a (deep) copy of another element. */
  10155. XmlElement& operator= (const XmlElement& other);
  10156. /** Deleting an XmlElement will also delete all its child elements. */
  10157. ~XmlElement() throw();
  10158. /** Compares two XmlElements to see if they contain the same text and attiributes.
  10159. The elements are only considered equivalent if they contain the same attiributes
  10160. with the same values, and have the same sub-nodes.
  10161. @param other the other element to compare to
  10162. @param ignoreOrderOfAttributes if true, this means that two elements with the
  10163. same attributes in a different order will be
  10164. considered the same; if false, the attributes must
  10165. be in the same order as well
  10166. */
  10167. bool isEquivalentTo (const XmlElement* other,
  10168. bool ignoreOrderOfAttributes) const throw();
  10169. /** Returns an XML text document that represents this element.
  10170. The string returned can be parsed to recreate the same XmlElement that
  10171. was used to create it.
  10172. @param dtdToUse the DTD to add to the document
  10173. @param allOnOneLine if true, this means that the document will not contain any
  10174. linefeeds, so it'll be smaller but not very easy to read.
  10175. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10176. document
  10177. @param encodingType the character encoding format string to put into the xml
  10178. header
  10179. @param lineWrapLength the line length that will be used before items get placed on
  10180. a new line. This isn't an absolute maximum length, it just
  10181. determines how lists of attributes get broken up
  10182. @see writeToStream, writeToFile
  10183. */
  10184. const String createDocument (const String& dtdToUse,
  10185. bool allOnOneLine = false,
  10186. bool includeXmlHeader = true,
  10187. const String& encodingType = "UTF-8",
  10188. int lineWrapLength = 60) const;
  10189. /** Writes the document to a stream as UTF-8.
  10190. @param output the stream to write to
  10191. @param dtdToUse the DTD to add to the document
  10192. @param allOnOneLine if true, this means that the document will not contain any
  10193. linefeeds, so it'll be smaller but not very easy to read.
  10194. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  10195. document
  10196. @param encodingType the character encoding format string to put into the xml
  10197. header
  10198. @param lineWrapLength the line length that will be used before items get placed on
  10199. a new line. This isn't an absolute maximum length, it just
  10200. determines how lists of attributes get broken up
  10201. @see writeToFile, createDocument
  10202. */
  10203. void writeToStream (OutputStream& output,
  10204. const String& dtdToUse,
  10205. bool allOnOneLine = false,
  10206. bool includeXmlHeader = true,
  10207. const String& encodingType = "UTF-8",
  10208. int lineWrapLength = 60) const;
  10209. /** Writes the element to a file as an XML document.
  10210. To improve safety in case something goes wrong while writing the file, this
  10211. will actually write the document to a new temporary file in the same
  10212. directory as the destination file, and if this succeeds, it will rename this
  10213. new file as the destination file (overwriting any existing file that was there).
  10214. @param destinationFile the file to write to. If this already exists, it will be
  10215. overwritten.
  10216. @param dtdToUse the DTD to add to the document
  10217. @param encodingType the character encoding format string to put into the xml
  10218. header
  10219. @param lineWrapLength the line length that will be used before items get placed on
  10220. a new line. This isn't an absolute maximum length, it just
  10221. determines how lists of attributes get broken up
  10222. @returns true if the file is written successfully; false if something goes wrong
  10223. in the process
  10224. @see createDocument
  10225. */
  10226. bool writeToFile (const File& destinationFile,
  10227. const String& dtdToUse,
  10228. const String& encodingType = "UTF-8",
  10229. int lineWrapLength = 60) const;
  10230. /** Returns this element's tag type name.
  10231. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  10232. "MOOSE".
  10233. @see hasTagName
  10234. */
  10235. inline const String& getTagName() const throw() { return tagName; }
  10236. /** Tests whether this element has a particular tag name.
  10237. @param possibleTagName the tag name you're comparing it with
  10238. @see getTagName
  10239. */
  10240. bool hasTagName (const String& possibleTagName) const throw();
  10241. /** Returns the number of XML attributes this element contains.
  10242. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  10243. return 2.
  10244. */
  10245. int getNumAttributes() const throw();
  10246. /** Returns the name of one of the elements attributes.
  10247. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10248. getAttributeName(1) would return "antlers".
  10249. @see getAttributeValue, getStringAttribute
  10250. */
  10251. const String& getAttributeName (int attributeIndex) const throw();
  10252. /** Returns the value of one of the elements attributes.
  10253. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  10254. getAttributeName(1) would return "2".
  10255. @see getAttributeName, getStringAttribute
  10256. */
  10257. const String& getAttributeValue (int attributeIndex) const throw();
  10258. // Attribute-handling methods..
  10259. /** Checks whether the element contains an attribute with a certain name. */
  10260. bool hasAttribute (const String& attributeName) const throw();
  10261. /** Returns the value of a named attribute.
  10262. @param attributeName the name of the attribute to look up
  10263. */
  10264. const String& getStringAttribute (const String& attributeName) const throw();
  10265. /** Returns the value of a named attribute.
  10266. @param attributeName the name of the attribute to look up
  10267. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10268. with this name
  10269. */
  10270. const String getStringAttribute (const String& attributeName,
  10271. const String& defaultReturnValue) const;
  10272. /** Compares the value of a named attribute with a value passed-in.
  10273. @param attributeName the name of the attribute to look up
  10274. @param stringToCompareAgainst the value to compare it with
  10275. @param ignoreCase whether the comparison should be case-insensitive
  10276. @returns true if the value of the attribute is the same as the string passed-in;
  10277. false if it's different (or if no such attribute exists)
  10278. */
  10279. bool compareAttribute (const String& attributeName,
  10280. const String& stringToCompareAgainst,
  10281. bool ignoreCase = false) const throw();
  10282. /** Returns the value of a named attribute as an integer.
  10283. This will try to find the attribute and convert it to an integer (using
  10284. the String::getIntValue() method).
  10285. @param attributeName the name of the attribute to look up
  10286. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10287. with this name
  10288. @see setAttribute
  10289. */
  10290. int getIntAttribute (const String& attributeName,
  10291. int defaultReturnValue = 0) const;
  10292. /** Returns the value of a named attribute as floating-point.
  10293. This will try to find the attribute and convert it to an integer (using
  10294. the String::getDoubleValue() method).
  10295. @param attributeName the name of the attribute to look up
  10296. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10297. with this name
  10298. @see setAttribute
  10299. */
  10300. double getDoubleAttribute (const String& attributeName,
  10301. double defaultReturnValue = 0.0) const;
  10302. /** Returns the value of a named attribute as a boolean.
  10303. This will try to find the attribute and interpret it as a boolean. To do this,
  10304. it'll return true if the value is "1", "true", "y", etc, or false for other
  10305. values.
  10306. @param attributeName the name of the attribute to look up
  10307. @param defaultReturnValue a value to return if the element doesn't have an attribute
  10308. with this name
  10309. */
  10310. bool getBoolAttribute (const String& attributeName,
  10311. bool defaultReturnValue = false) const;
  10312. /** Adds a named attribute to the element.
  10313. If the element already contains an attribute with this name, it's value will
  10314. be updated to the new value. If there's no such attribute yet, a new one will
  10315. be added.
  10316. Note that there are other setAttribute() methods that take integers,
  10317. doubles, etc. to make it easy to store numbers.
  10318. @param attributeName the name of the attribute to set
  10319. @param newValue the value to set it to
  10320. @see removeAttribute
  10321. */
  10322. void setAttribute (const String& attributeName,
  10323. const String& newValue);
  10324. /** Adds a named attribute to the element, setting it to an integer value.
  10325. If the element already contains an attribute with this name, it's value will
  10326. be updated to the new value. If there's no such attribute yet, a new one will
  10327. be added.
  10328. Note that there are other setAttribute() methods that take integers,
  10329. doubles, etc. to make it easy to store numbers.
  10330. @param attributeName the name of the attribute to set
  10331. @param newValue the value to set it to
  10332. */
  10333. void setAttribute (const String& attributeName,
  10334. int newValue);
  10335. /** Adds a named attribute to the element, setting it to a floating-point value.
  10336. If the element already contains an attribute with this name, it's value will
  10337. be updated to the new value. If there's no such attribute yet, a new one will
  10338. be added.
  10339. Note that there are other setAttribute() methods that take integers,
  10340. doubles, etc. to make it easy to store numbers.
  10341. @param attributeName the name of the attribute to set
  10342. @param newValue the value to set it to
  10343. */
  10344. void setAttribute (const String& attributeName,
  10345. double newValue);
  10346. /** Removes a named attribute from the element.
  10347. @param attributeName the name of the attribute to remove
  10348. @see removeAllAttributes
  10349. */
  10350. void removeAttribute (const String& attributeName) throw();
  10351. /** Removes all attributes from this element.
  10352. */
  10353. void removeAllAttributes() throw();
  10354. // Child element methods..
  10355. /** Returns the first of this element's sub-elements.
  10356. see getNextElement() for an example of how to iterate the sub-elements.
  10357. @see forEachXmlChildElement
  10358. */
  10359. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  10360. /** Returns the next of this element's siblings.
  10361. This can be used for iterating an element's sub-elements, e.g.
  10362. @code
  10363. XmlElement* child = myXmlDocument->getFirstChildElement();
  10364. while (child != 0)
  10365. {
  10366. ...do stuff with this child..
  10367. child = child->getNextElement();
  10368. }
  10369. @endcode
  10370. Note that when iterating the child elements, some of them might be
  10371. text elements as well as XML tags - use isTextElement() to work this
  10372. out.
  10373. Also, it's much easier and neater to use this method indirectly via the
  10374. forEachXmlChildElement macro.
  10375. @returns the sibling element that follows this one, or zero if this is the last
  10376. element in its parent
  10377. @see getNextElement, isTextElement, forEachXmlChildElement
  10378. */
  10379. inline XmlElement* getNextElement() const throw() { return nextListItem; }
  10380. /** Returns the next of this element's siblings which has the specified tag
  10381. name.
  10382. This is like getNextElement(), but will scan through the list until it
  10383. finds an element with the given tag name.
  10384. @see getNextElement, forEachXmlChildElementWithTagName
  10385. */
  10386. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  10387. /** Returns the number of sub-elements in this element.
  10388. @see getChildElement
  10389. */
  10390. int getNumChildElements() const throw();
  10391. /** Returns the sub-element at a certain index.
  10392. It's not very efficient to iterate the sub-elements by index - see
  10393. getNextElement() for an example of how best to iterate.
  10394. @returns the n'th child of this element, or 0 if the index is out-of-range
  10395. @see getNextElement, isTextElement, getChildByName
  10396. */
  10397. XmlElement* getChildElement (int index) const throw();
  10398. /** Returns the first sub-element with a given tag-name.
  10399. @param tagNameToLookFor the tag name of the element you want to find
  10400. @returns the first element with this tag name, or 0 if none is found
  10401. @see getNextElement, isTextElement, getChildElement
  10402. */
  10403. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  10404. /** Appends an element to this element's list of children.
  10405. Child elements are deleted automatically when their parent is deleted, so
  10406. make sure the object that you pass in will not be deleted by anything else,
  10407. and make sure it's not already the child of another element.
  10408. @see getFirstChildElement, getNextElement, getNumChildElements,
  10409. getChildElement, removeChildElement
  10410. */
  10411. void addChildElement (XmlElement* newChildElement) throw();
  10412. /** Inserts an element into this element's list of children.
  10413. Child elements are deleted automatically when their parent is deleted, so
  10414. make sure the object that you pass in will not be deleted by anything else,
  10415. and make sure it's not already the child of another element.
  10416. @param newChildNode the element to add
  10417. @param indexToInsertAt the index at which to insert the new element - if this is
  10418. below zero, it will be added to the end of the list
  10419. @see addChildElement, insertChildElement
  10420. */
  10421. void insertChildElement (XmlElement* newChildNode,
  10422. int indexToInsertAt) throw();
  10423. /** Creates a new element with the given name and returns it, after adding it
  10424. as a child element.
  10425. This is a handy method that means that instead of writing this:
  10426. @code
  10427. XmlElement* newElement = new XmlElement ("foobar");
  10428. myParentElement->addChildElement (newElement);
  10429. @endcode
  10430. ..you could just write this:
  10431. @code
  10432. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  10433. @endcode
  10434. */
  10435. XmlElement* createNewChildElement (const String& tagName);
  10436. /** Replaces one of this element's children with another node.
  10437. If the current element passed-in isn't actually a child of this element,
  10438. this will return false and the new one won't be added. Otherwise, the
  10439. existing element will be deleted, replaced with the new one, and it
  10440. will return true.
  10441. */
  10442. bool replaceChildElement (XmlElement* currentChildElement,
  10443. XmlElement* newChildNode) throw();
  10444. /** Removes a child element.
  10445. @param childToRemove the child to look for and remove
  10446. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  10447. just remove it
  10448. */
  10449. void removeChildElement (XmlElement* childToRemove,
  10450. bool shouldDeleteTheChild) throw();
  10451. /** Deletes all the child elements in the element.
  10452. @see removeChildElement, deleteAllChildElementsWithTagName
  10453. */
  10454. void deleteAllChildElements() throw();
  10455. /** Deletes all the child elements with a given tag name.
  10456. @see removeChildElement
  10457. */
  10458. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  10459. /** Returns true if the given element is a child of this one. */
  10460. bool containsChildElement (const XmlElement* possibleChild) const throw();
  10461. /** Recursively searches all sub-elements to find one that contains the specified
  10462. child element.
  10463. */
  10464. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  10465. /** Sorts the child elements using a comparator.
  10466. This will use a comparator object to sort the elements into order. The object
  10467. passed must have a method of the form:
  10468. @code
  10469. int compareElements (const XmlElement* first, const XmlElement* second);
  10470. @endcode
  10471. ..and this method must return:
  10472. - a value of < 0 if the first comes before the second
  10473. - a value of 0 if the two objects are equivalent
  10474. - a value of > 0 if the second comes before the first
  10475. To improve performance, the compareElements() method can be declared as static or const.
  10476. @param comparator the comparator to use for comparing elements.
  10477. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  10478. says are equivalent will be kept in the order in which they
  10479. currently appear in the array. This is slower to perform, but
  10480. may be important in some cases. If it's false, a faster algorithm
  10481. is used, but equivalent elements may be rearranged.
  10482. */
  10483. template <class ElementComparator>
  10484. void sortChildElements (ElementComparator& comparator,
  10485. bool retainOrderOfEquivalentItems = false)
  10486. {
  10487. const int num = getNumChildElements();
  10488. if (num > 1)
  10489. {
  10490. HeapBlock <XmlElement*> elems (num);
  10491. getChildElementsAsArray (elems);
  10492. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  10493. reorderChildElements (elems, num);
  10494. }
  10495. }
  10496. /** Returns true if this element is a section of text.
  10497. Elements can either be an XML tag element or a secton of text, so this
  10498. is used to find out what kind of element this one is.
  10499. @see getAllText, addTextElement, deleteAllTextElements
  10500. */
  10501. bool isTextElement() const throw();
  10502. /** Returns the text for a text element.
  10503. Note that if you have an element like this:
  10504. @code<xyz>hello</xyz>@endcode
  10505. then calling getText on the "xyz" element won't return "hello", because that is
  10506. actually stored in a special text sub-element inside the xyz element. To get the
  10507. "hello" string, you could either call getText on the (unnamed) sub-element, or
  10508. use getAllSubText() to do this automatically.
  10509. Note that leading and trailing whitespace will be included in the string - to remove
  10510. if, just call String::trim() on the result.
  10511. @see isTextElement, getAllSubText, getChildElementAllSubText
  10512. */
  10513. const String& getText() const throw();
  10514. /** Sets the text in a text element.
  10515. Note that this is only a valid call if this element is a text element. If it's
  10516. not, then no action will be performed. If you're trying to add text inside a normal
  10517. element, you probably want to use addTextElement() instead.
  10518. */
  10519. void setText (const String& newText);
  10520. /** Returns all the text from this element's child nodes.
  10521. This iterates all the child elements and when it finds text elements,
  10522. it concatenates their text into a big string which it returns.
  10523. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  10524. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  10525. Note that leading and trailing whitespace will be included in the string - to remove
  10526. if, just call String::trim() on the result.
  10527. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  10528. */
  10529. const String getAllSubText() const;
  10530. /** Returns all the sub-text of a named child element.
  10531. If there is a child element with the given tag name, this will return
  10532. all of its sub-text (by calling getAllSubText() on it). If there is
  10533. no such child element, this will return the default string passed-in.
  10534. @see getAllSubText
  10535. */
  10536. const String getChildElementAllSubText (const String& childTagName,
  10537. const String& defaultReturnValue) const;
  10538. /** Appends a section of text to this element.
  10539. @see isTextElement, getText, getAllSubText
  10540. */
  10541. void addTextElement (const String& text);
  10542. /** Removes all the text elements from this element.
  10543. @see isTextElement, getText, getAllSubText, addTextElement
  10544. */
  10545. void deleteAllTextElements() throw();
  10546. /** Creates a text element that can be added to a parent element.
  10547. */
  10548. static XmlElement* createTextElement (const String& text);
  10549. private:
  10550. struct XmlAttributeNode
  10551. {
  10552. XmlAttributeNode (const XmlAttributeNode& other) throw();
  10553. XmlAttributeNode (const String& name, const String& value) throw();
  10554. LinkedListPointer<XmlAttributeNode> nextListItem;
  10555. String name, value;
  10556. bool hasName (const String& name) const throw();
  10557. private:
  10558. XmlAttributeNode& operator= (const XmlAttributeNode&);
  10559. };
  10560. friend class XmlDocument;
  10561. friend class LinkedListPointer<XmlAttributeNode>;
  10562. friend class LinkedListPointer <XmlElement>;
  10563. friend class LinkedListPointer <XmlElement>::Appender;
  10564. LinkedListPointer <XmlElement> nextListItem;
  10565. LinkedListPointer <XmlElement> firstChildElement;
  10566. LinkedListPointer <XmlAttributeNode> attributes;
  10567. String tagName;
  10568. XmlElement (int) throw();
  10569. void copyChildrenAndAttributesFrom (const XmlElement& other);
  10570. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  10571. void getChildElementsAsArray (XmlElement**) const throw();
  10572. void reorderChildElements (XmlElement**, int) throw();
  10573. JUCE_LEAK_DETECTOR (XmlElement);
  10574. };
  10575. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  10576. /*** End of inlined file: juce_XmlElement.h ***/
  10577. /**
  10578. A set of named property values, which can be strings, integers, floating point, etc.
  10579. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  10580. to load and save types other than strings.
  10581. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  10582. messages and saves/loads the list from a file.
  10583. */
  10584. class JUCE_API PropertySet
  10585. {
  10586. public:
  10587. /** Creates an empty PropertySet.
  10588. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  10589. case-insensitive way
  10590. */
  10591. PropertySet (bool ignoreCaseOfKeyNames = false);
  10592. /** Creates a copy of another PropertySet.
  10593. */
  10594. PropertySet (const PropertySet& other);
  10595. /** Copies another PropertySet over this one.
  10596. */
  10597. PropertySet& operator= (const PropertySet& other);
  10598. /** Destructor. */
  10599. virtual ~PropertySet();
  10600. /** Returns one of the properties as a string.
  10601. If the value isn't found in this set, then this will look for it in a fallback
  10602. property set (if you've specified one with the setFallbackPropertySet() method),
  10603. and if it can't find one there, it'll return the default value passed-in.
  10604. @param keyName the name of the property to retrieve
  10605. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10606. */
  10607. const String getValue (const String& keyName,
  10608. const String& defaultReturnValue = String::empty) const throw();
  10609. /** Returns one of the properties as an integer.
  10610. If the value isn't found in this set, then this will look for it in a fallback
  10611. property set (if you've specified one with the setFallbackPropertySet() method),
  10612. and if it can't find one there, it'll return the default value passed-in.
  10613. @param keyName the name of the property to retrieve
  10614. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10615. */
  10616. int getIntValue (const String& keyName,
  10617. const int defaultReturnValue = 0) const throw();
  10618. /** Returns one of the properties as an double.
  10619. If the value isn't found in this set, then this will look for it in a fallback
  10620. property set (if you've specified one with the setFallbackPropertySet() method),
  10621. and if it can't find one there, it'll return the default value passed-in.
  10622. @param keyName the name of the property to retrieve
  10623. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10624. */
  10625. double getDoubleValue (const String& keyName,
  10626. const double defaultReturnValue = 0.0) const throw();
  10627. /** Returns one of the properties as an boolean.
  10628. The result will be true if the string found for this key name can be parsed as a non-zero
  10629. integer.
  10630. If the value isn't found in this set, then this will look for it in a fallback
  10631. property set (if you've specified one with the setFallbackPropertySet() method),
  10632. and if it can't find one there, it'll return the default value passed-in.
  10633. @param keyName the name of the property to retrieve
  10634. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10635. */
  10636. bool getBoolValue (const String& keyName,
  10637. const bool defaultReturnValue = false) const throw();
  10638. /** Returns one of the properties as an XML element.
  10639. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  10640. key isn't found, or if the entry contains an string that isn't valid XML.
  10641. If the value isn't found in this set, then this will look for it in a fallback
  10642. property set (if you've specified one with the setFallbackPropertySet() method),
  10643. and if it can't find one there, it'll return the default value passed-in.
  10644. @param keyName the name of the property to retrieve
  10645. */
  10646. XmlElement* getXmlValue (const String& keyName) const;
  10647. /** Sets a named property.
  10648. @param keyName the name of the property to set. (This mustn't be an empty string)
  10649. @param value the new value to set it to
  10650. */
  10651. void setValue (const String& keyName, const var& value);
  10652. /** Sets a named property to an XML element.
  10653. @param keyName the name of the property to set. (This mustn't be an empty string)
  10654. @param xml the new element to set it to. If this is zero, the value will be set to
  10655. an empty string
  10656. @see getXmlValue
  10657. */
  10658. void setValue (const String& keyName, const XmlElement* xml);
  10659. /** Deletes a property.
  10660. @param keyName the name of the property to delete. (This mustn't be an empty string)
  10661. */
  10662. void removeValue (const String& keyName);
  10663. /** Returns true if the properies include the given key. */
  10664. bool containsKey (const String& keyName) const throw();
  10665. /** Removes all values. */
  10666. void clear();
  10667. /** Returns the keys/value pair array containing all the properties. */
  10668. StringPairArray& getAllProperties() throw() { return properties; }
  10669. /** Returns the lock used when reading or writing to this set */
  10670. const CriticalSection& getLock() const throw() { return lock; }
  10671. /** Returns an XML element which encapsulates all the items in this property set.
  10672. The string parameter is the tag name that should be used for the node.
  10673. @see restoreFromXml
  10674. */
  10675. XmlElement* createXml (const String& nodeName) const;
  10676. /** Reloads a set of properties that were previously stored as XML.
  10677. The node passed in must have been created by the createXml() method.
  10678. @see createXml
  10679. */
  10680. void restoreFromXml (const XmlElement& xml);
  10681. /** Sets up a second PopertySet that will be used to look up any values that aren't
  10682. set in this one.
  10683. If you set this up to be a pointer to a second property set, then whenever one
  10684. of the getValue() methods fails to find an entry in this set, it will look up that
  10685. value in the fallback set, and if it finds it, it will return that.
  10686. Make sure that you don't delete the fallback set while it's still being used by
  10687. another set! To remove the fallback set, just call this method with a null pointer.
  10688. @see getFallbackPropertySet
  10689. */
  10690. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  10691. /** Returns the fallback property set.
  10692. @see setFallbackPropertySet
  10693. */
  10694. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  10695. protected:
  10696. /** Subclasses can override this to be told when one of the properies has been changed. */
  10697. virtual void propertyChanged();
  10698. private:
  10699. StringPairArray properties;
  10700. PropertySet* fallbackProperties;
  10701. CriticalSection lock;
  10702. bool ignoreCaseOfKeys;
  10703. JUCE_LEAK_DETECTOR (PropertySet);
  10704. };
  10705. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  10706. /*** End of inlined file: juce_PropertySet.h ***/
  10707. #endif
  10708. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10709. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  10710. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10711. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10712. /**
  10713. Holds a list of objects derived from ReferenceCountedObject.
  10714. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  10715. and takes care of incrementing and decrementing their ref counts when they
  10716. are added and removed from the array.
  10717. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  10718. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10719. @see Array, OwnedArray, StringArray
  10720. */
  10721. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10722. class ReferenceCountedArray
  10723. {
  10724. public:
  10725. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  10726. /** Creates an empty array.
  10727. @see ReferenceCountedObject, Array, OwnedArray
  10728. */
  10729. ReferenceCountedArray() throw()
  10730. : numUsed (0)
  10731. {
  10732. }
  10733. /** Creates a copy of another array */
  10734. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  10735. {
  10736. const ScopedLockType lock (other.getLock());
  10737. numUsed = other.numUsed;
  10738. data.setAllocatedSize (numUsed);
  10739. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10740. for (int i = numUsed; --i >= 0;)
  10741. if (data.elements[i] != 0)
  10742. data.elements[i]->incReferenceCount();
  10743. }
  10744. /** Copies another array into this one.
  10745. Any existing objects in this array will first be released.
  10746. */
  10747. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  10748. {
  10749. if (this != &other)
  10750. {
  10751. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10752. swapWithArray (otherCopy);
  10753. }
  10754. return *this;
  10755. }
  10756. /** Destructor.
  10757. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10758. */
  10759. ~ReferenceCountedArray()
  10760. {
  10761. clear();
  10762. }
  10763. /** Removes all objects from the array.
  10764. Any objects in the array that are not referenced from elsewhere will be deleted.
  10765. */
  10766. void clear()
  10767. {
  10768. const ScopedLockType lock (getLock());
  10769. while (numUsed > 0)
  10770. if (data.elements [--numUsed] != 0)
  10771. data.elements [numUsed]->decReferenceCount();
  10772. jassert (numUsed == 0);
  10773. data.setAllocatedSize (0);
  10774. }
  10775. /** Returns the current number of objects in the array. */
  10776. inline int size() const throw()
  10777. {
  10778. return numUsed;
  10779. }
  10780. /** Returns a pointer to the object at this index in the array.
  10781. If the index is out-of-range, this will return a null pointer, (and
  10782. it could be null anyway, because it's ok for the array to hold null
  10783. pointers as well as objects).
  10784. @see getUnchecked
  10785. */
  10786. inline const ObjectClassPtr operator[] (const int index) const throw()
  10787. {
  10788. const ScopedLockType lock (getLock());
  10789. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10790. : static_cast <ObjectClass*> (0);
  10791. }
  10792. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  10793. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  10794. it can be used when you're sure the index if always going to be legal.
  10795. */
  10796. inline const ObjectClassPtr getUnchecked (const int index) const throw()
  10797. {
  10798. const ScopedLockType lock (getLock());
  10799. jassert (isPositiveAndBelow (index, numUsed));
  10800. return data.elements [index];
  10801. }
  10802. /** Returns a pointer to the first object in the array.
  10803. This will return a null pointer if the array's empty.
  10804. @see getLast
  10805. */
  10806. inline const ObjectClassPtr getFirst() const throw()
  10807. {
  10808. const ScopedLockType lock (getLock());
  10809. return numUsed > 0 ? data.elements [0]
  10810. : static_cast <ObjectClass*> (0);
  10811. }
  10812. /** Returns a pointer to the last object in the array.
  10813. This will return a null pointer if the array's empty.
  10814. @see getFirst
  10815. */
  10816. inline const ObjectClassPtr getLast() const throw()
  10817. {
  10818. const ScopedLockType lock (getLock());
  10819. return numUsed > 0 ? data.elements [numUsed - 1]
  10820. : static_cast <ObjectClass*> (0);
  10821. }
  10822. /** Finds the index of the first occurrence of an object in the array.
  10823. @param objectToLookFor the object to look for
  10824. @returns the index at which the object was found, or -1 if it's not found
  10825. */
  10826. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  10827. {
  10828. const ScopedLockType lock (getLock());
  10829. ObjectClass** e = data.elements.getData();
  10830. ObjectClass** const end = e + numUsed;
  10831. while (e != end)
  10832. {
  10833. if (objectToLookFor == *e)
  10834. return static_cast <int> (e - data.elements.getData());
  10835. ++e;
  10836. }
  10837. return -1;
  10838. }
  10839. /** Returns true if the array contains a specified object.
  10840. @param objectToLookFor the object to look for
  10841. @returns true if the object is in the array
  10842. */
  10843. bool contains (const ObjectClass* const objectToLookFor) const throw()
  10844. {
  10845. const ScopedLockType lock (getLock());
  10846. ObjectClass** e = data.elements.getData();
  10847. ObjectClass** const end = e + numUsed;
  10848. while (e != end)
  10849. {
  10850. if (objectToLookFor == *e)
  10851. return true;
  10852. ++e;
  10853. }
  10854. return false;
  10855. }
  10856. /** Appends a new object to the end of the array.
  10857. This will increase the new object's reference count.
  10858. @param newObject the new object to add to the array
  10859. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  10860. */
  10861. void add (ObjectClass* const newObject) throw()
  10862. {
  10863. const ScopedLockType lock (getLock());
  10864. data.ensureAllocatedSize (numUsed + 1);
  10865. data.elements [numUsed++] = newObject;
  10866. if (newObject != 0)
  10867. newObject->incReferenceCount();
  10868. }
  10869. /** Inserts a new object into the array at the given index.
  10870. If the index is less than 0 or greater than the size of the array, the
  10871. element will be added to the end of the array.
  10872. Otherwise, it will be inserted into the array, moving all the later elements
  10873. along to make room.
  10874. This will increase the new object's reference count.
  10875. @param indexToInsertAt the index at which the new element should be inserted
  10876. @param newObject the new object to add to the array
  10877. @see add, addSorted, addIfNotAlreadyThere, set
  10878. */
  10879. void insert (int indexToInsertAt,
  10880. ObjectClass* const newObject) throw()
  10881. {
  10882. if (indexToInsertAt >= 0)
  10883. {
  10884. const ScopedLockType lock (getLock());
  10885. if (indexToInsertAt > numUsed)
  10886. indexToInsertAt = numUsed;
  10887. data.ensureAllocatedSize (numUsed + 1);
  10888. ObjectClass** const e = data.elements + indexToInsertAt;
  10889. const int numToMove = numUsed - indexToInsertAt;
  10890. if (numToMove > 0)
  10891. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  10892. *e = newObject;
  10893. if (newObject != 0)
  10894. newObject->incReferenceCount();
  10895. ++numUsed;
  10896. }
  10897. else
  10898. {
  10899. add (newObject);
  10900. }
  10901. }
  10902. /** Appends a new object at the end of the array as long as the array doesn't
  10903. already contain it.
  10904. If the array already contains a matching object, nothing will be done.
  10905. @param newObject the new object to add to the array
  10906. */
  10907. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  10908. {
  10909. const ScopedLockType lock (getLock());
  10910. if (! contains (newObject))
  10911. add (newObject);
  10912. }
  10913. /** Replaces an object in the array with a different one.
  10914. If the index is less than zero, this method does nothing.
  10915. If the index is beyond the end of the array, the new object is added to the end of the array.
  10916. The object being added has its reference count increased, and if it's replacing
  10917. another object, then that one has its reference count decreased, and may be deleted.
  10918. @param indexToChange the index whose value you want to change
  10919. @param newObject the new value to set for this index.
  10920. @see add, insert, remove
  10921. */
  10922. void set (const int indexToChange,
  10923. ObjectClass* const newObject)
  10924. {
  10925. if (indexToChange >= 0)
  10926. {
  10927. const ScopedLockType lock (getLock());
  10928. if (newObject != 0)
  10929. newObject->incReferenceCount();
  10930. if (indexToChange < numUsed)
  10931. {
  10932. if (data.elements [indexToChange] != 0)
  10933. data.elements [indexToChange]->decReferenceCount();
  10934. data.elements [indexToChange] = newObject;
  10935. }
  10936. else
  10937. {
  10938. data.ensureAllocatedSize (numUsed + 1);
  10939. data.elements [numUsed++] = newObject;
  10940. }
  10941. }
  10942. }
  10943. /** Adds elements from another array to the end of this array.
  10944. @param arrayToAddFrom the array from which to copy the elements
  10945. @param startIndex the first element of the other array to start copying from
  10946. @param numElementsToAdd how many elements to add from the other array. If this
  10947. value is negative or greater than the number of available elements,
  10948. all available elements will be copied.
  10949. @see add
  10950. */
  10951. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  10952. int startIndex = 0,
  10953. int numElementsToAdd = -1) throw()
  10954. {
  10955. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  10956. {
  10957. const ScopedLockType lock2 (getLock());
  10958. if (startIndex < 0)
  10959. {
  10960. jassertfalse;
  10961. startIndex = 0;
  10962. }
  10963. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  10964. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  10965. if (numElementsToAdd > 0)
  10966. {
  10967. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  10968. while (--numElementsToAdd >= 0)
  10969. add (arrayToAddFrom.getUnchecked (startIndex++));
  10970. }
  10971. }
  10972. }
  10973. /** Inserts a new object into the array assuming that the array is sorted.
  10974. This will use a comparator to find the position at which the new object
  10975. should go. If the array isn't sorted, the behaviour of this
  10976. method will be unpredictable.
  10977. @param comparator the comparator object to use to compare the elements - see the
  10978. sort() method for details about this object's form
  10979. @param newObject the new object to insert to the array
  10980. @returns the index at which the new object was added
  10981. @see add, sort
  10982. */
  10983. template <class ElementComparator>
  10984. int addSorted (ElementComparator& comparator, ObjectClass* newObject) throw()
  10985. {
  10986. const ScopedLockType lock (getLock());
  10987. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  10988. insert (index, newObject);
  10989. return index;
  10990. }
  10991. /** Inserts or replaces an object in the array, assuming it is sorted.
  10992. This is similar to addSorted, but if a matching element already exists, then it will be
  10993. replaced by the new one, rather than the new one being added as well.
  10994. */
  10995. template <class ElementComparator>
  10996. void addOrReplaceSorted (ElementComparator& comparator,
  10997. ObjectClass* newObject) throw()
  10998. {
  10999. const ScopedLockType lock (getLock());
  11000. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  11001. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  11002. set (index - 1, newObject); // replace an existing object that matches
  11003. else
  11004. insert (index, newObject); // no match, so insert the new one
  11005. }
  11006. /** Removes an object from the array.
  11007. This will remove the object at a given index and move back all the
  11008. subsequent objects to close the gap.
  11009. If the index passed in is out-of-range, nothing will happen.
  11010. The object that is removed will have its reference count decreased,
  11011. and may be deleted if not referenced from elsewhere.
  11012. @param indexToRemove the index of the element to remove
  11013. @see removeObject, removeRange
  11014. */
  11015. void remove (const int indexToRemove)
  11016. {
  11017. const ScopedLockType lock (getLock());
  11018. if (isPositiveAndBelow (indexToRemove, numUsed))
  11019. {
  11020. ObjectClass** const e = data.elements + indexToRemove;
  11021. if (*e != 0)
  11022. (*e)->decReferenceCount();
  11023. --numUsed;
  11024. const int numberToShift = numUsed - indexToRemove;
  11025. if (numberToShift > 0)
  11026. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11027. if ((numUsed << 1) < data.numAllocated)
  11028. minimiseStorageOverheads();
  11029. }
  11030. }
  11031. /** Removes and returns an object from the array.
  11032. This will remove the object at a given index and return it, moving back all
  11033. the subsequent objects to close the gap. If the index passed in is out-of-range,
  11034. nothing will happen and a null pointer will be returned.
  11035. @param indexToRemove the index of the element to remove
  11036. @see remove, removeObject, removeRange
  11037. */
  11038. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  11039. {
  11040. ObjectClassPtr removedItem;
  11041. const ScopedLockType lock (getLock());
  11042. if (isPositiveAndBelow (indexToRemove, numUsed))
  11043. {
  11044. ObjectClass** const e = data.elements + indexToRemove;
  11045. if (*e != 0)
  11046. {
  11047. removedItem = *e;
  11048. (*e)->decReferenceCount();
  11049. }
  11050. --numUsed;
  11051. const int numberToShift = numUsed - indexToRemove;
  11052. if (numberToShift > 0)
  11053. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  11054. if ((numUsed << 1) < data.numAllocated)
  11055. minimiseStorageOverheads();
  11056. }
  11057. return removedItem;
  11058. }
  11059. /** Removes the first occurrence of a specified object from the array.
  11060. If the item isn't found, no action is taken. If it is found, it is
  11061. removed and has its reference count decreased.
  11062. @param objectToRemove the object to try to remove
  11063. @see remove, removeRange
  11064. */
  11065. void removeObject (ObjectClass* const objectToRemove)
  11066. {
  11067. const ScopedLockType lock (getLock());
  11068. remove (indexOf (objectToRemove));
  11069. }
  11070. /** Removes a range of objects from the array.
  11071. This will remove a set of objects, starting from the given index,
  11072. and move any subsequent elements down to close the gap.
  11073. If the range extends beyond the bounds of the array, it will
  11074. be safely clipped to the size of the array.
  11075. The objects that are removed will have their reference counts decreased,
  11076. and may be deleted if not referenced from elsewhere.
  11077. @param startIndex the index of the first object to remove
  11078. @param numberToRemove how many objects should be removed
  11079. @see remove, removeObject
  11080. */
  11081. void removeRange (const int startIndex,
  11082. const int numberToRemove)
  11083. {
  11084. const ScopedLockType lock (getLock());
  11085. const int start = jlimit (0, numUsed, startIndex);
  11086. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  11087. if (end > start)
  11088. {
  11089. int i;
  11090. for (i = start; i < end; ++i)
  11091. {
  11092. if (data.elements[i] != 0)
  11093. {
  11094. data.elements[i]->decReferenceCount();
  11095. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  11096. }
  11097. }
  11098. const int rangeSize = end - start;
  11099. ObjectClass** e = data.elements + start;
  11100. i = numUsed - end;
  11101. numUsed -= rangeSize;
  11102. while (--i >= 0)
  11103. {
  11104. *e = e [rangeSize];
  11105. ++e;
  11106. }
  11107. if ((numUsed << 1) < data.numAllocated)
  11108. minimiseStorageOverheads();
  11109. }
  11110. }
  11111. /** Removes the last n objects from the array.
  11112. The objects that are removed will have their reference counts decreased,
  11113. and may be deleted if not referenced from elsewhere.
  11114. @param howManyToRemove how many objects to remove from the end of the array
  11115. @see remove, removeObject, removeRange
  11116. */
  11117. void removeLast (int howManyToRemove = 1)
  11118. {
  11119. const ScopedLockType lock (getLock());
  11120. if (howManyToRemove > numUsed)
  11121. howManyToRemove = numUsed;
  11122. while (--howManyToRemove >= 0)
  11123. remove (numUsed - 1);
  11124. }
  11125. /** Swaps a pair of objects in the array.
  11126. If either of the indexes passed in is out-of-range, nothing will happen,
  11127. otherwise the two objects at these positions will be exchanged.
  11128. */
  11129. void swap (const int index1,
  11130. const int index2) throw()
  11131. {
  11132. const ScopedLockType lock (getLock());
  11133. if (isPositiveAndBelow (index1, numUsed)
  11134. && isPositiveAndBelow (index2, numUsed))
  11135. {
  11136. swapVariables (data.elements [index1],
  11137. data.elements [index2]);
  11138. }
  11139. }
  11140. /** Moves one of the objects to a different position.
  11141. This will move the object to a specified index, shuffling along
  11142. any intervening elements as required.
  11143. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  11144. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  11145. @param currentIndex the index of the object to be moved. If this isn't a
  11146. valid index, then nothing will be done
  11147. @param newIndex the index at which you'd like this object to end up. If this
  11148. is less than zero, it will be moved to the end of the array
  11149. */
  11150. void move (const int currentIndex,
  11151. int newIndex) throw()
  11152. {
  11153. if (currentIndex != newIndex)
  11154. {
  11155. const ScopedLockType lock (getLock());
  11156. if (isPositiveAndBelow (currentIndex, numUsed))
  11157. {
  11158. if (! isPositiveAndBelow (newIndex, numUsed))
  11159. newIndex = numUsed - 1;
  11160. ObjectClass* const value = data.elements [currentIndex];
  11161. if (newIndex > currentIndex)
  11162. {
  11163. memmove (data.elements + currentIndex,
  11164. data.elements + currentIndex + 1,
  11165. (newIndex - currentIndex) * sizeof (ObjectClass*));
  11166. }
  11167. else
  11168. {
  11169. memmove (data.elements + newIndex + 1,
  11170. data.elements + newIndex,
  11171. (currentIndex - newIndex) * sizeof (ObjectClass*));
  11172. }
  11173. data.elements [newIndex] = value;
  11174. }
  11175. }
  11176. }
  11177. /** This swaps the contents of this array with those of another array.
  11178. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  11179. because it just swaps their internal pointers.
  11180. */
  11181. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  11182. {
  11183. const ScopedLockType lock1 (getLock());
  11184. const ScopedLockType lock2 (otherArray.getLock());
  11185. data.swapWith (otherArray.data);
  11186. swapVariables (numUsed, otherArray.numUsed);
  11187. }
  11188. /** Compares this array to another one.
  11189. @returns true only if the other array contains the same objects in the same order
  11190. */
  11191. bool operator== (const ReferenceCountedArray& other) const throw()
  11192. {
  11193. const ScopedLockType lock2 (other.getLock());
  11194. const ScopedLockType lock1 (getLock());
  11195. if (numUsed != other.numUsed)
  11196. return false;
  11197. for (int i = numUsed; --i >= 0;)
  11198. if (data.elements [i] != other.data.elements [i])
  11199. return false;
  11200. return true;
  11201. }
  11202. /** Compares this array to another one.
  11203. @see operator==
  11204. */
  11205. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  11206. {
  11207. return ! operator== (other);
  11208. }
  11209. /** Sorts the elements in the array.
  11210. This will use a comparator object to sort the elements into order. The object
  11211. passed must have a method of the form:
  11212. @code
  11213. int compareElements (ElementType first, ElementType second);
  11214. @endcode
  11215. ..and this method must return:
  11216. - a value of < 0 if the first comes before the second
  11217. - a value of 0 if the two objects are equivalent
  11218. - a value of > 0 if the second comes before the first
  11219. To improve performance, the compareElements() method can be declared as static or const.
  11220. @param comparator the comparator to use for comparing elements.
  11221. @param retainOrderOfEquivalentItems if this is true, then items
  11222. which the comparator says are equivalent will be
  11223. kept in the order in which they currently appear
  11224. in the array. This is slower to perform, but may
  11225. be important in some cases. If it's false, a faster
  11226. algorithm is used, but equivalent elements may be
  11227. rearranged.
  11228. @see sortArray
  11229. */
  11230. template <class ElementComparator>
  11231. void sort (ElementComparator& comparator,
  11232. const bool retainOrderOfEquivalentItems = false) const throw()
  11233. {
  11234. (void) comparator; // if you pass in an object with a static compareElements() method, this
  11235. // avoids getting warning messages about the parameter being unused
  11236. const ScopedLockType lock (getLock());
  11237. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  11238. }
  11239. /** Reduces the amount of storage being used by the array.
  11240. Arrays typically allocate slightly more storage than they need, and after
  11241. removing elements, they may have quite a lot of unused space allocated.
  11242. This method will reduce the amount of allocated storage to a minimum.
  11243. */
  11244. void minimiseStorageOverheads() throw()
  11245. {
  11246. const ScopedLockType lock (getLock());
  11247. data.shrinkToNoMoreThan (numUsed);
  11248. }
  11249. /** Returns the CriticalSection that locks this array.
  11250. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11251. an object of ScopedLockType as an RAII lock for it.
  11252. */
  11253. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  11254. /** Returns the type of scoped lock to use for locking this array */
  11255. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11256. private:
  11257. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  11258. int numUsed;
  11259. };
  11260. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  11261. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  11262. #endif
  11263. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11264. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  11265. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11266. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11267. /**
  11268. Helper class providing an RAII-based mechanism for temporarily setting and
  11269. then re-setting a value.
  11270. E.g. @code
  11271. int x = 1;
  11272. {
  11273. ScopedValueSetter setter (x, 2);
  11274. // x is now 2
  11275. }
  11276. // x is now 1 again
  11277. {
  11278. ScopedValueSetter setter (x, 3, 4);
  11279. // x is now 3
  11280. }
  11281. // x is now 4
  11282. @endcode
  11283. */
  11284. template <typename ValueType>
  11285. class ScopedValueSetter
  11286. {
  11287. public:
  11288. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11289. given new value, and will then reset it to its original value when this object is deleted.
  11290. */
  11291. ScopedValueSetter (ValueType& valueToSet,
  11292. const ValueType& newValue)
  11293. : value (valueToSet),
  11294. originalValue (valueToSet)
  11295. {
  11296. valueToSet = newValue;
  11297. }
  11298. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  11299. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  11300. */
  11301. ScopedValueSetter (ValueType& valueToSet,
  11302. const ValueType& newValue,
  11303. const ValueType& valueWhenDeleted)
  11304. : value (valueToSet),
  11305. originalValue (valueWhenDeleted)
  11306. {
  11307. valueToSet = newValue;
  11308. }
  11309. ~ScopedValueSetter()
  11310. {
  11311. value = originalValue;
  11312. }
  11313. private:
  11314. ValueType& value;
  11315. const ValueType originalValue;
  11316. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  11317. };
  11318. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  11319. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  11320. #endif
  11321. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11322. /*** Start of inlined file: juce_SortedSet.h ***/
  11323. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  11324. #define __JUCE_SORTEDSET_JUCEHEADER__
  11325. #if JUCE_MSVC
  11326. #pragma warning (push)
  11327. #pragma warning (disable: 4512)
  11328. #endif
  11329. /**
  11330. Holds a set of unique primitive objects, such as ints or doubles.
  11331. A set can only hold one item with a given value, so if for example it's a
  11332. set of integers, attempting to add the same integer twice will do nothing
  11333. the second time.
  11334. Internally, the list of items is kept sorted (which means that whatever
  11335. kind of primitive type is used must support the ==, <, >, <= and >= operators
  11336. to determine the order), and searching the set for known values is very fast
  11337. because it uses a binary-chop method.
  11338. Note that if you're using a class or struct as the element type, it must be
  11339. capable of being copied or moved with a straightforward memcpy, rather than
  11340. needing construction and destruction code.
  11341. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  11342. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  11343. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  11344. */
  11345. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  11346. class SortedSet
  11347. {
  11348. public:
  11349. /** Creates an empty set. */
  11350. SortedSet() throw()
  11351. : numUsed (0)
  11352. {
  11353. }
  11354. /** Creates a copy of another set.
  11355. @param other the set to copy
  11356. */
  11357. SortedSet (const SortedSet& other) throw()
  11358. {
  11359. const ScopedLockType lock (other.getLock());
  11360. numUsed = other.numUsed;
  11361. data.setAllocatedSize (other.numUsed);
  11362. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11363. }
  11364. /** Destructor. */
  11365. ~SortedSet() throw()
  11366. {
  11367. }
  11368. /** Copies another set over this one.
  11369. @param other the set to copy
  11370. */
  11371. SortedSet& operator= (const SortedSet& other) throw()
  11372. {
  11373. if (this != &other)
  11374. {
  11375. const ScopedLockType lock1 (other.getLock());
  11376. const ScopedLockType lock2 (getLock());
  11377. data.ensureAllocatedSize (other.size());
  11378. numUsed = other.numUsed;
  11379. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  11380. minimiseStorageOverheads();
  11381. }
  11382. return *this;
  11383. }
  11384. /** Compares this set to another one.
  11385. Two sets are considered equal if they both contain the same set of
  11386. elements.
  11387. @param other the other set to compare with
  11388. */
  11389. bool operator== (const SortedSet<ElementType>& other) const throw()
  11390. {
  11391. const ScopedLockType lock (getLock());
  11392. if (numUsed != other.numUsed)
  11393. return false;
  11394. for (int i = numUsed; --i >= 0;)
  11395. if (data.elements[i] != other.data.elements[i])
  11396. return false;
  11397. return true;
  11398. }
  11399. /** Compares this set to another one.
  11400. Two sets are considered equal if they both contain the same set of
  11401. elements.
  11402. @param other the other set to compare with
  11403. */
  11404. bool operator!= (const SortedSet<ElementType>& other) const throw()
  11405. {
  11406. return ! operator== (other);
  11407. }
  11408. /** Removes all elements from the set.
  11409. This will remove all the elements, and free any storage that the set is
  11410. using. To clear it without freeing the storage, use the clearQuick()
  11411. method instead.
  11412. @see clearQuick
  11413. */
  11414. void clear() throw()
  11415. {
  11416. const ScopedLockType lock (getLock());
  11417. data.setAllocatedSize (0);
  11418. numUsed = 0;
  11419. }
  11420. /** Removes all elements from the set without freeing the array's allocated storage.
  11421. @see clear
  11422. */
  11423. void clearQuick() throw()
  11424. {
  11425. const ScopedLockType lock (getLock());
  11426. numUsed = 0;
  11427. }
  11428. /** Returns the current number of elements in the set.
  11429. */
  11430. inline int size() const throw()
  11431. {
  11432. return numUsed;
  11433. }
  11434. /** Returns one of the elements in the set.
  11435. If the index passed in is beyond the range of valid elements, this
  11436. will return zero.
  11437. If you're certain that the index will always be a valid element, you
  11438. can call getUnchecked() instead, which is faster.
  11439. @param index the index of the element being requested (0 is the first element in the set)
  11440. @see getUnchecked, getFirst, getLast
  11441. */
  11442. inline ElementType operator[] (const int index) const throw()
  11443. {
  11444. const ScopedLockType lock (getLock());
  11445. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  11446. : ElementType();
  11447. }
  11448. /** Returns one of the elements in the set, without checking the index passed in.
  11449. Unlike the operator[] method, this will try to return an element without
  11450. checking that the index is within the bounds of the set, so should only
  11451. be used when you're confident that it will always be a valid index.
  11452. @param index the index of the element being requested (0 is the first element in the set)
  11453. @see operator[], getFirst, getLast
  11454. */
  11455. inline ElementType getUnchecked (const int index) const throw()
  11456. {
  11457. const ScopedLockType lock (getLock());
  11458. jassert (isPositiveAndBelow (index, numUsed));
  11459. return data.elements [index];
  11460. }
  11461. /** Returns the first element in the set, or 0 if the set is empty.
  11462. @see operator[], getUnchecked, getLast
  11463. */
  11464. inline ElementType getFirst() const throw()
  11465. {
  11466. const ScopedLockType lock (getLock());
  11467. return numUsed > 0 ? data.elements [0] : ElementType();
  11468. }
  11469. /** Returns the last element in the set, or 0 if the set is empty.
  11470. @see operator[], getUnchecked, getFirst
  11471. */
  11472. inline ElementType getLast() const throw()
  11473. {
  11474. const ScopedLockType lock (getLock());
  11475. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  11476. }
  11477. /** Finds the index of the first element which matches the value passed in.
  11478. This will search the set for the given object, and return the index
  11479. of its first occurrence. If the object isn't found, the method will return -1.
  11480. @param elementToLookFor the value or object to look for
  11481. @returns the index of the object, or -1 if it's not found
  11482. */
  11483. int indexOf (const ElementType elementToLookFor) const throw()
  11484. {
  11485. const ScopedLockType lock (getLock());
  11486. int start = 0;
  11487. int end = numUsed;
  11488. for (;;)
  11489. {
  11490. if (start >= end)
  11491. {
  11492. return -1;
  11493. }
  11494. else if (elementToLookFor == data.elements [start])
  11495. {
  11496. return start;
  11497. }
  11498. else
  11499. {
  11500. const int halfway = (start + end) >> 1;
  11501. if (halfway == start)
  11502. return -1;
  11503. else if (elementToLookFor >= data.elements [halfway])
  11504. start = halfway;
  11505. else
  11506. end = halfway;
  11507. }
  11508. }
  11509. }
  11510. /** Returns true if the set contains at least one occurrence of an object.
  11511. @param elementToLookFor the value or object to look for
  11512. @returns true if the item is found
  11513. */
  11514. bool contains (const ElementType elementToLookFor) const throw()
  11515. {
  11516. const ScopedLockType lock (getLock());
  11517. int start = 0;
  11518. int end = numUsed;
  11519. for (;;)
  11520. {
  11521. if (start >= end)
  11522. {
  11523. return false;
  11524. }
  11525. else if (elementToLookFor == data.elements [start])
  11526. {
  11527. return true;
  11528. }
  11529. else
  11530. {
  11531. const int halfway = (start + end) >> 1;
  11532. if (halfway == start)
  11533. return false;
  11534. else if (elementToLookFor >= data.elements [halfway])
  11535. start = halfway;
  11536. else
  11537. end = halfway;
  11538. }
  11539. }
  11540. }
  11541. /** Adds a new element to the set, (as long as it's not already in there).
  11542. @param newElement the new object to add to the set
  11543. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  11544. */
  11545. void add (const ElementType newElement) throw()
  11546. {
  11547. const ScopedLockType lock (getLock());
  11548. int start = 0;
  11549. int end = numUsed;
  11550. for (;;)
  11551. {
  11552. if (start >= end)
  11553. {
  11554. jassert (start <= end);
  11555. insertInternal (start, newElement);
  11556. break;
  11557. }
  11558. else if (newElement == data.elements [start])
  11559. {
  11560. break;
  11561. }
  11562. else
  11563. {
  11564. const int halfway = (start + end) >> 1;
  11565. if (halfway == start)
  11566. {
  11567. if (newElement >= data.elements [halfway])
  11568. insertInternal (start + 1, newElement);
  11569. else
  11570. insertInternal (start, newElement);
  11571. break;
  11572. }
  11573. else if (newElement >= data.elements [halfway])
  11574. start = halfway;
  11575. else
  11576. end = halfway;
  11577. }
  11578. }
  11579. }
  11580. /** Adds elements from an array to this set.
  11581. @param elementsToAdd the array of elements to add
  11582. @param numElementsToAdd how many elements are in this other array
  11583. @see add
  11584. */
  11585. void addArray (const ElementType* elementsToAdd,
  11586. int numElementsToAdd) throw()
  11587. {
  11588. const ScopedLockType lock (getLock());
  11589. while (--numElementsToAdd >= 0)
  11590. add (*elementsToAdd++);
  11591. }
  11592. /** Adds elements from another set to this one.
  11593. @param setToAddFrom the set from which to copy the elements
  11594. @param startIndex the first element of the other set to start copying from
  11595. @param numElementsToAdd how many elements to add from the other set. If this
  11596. value is negative or greater than the number of available elements,
  11597. all available elements will be copied.
  11598. @see add
  11599. */
  11600. template <class OtherSetType>
  11601. void addSet (const OtherSetType& setToAddFrom,
  11602. int startIndex = 0,
  11603. int numElementsToAdd = -1) throw()
  11604. {
  11605. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  11606. {
  11607. const ScopedLockType lock2 (getLock());
  11608. jassert (this != &setToAddFrom);
  11609. if (this != &setToAddFrom)
  11610. {
  11611. if (startIndex < 0)
  11612. {
  11613. jassertfalse;
  11614. startIndex = 0;
  11615. }
  11616. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  11617. numElementsToAdd = setToAddFrom.size() - startIndex;
  11618. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  11619. }
  11620. }
  11621. }
  11622. /** Removes an element from the set.
  11623. This will remove the element at a given index.
  11624. If the index passed in is out-of-range, nothing will happen.
  11625. @param indexToRemove the index of the element to remove
  11626. @returns the element that has been removed
  11627. @see removeValue, removeRange
  11628. */
  11629. ElementType remove (const int indexToRemove) throw()
  11630. {
  11631. const ScopedLockType lock (getLock());
  11632. if (isPositiveAndBelow (indexToRemove, numUsed))
  11633. {
  11634. --numUsed;
  11635. ElementType* const e = data.elements + indexToRemove;
  11636. ElementType const removed = *e;
  11637. const int numberToShift = numUsed - indexToRemove;
  11638. if (numberToShift > 0)
  11639. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  11640. if ((numUsed << 1) < data.numAllocated)
  11641. minimiseStorageOverheads();
  11642. return removed;
  11643. }
  11644. return 0;
  11645. }
  11646. /** Removes an item from the set.
  11647. This will remove the given element from the set, if it's there.
  11648. @param valueToRemove the object to try to remove
  11649. @see remove, removeRange
  11650. */
  11651. void removeValue (const ElementType valueToRemove) throw()
  11652. {
  11653. const ScopedLockType lock (getLock());
  11654. remove (indexOf (valueToRemove));
  11655. }
  11656. /** Removes any elements which are also in another set.
  11657. @param otherSet the other set in which to look for elements to remove
  11658. @see removeValuesNotIn, remove, removeValue, removeRange
  11659. */
  11660. template <class OtherSetType>
  11661. void removeValuesIn (const OtherSetType& otherSet) throw()
  11662. {
  11663. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11664. const ScopedLockType lock2 (getLock());
  11665. if (this == &otherSet)
  11666. {
  11667. clear();
  11668. }
  11669. else
  11670. {
  11671. if (otherSet.size() > 0)
  11672. {
  11673. for (int i = numUsed; --i >= 0;)
  11674. if (otherSet.contains (data.elements [i]))
  11675. remove (i);
  11676. }
  11677. }
  11678. }
  11679. /** Removes any elements which are not found in another set.
  11680. Only elements which occur in this other set will be retained.
  11681. @param otherSet the set in which to look for elements NOT to remove
  11682. @see removeValuesIn, remove, removeValue, removeRange
  11683. */
  11684. template <class OtherSetType>
  11685. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  11686. {
  11687. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11688. const ScopedLockType lock2 (getLock());
  11689. if (this != &otherSet)
  11690. {
  11691. if (otherSet.size() <= 0)
  11692. {
  11693. clear();
  11694. }
  11695. else
  11696. {
  11697. for (int i = numUsed; --i >= 0;)
  11698. if (! otherSet.contains (data.elements [i]))
  11699. remove (i);
  11700. }
  11701. }
  11702. }
  11703. /** Reduces the amount of storage being used by the set.
  11704. Sets typically allocate slightly more storage than they need, and after
  11705. removing elements, they may have quite a lot of unused space allocated.
  11706. This method will reduce the amount of allocated storage to a minimum.
  11707. */
  11708. void minimiseStorageOverheads() throw()
  11709. {
  11710. const ScopedLockType lock (getLock());
  11711. data.shrinkToNoMoreThan (numUsed);
  11712. }
  11713. /** Returns the CriticalSection that locks this array.
  11714. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11715. an object of ScopedLockType as an RAII lock for it.
  11716. */
  11717. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  11718. /** Returns the type of scoped lock to use for locking this array */
  11719. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11720. private:
  11721. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  11722. int numUsed;
  11723. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  11724. {
  11725. data.ensureAllocatedSize (numUsed + 1);
  11726. ElementType* const insertPos = data.elements + indexToInsertAt;
  11727. const int numberToMove = numUsed - indexToInsertAt;
  11728. if (numberToMove > 0)
  11729. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  11730. *insertPos = newElement;
  11731. ++numUsed;
  11732. }
  11733. };
  11734. #if JUCE_MSVC
  11735. #pragma warning (pop)
  11736. #endif
  11737. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  11738. /*** End of inlined file: juce_SortedSet.h ***/
  11739. #endif
  11740. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11741. /*** Start of inlined file: juce_SparseSet.h ***/
  11742. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11743. #define __JUCE_SPARSESET_JUCEHEADER__
  11744. /*** Start of inlined file: juce_Range.h ***/
  11745. #ifndef __JUCE_RANGE_JUCEHEADER__
  11746. #define __JUCE_RANGE_JUCEHEADER__
  11747. /** A general-purpose range object, that simply represents any linear range with
  11748. a start and end point.
  11749. The templated parameter is expected to be a primitive integer or floating point
  11750. type, though class types could also be used if they behave in a number-like way.
  11751. */
  11752. template <typename ValueType>
  11753. class Range
  11754. {
  11755. public:
  11756. /** Constructs an empty range. */
  11757. Range() throw()
  11758. : start (ValueType()), end (ValueType())
  11759. {
  11760. }
  11761. /** Constructs a range with given start and end values. */
  11762. Range (const ValueType start_, const ValueType end_) throw()
  11763. : start (start_), end (jmax (start_, end_))
  11764. {
  11765. }
  11766. /** Constructs a copy of another range. */
  11767. Range (const Range& other) throw()
  11768. : start (other.start), end (other.end)
  11769. {
  11770. }
  11771. /** Copies another range object. */
  11772. Range& operator= (const Range& other) throw()
  11773. {
  11774. start = other.start;
  11775. end = other.end;
  11776. return *this;
  11777. }
  11778. /** Destructor. */
  11779. ~Range() throw()
  11780. {
  11781. }
  11782. /** Returns the range that lies between two positions (in either order). */
  11783. static const Range between (const ValueType position1, const ValueType position2) throw()
  11784. {
  11785. return (position1 < position2) ? Range (position1, position2)
  11786. : Range (position2, position1);
  11787. }
  11788. /** Returns a range with the specified start position and a length of zero. */
  11789. static const Range emptyRange (const ValueType start) throw()
  11790. {
  11791. return Range (start, start);
  11792. }
  11793. /** Returns the start of the range. */
  11794. inline ValueType getStart() const throw() { return start; }
  11795. /** Returns the length of the range. */
  11796. inline ValueType getLength() const throw() { return end - start; }
  11797. /** Returns the end of the range. */
  11798. inline ValueType getEnd() const throw() { return end; }
  11799. /** Returns true if the range has a length of zero. */
  11800. inline bool isEmpty() const throw() { return start == end; }
  11801. /** Changes the start position of the range, leaving the end position unchanged.
  11802. If the new start position is higher than the current end of the range, the end point
  11803. will be pushed along to equal it, leaving an empty range at the new position.
  11804. */
  11805. void setStart (const ValueType newStart) throw()
  11806. {
  11807. start = newStart;
  11808. if (end < newStart)
  11809. end = newStart;
  11810. }
  11811. /** Returns a range with the same end as this one, but a different start.
  11812. If the new start position is higher than the current end of the range, the end point
  11813. will be pushed along to equal it, returning an empty range at the new position.
  11814. */
  11815. const Range withStart (const ValueType newStart) const throw()
  11816. {
  11817. return Range (newStart, jmax (newStart, end));
  11818. }
  11819. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11820. const Range movedToStartAt (const ValueType newStart) const throw()
  11821. {
  11822. return Range (newStart, end + (newStart - start));
  11823. }
  11824. /** Changes the end position of the range, leaving the start unchanged.
  11825. If the new end position is below the current start of the range, the start point
  11826. will be pushed back to equal the new end point.
  11827. */
  11828. void setEnd (const ValueType newEnd) throw()
  11829. {
  11830. end = newEnd;
  11831. if (newEnd < start)
  11832. start = newEnd;
  11833. }
  11834. /** Returns a range with the same start position as this one, but a different end.
  11835. If the new end position is below the current start of the range, the start point
  11836. will be pushed back to equal the new end point.
  11837. */
  11838. const Range withEnd (const ValueType newEnd) const throw()
  11839. {
  11840. return Range (jmin (start, newEnd), newEnd);
  11841. }
  11842. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11843. const Range movedToEndAt (const ValueType newEnd) const throw()
  11844. {
  11845. return Range (start + (newEnd - end), newEnd);
  11846. }
  11847. /** Changes the length of the range.
  11848. Lengths less than zero are treated as zero.
  11849. */
  11850. void setLength (const ValueType newLength) throw()
  11851. {
  11852. end = start + jmax (ValueType(), newLength);
  11853. }
  11854. /** Returns a range with the same start as this one, but a different length.
  11855. Lengths less than zero are treated as zero.
  11856. */
  11857. const Range withLength (const ValueType newLength) const throw()
  11858. {
  11859. return Range (start, start + newLength);
  11860. }
  11861. /** Adds an amount to the start and end of the range. */
  11862. inline const Range& operator+= (const ValueType amountToAdd) throw()
  11863. {
  11864. start += amountToAdd;
  11865. end += amountToAdd;
  11866. return *this;
  11867. }
  11868. /** Subtracts an amount from the start and end of the range. */
  11869. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  11870. {
  11871. start -= amountToSubtract;
  11872. end -= amountToSubtract;
  11873. return *this;
  11874. }
  11875. /** Returns a range that is equal to this one with an amount added to its
  11876. start and end.
  11877. */
  11878. const Range operator+ (const ValueType amountToAdd) const throw()
  11879. {
  11880. return Range (start + amountToAdd, end + amountToAdd);
  11881. }
  11882. /** Returns a range that is equal to this one with the specified amount
  11883. subtracted from its start and end. */
  11884. const Range operator- (const ValueType amountToSubtract) const throw()
  11885. {
  11886. return Range (start - amountToSubtract, end - amountToSubtract);
  11887. }
  11888. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  11889. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  11890. /** Returns true if the given position lies inside this range. */
  11891. bool contains (const ValueType position) const throw()
  11892. {
  11893. return start <= position && position < end;
  11894. }
  11895. /** Returns the nearest value to the one supplied, which lies within the range. */
  11896. ValueType clipValue (const ValueType value) const throw()
  11897. {
  11898. return jlimit (start, end, value);
  11899. }
  11900. /** Returns true if the given range lies entirely inside this range. */
  11901. bool contains (const Range& other) const throw()
  11902. {
  11903. return start <= other.start && end >= other.end;
  11904. }
  11905. /** Returns true if the given range intersects this one. */
  11906. bool intersects (const Range& other) const throw()
  11907. {
  11908. return other.start < end && start < other.end;
  11909. }
  11910. /** Returns the range that is the intersection of the two ranges, or an empty range
  11911. with an undefined start position if they don't overlap. */
  11912. const Range getIntersectionWith (const Range& other) const throw()
  11913. {
  11914. return Range (jmax (start, other.start),
  11915. jmin (end, other.end));
  11916. }
  11917. /** Returns the smallest range that contains both this one and the other one. */
  11918. const Range getUnionWith (const Range& other) const throw()
  11919. {
  11920. return Range (jmin (start, other.start),
  11921. jmax (end, other.end));
  11922. }
  11923. /** Returns a given range, after moving it forwards or backwards to fit it
  11924. within this range.
  11925. If the supplied range has a greater length than this one, the return value
  11926. will be this range.
  11927. Otherwise, if the supplied range is smaller than this one, the return value
  11928. will be the new range, shifted forwards or backwards so that it doesn't extend
  11929. beyond this one, but keeping its original length.
  11930. */
  11931. const Range constrainRange (const Range& rangeToConstrain) const throw()
  11932. {
  11933. const ValueType otherLen = rangeToConstrain.getLength();
  11934. return getLength() <= otherLen
  11935. ? *this
  11936. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  11937. }
  11938. private:
  11939. ValueType start, end;
  11940. };
  11941. #endif // __JUCE_RANGE_JUCEHEADER__
  11942. /*** End of inlined file: juce_Range.h ***/
  11943. /**
  11944. Holds a set of primitive values, storing them as a set of ranges.
  11945. This container acts like an array, but can efficiently hold large continguous
  11946. ranges of values. It's quite a specialised class, mostly useful for things
  11947. like keeping the set of selected rows in a listbox.
  11948. The type used as a template paramter must be an integer type, such as int, short,
  11949. int64, etc.
  11950. */
  11951. template <class Type>
  11952. class SparseSet
  11953. {
  11954. public:
  11955. /** Creates a new empty set. */
  11956. SparseSet()
  11957. {
  11958. }
  11959. /** Creates a copy of another SparseSet. */
  11960. SparseSet (const SparseSet<Type>& other)
  11961. : values (other.values)
  11962. {
  11963. }
  11964. /** Clears the set. */
  11965. void clear()
  11966. {
  11967. values.clear();
  11968. }
  11969. /** Checks whether the set is empty.
  11970. This is much quicker than using (size() == 0).
  11971. */
  11972. bool isEmpty() const throw()
  11973. {
  11974. return values.size() == 0;
  11975. }
  11976. /** Returns the number of values in the set.
  11977. Because of the way the data is stored, this method can take longer if there
  11978. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  11979. are any items.
  11980. */
  11981. Type size() const
  11982. {
  11983. Type total (0);
  11984. for (int i = 0; i < values.size(); i += 2)
  11985. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  11986. return total;
  11987. }
  11988. /** Returns one of the values in the set.
  11989. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  11990. @returns the value at this index, or 0 if it's out-of-range
  11991. */
  11992. Type operator[] (Type index) const
  11993. {
  11994. for (int i = 0; i < values.size(); i += 2)
  11995. {
  11996. const Type start (values.getUnchecked (i));
  11997. const Type len (values.getUnchecked (i + 1) - start);
  11998. if (index < len)
  11999. return start + index;
  12000. index -= len;
  12001. }
  12002. return Type();
  12003. }
  12004. /** Checks whether a particular value is in the set. */
  12005. bool contains (const Type valueToLookFor) const
  12006. {
  12007. for (int i = 0; i < values.size(); ++i)
  12008. if (valueToLookFor < values.getUnchecked(i))
  12009. return (i & 1) != 0;
  12010. return false;
  12011. }
  12012. /** Returns the number of contiguous blocks of values.
  12013. @see getRange
  12014. */
  12015. int getNumRanges() const throw()
  12016. {
  12017. return values.size() >> 1;
  12018. }
  12019. /** Returns one of the contiguous ranges of values stored.
  12020. @param rangeIndex the index of the range to look up, between 0
  12021. and (getNumRanges() - 1)
  12022. @see getTotalRange
  12023. */
  12024. const Range<Type> getRange (const int rangeIndex) const
  12025. {
  12026. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  12027. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  12028. values.getUnchecked ((rangeIndex << 1) + 1));
  12029. else
  12030. return Range<Type>();
  12031. }
  12032. /** Returns the range between the lowest and highest values in the set.
  12033. @see getRange
  12034. */
  12035. const Range<Type> getTotalRange() const
  12036. {
  12037. if (values.size() > 0)
  12038. {
  12039. jassert ((values.size() & 1) == 0);
  12040. return Range<Type> (values.getUnchecked (0),
  12041. values.getUnchecked (values.size() - 1));
  12042. }
  12043. return Range<Type>();
  12044. }
  12045. /** Adds a range of contiguous values to the set.
  12046. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  12047. */
  12048. void addRange (const Range<Type>& range)
  12049. {
  12050. jassert (range.getLength() >= 0);
  12051. if (range.getLength() > 0)
  12052. {
  12053. removeRange (range);
  12054. values.addUsingDefaultSort (range.getStart());
  12055. values.addUsingDefaultSort (range.getEnd());
  12056. simplify();
  12057. }
  12058. }
  12059. /** Removes a range of values from the set.
  12060. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  12061. */
  12062. void removeRange (const Range<Type>& rangeToRemove)
  12063. {
  12064. jassert (rangeToRemove.getLength() >= 0);
  12065. if (rangeToRemove.getLength() > 0
  12066. && values.size() > 0
  12067. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  12068. && values.getUnchecked(0) < rangeToRemove.getEnd())
  12069. {
  12070. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  12071. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  12072. const bool onAtEnd = contains (lastValue);
  12073. for (int i = values.size(); --i >= 0;)
  12074. {
  12075. if (values.getUnchecked(i) <= lastValue)
  12076. {
  12077. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  12078. {
  12079. values.remove (i);
  12080. if (--i < 0)
  12081. break;
  12082. }
  12083. break;
  12084. }
  12085. }
  12086. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  12087. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  12088. simplify();
  12089. }
  12090. }
  12091. /** Does an XOR of the values in a given range. */
  12092. void invertRange (const Range<Type>& range)
  12093. {
  12094. SparseSet newItems;
  12095. newItems.addRange (range);
  12096. int i;
  12097. for (i = getNumRanges(); --i >= 0;)
  12098. newItems.removeRange (getRange (i));
  12099. removeRange (range);
  12100. for (i = newItems.getNumRanges(); --i >= 0;)
  12101. addRange (newItems.getRange(i));
  12102. }
  12103. /** Checks whether any part of a given range overlaps any part of this set. */
  12104. bool overlapsRange (const Range<Type>& range)
  12105. {
  12106. if (range.getLength() > 0)
  12107. {
  12108. for (int i = getNumRanges(); --i >= 0;)
  12109. {
  12110. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12111. return false;
  12112. if (values.getUnchecked (i << 1) < range.getEnd())
  12113. return true;
  12114. }
  12115. }
  12116. return false;
  12117. }
  12118. /** Checks whether the whole of a given range is contained within this one. */
  12119. bool containsRange (const Range<Type>& range)
  12120. {
  12121. if (range.getLength() > 0)
  12122. {
  12123. for (int i = getNumRanges(); --i >= 0;)
  12124. {
  12125. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  12126. return false;
  12127. if (values.getUnchecked (i << 1) <= range.getStart()
  12128. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  12129. return true;
  12130. }
  12131. }
  12132. return false;
  12133. }
  12134. bool operator== (const SparseSet<Type>& other) throw()
  12135. {
  12136. return values == other.values;
  12137. }
  12138. bool operator!= (const SparseSet<Type>& other) throw()
  12139. {
  12140. return values != other.values;
  12141. }
  12142. private:
  12143. // alternating start/end values of ranges of values that are present.
  12144. Array<Type, DummyCriticalSection> values;
  12145. void simplify()
  12146. {
  12147. jassert ((values.size() & 1) == 0);
  12148. for (int i = values.size(); --i > 0;)
  12149. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  12150. values.removeRange (--i, 2);
  12151. }
  12152. };
  12153. #endif // __JUCE_SPARSESET_JUCEHEADER__
  12154. /*** End of inlined file: juce_SparseSet.h ***/
  12155. #endif
  12156. #ifndef __JUCE_VALUE_JUCEHEADER__
  12157. /*** Start of inlined file: juce_Value.h ***/
  12158. #ifndef __JUCE_VALUE_JUCEHEADER__
  12159. #define __JUCE_VALUE_JUCEHEADER__
  12160. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  12161. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  12162. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  12163. /*** Start of inlined file: juce_CallbackMessage.h ***/
  12164. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12165. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12166. /*** Start of inlined file: juce_Message.h ***/
  12167. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  12168. #define __JUCE_MESSAGE_JUCEHEADER__
  12169. class MessageListener;
  12170. class MessageManager;
  12171. /** The base class for objects that can be delivered to a MessageListener.
  12172. The simplest Message object contains a few integer and pointer parameters
  12173. that the user can set, and this is enough for a lot of purposes. For passing more
  12174. complex data, subclasses of Message can also be used.
  12175. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12176. */
  12177. class JUCE_API Message : public ReferenceCountedObject
  12178. {
  12179. public:
  12180. /** Creates an uninitialised message.
  12181. The class's variables will also be left uninitialised.
  12182. */
  12183. Message() throw();
  12184. /** Creates a message object, filling in the member variables.
  12185. The corresponding public member variables will be set from the parameters
  12186. passed in.
  12187. */
  12188. Message (int intParameter1,
  12189. int intParameter2,
  12190. int intParameter3,
  12191. void* pointerParameter) throw();
  12192. /** Destructor. */
  12193. virtual ~Message();
  12194. // These values can be used for carrying simple data that the application needs to
  12195. // pass around. For more complex messages, just create a subclass.
  12196. int intParameter1; /**< user-defined integer value. */
  12197. int intParameter2; /**< user-defined integer value. */
  12198. int intParameter3; /**< user-defined integer value. */
  12199. void* pointerParameter; /**< user-defined pointer value. */
  12200. /** A typedef for pointers to messages. */
  12201. typedef ReferenceCountedObjectPtr <Message> Ptr;
  12202. private:
  12203. friend class MessageListener;
  12204. friend class MessageManager;
  12205. MessageListener* messageRecipient;
  12206. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Message);
  12207. };
  12208. #endif // __JUCE_MESSAGE_JUCEHEADER__
  12209. /*** End of inlined file: juce_Message.h ***/
  12210. /**
  12211. A message that calls a custom function when it gets delivered.
  12212. You can use this class to fire off actions that you want to be performed later
  12213. on the message thread.
  12214. Unlike other Message objects, these don't get sent to a MessageListener, you
  12215. just call the post() method to send them, and when they arrive, your
  12216. messageCallback() method will automatically be invoked.
  12217. Always create an instance of a CallbackMessage on the heap, as it will be
  12218. deleted automatically after the message has been delivered.
  12219. @see MessageListener, MessageManager, ActionListener, ChangeListener
  12220. */
  12221. class JUCE_API CallbackMessage : public Message
  12222. {
  12223. public:
  12224. CallbackMessage() throw();
  12225. /** Destructor. */
  12226. ~CallbackMessage();
  12227. /** Called when the message is delivered.
  12228. You should implement this method and make it do whatever action you want
  12229. to perform.
  12230. Note that like all other messages, this object will be deleted immediately
  12231. after this method has been invoked.
  12232. */
  12233. virtual void messageCallback() = 0;
  12234. /** Instead of sending this message to a MessageListener, just call this method
  12235. to post it to the event queue.
  12236. After you've called this, this object will belong to the MessageManager,
  12237. which will delete it later. So make sure you don't delete the object yourself,
  12238. call post() more than once, or call post() on a stack-based obect!
  12239. */
  12240. void post();
  12241. private:
  12242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackMessage);
  12243. };
  12244. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  12245. /*** End of inlined file: juce_CallbackMessage.h ***/
  12246. /**
  12247. Has a callback method that is triggered asynchronously.
  12248. This object allows an asynchronous callback function to be triggered, for
  12249. tasks such as coalescing multiple updates into a single callback later on.
  12250. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  12251. message thread calling handleAsyncUpdate() as soon as it can.
  12252. */
  12253. class JUCE_API AsyncUpdater
  12254. {
  12255. public:
  12256. /** Creates an AsyncUpdater object. */
  12257. AsyncUpdater();
  12258. /** Destructor.
  12259. If there are any pending callbacks when the object is deleted, these are lost.
  12260. */
  12261. virtual ~AsyncUpdater();
  12262. /** Causes the callback to be triggered at a later time.
  12263. This method returns immediately, having made sure that a callback
  12264. to the handleAsyncUpdate() method will occur as soon as possible.
  12265. If an update callback is already pending but hasn't happened yet, calls
  12266. to this method will be ignored.
  12267. It's thread-safe to call this method from any number of threads without
  12268. needing to worry about locking.
  12269. */
  12270. void triggerAsyncUpdate();
  12271. /** This will stop any pending updates from happening.
  12272. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  12273. callback happens, this will cancel the handleAsyncUpdate() callback.
  12274. Note that this method simply cancels the next callback - if a callback is already
  12275. in progress on a different thread, this won't block until it finishes, so there's
  12276. no guarantee that the callback isn't still running when you return from
  12277. */
  12278. void cancelPendingUpdate() throw();
  12279. /** If an update has been triggered and is pending, this will invoke it
  12280. synchronously.
  12281. Use this as a kind of "flush" operation - if an update is pending, the
  12282. handleAsyncUpdate() method will be called immediately; if no update is
  12283. pending, then nothing will be done.
  12284. Because this may invoke the callback, this method must only be called on
  12285. the main event thread.
  12286. */
  12287. void handleUpdateNowIfNeeded();
  12288. /** Returns true if there's an update callback in the pipeline. */
  12289. bool isUpdatePending() const throw();
  12290. /** Called back to do whatever your class needs to do.
  12291. This method is called by the message thread at the next convenient time
  12292. after the triggerAsyncUpdate() method has been called.
  12293. */
  12294. virtual void handleAsyncUpdate() = 0;
  12295. private:
  12296. ReferenceCountedObjectPtr<CallbackMessage> message;
  12297. Atomic<int>& getDeliveryFlag() const throw();
  12298. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  12299. };
  12300. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  12301. /*** End of inlined file: juce_AsyncUpdater.h ***/
  12302. /*** Start of inlined file: juce_ListenerList.h ***/
  12303. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  12304. #define __JUCE_LISTENERLIST_JUCEHEADER__
  12305. /**
  12306. Holds a set of objects and can invoke a member function callback on each object
  12307. in the set with a single call.
  12308. Use a ListenerList to manage a set of objects which need a callback, and you
  12309. can invoke a member function by simply calling call() or callChecked().
  12310. E.g.
  12311. @code
  12312. class MyListenerType
  12313. {
  12314. public:
  12315. void myCallbackMethod (int foo, bool bar);
  12316. };
  12317. ListenerList <MyListenerType> listeners;
  12318. listeners.add (someCallbackObjects...);
  12319. // This will invoke myCallbackMethod (1234, true) on each of the objects
  12320. // in the list...
  12321. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  12322. @endcode
  12323. If you add or remove listeners from the list during one of the callbacks - i.e. while
  12324. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  12325. will be mistakenly called after they've been removed, but it may mean that some of the
  12326. listeners could be called more than once, or not at all, depending on the list's order.
  12327. Sometimes, there's a chance that invoking one of the callbacks might result in the
  12328. list itself being deleted while it's still iterating - to survive this situation, you can
  12329. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  12330. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  12331. the list will check this after each callback to determine whether it should abort the
  12332. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  12333. which can be used to check when a Component has been deleted. See also
  12334. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  12335. */
  12336. template <class ListenerClass,
  12337. class ArrayType = Array <ListenerClass*> >
  12338. class ListenerList
  12339. {
  12340. // Horrible macros required to support VC6/7..
  12341. #ifndef DOXYGEN
  12342. #if JUCE_VC8_OR_EARLIER
  12343. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  12344. #define LL_PARAM(a) Q##a& param##a
  12345. #else
  12346. #define LL_TEMPLATE(a) typename P##a
  12347. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  12348. #endif
  12349. #endif
  12350. public:
  12351. /** Creates an empty list. */
  12352. ListenerList()
  12353. {
  12354. }
  12355. /** Destructor. */
  12356. ~ListenerList()
  12357. {
  12358. }
  12359. /** Adds a listener to the list.
  12360. A listener can only be added once, so if the listener is already in the list,
  12361. this method has no effect.
  12362. @see remove
  12363. */
  12364. void add (ListenerClass* const listenerToAdd)
  12365. {
  12366. // Listeners can't be null pointers!
  12367. jassert (listenerToAdd != 0);
  12368. if (listenerToAdd != 0)
  12369. listeners.addIfNotAlreadyThere (listenerToAdd);
  12370. }
  12371. /** Removes a listener from the list.
  12372. If the listener wasn't in the list, this has no effect.
  12373. */
  12374. void remove (ListenerClass* const listenerToRemove)
  12375. {
  12376. // Listeners can't be null pointers!
  12377. jassert (listenerToRemove != 0);
  12378. listeners.removeValue (listenerToRemove);
  12379. }
  12380. /** Returns the number of registered listeners. */
  12381. int size() const throw()
  12382. {
  12383. return listeners.size();
  12384. }
  12385. /** Returns true if any listeners are registered. */
  12386. bool isEmpty() const throw()
  12387. {
  12388. return listeners.size() == 0;
  12389. }
  12390. /** Clears the list. */
  12391. void clear()
  12392. {
  12393. listeners.clear();
  12394. }
  12395. /** Returns true if the specified listener has been added to the list. */
  12396. bool contains (ListenerClass* const listener) const throw()
  12397. {
  12398. return listeners.contains (listener);
  12399. }
  12400. /** Calls a member function on each listener in the list, with no parameters. */
  12401. void call (void (ListenerClass::*callbackFunction) ())
  12402. {
  12403. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  12404. }
  12405. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  12406. See the class description for info about writing a bail-out checker. */
  12407. template <class BailOutCheckerType>
  12408. void callChecked (const BailOutCheckerType& bailOutChecker,
  12409. void (ListenerClass::*callbackFunction) ())
  12410. {
  12411. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12412. (iter.getListener()->*callbackFunction) ();
  12413. }
  12414. /** Calls a member function on each listener in the list, with 1 parameter. */
  12415. template <LL_TEMPLATE(1)>
  12416. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  12417. {
  12418. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12419. (iter.getListener()->*callbackFunction) (param1);
  12420. }
  12421. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  12422. See the class description for info about writing a bail-out checker. */
  12423. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  12424. void callChecked (const BailOutCheckerType& bailOutChecker,
  12425. void (ListenerClass::*callbackFunction) (P1),
  12426. LL_PARAM(1))
  12427. {
  12428. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12429. (iter.getListener()->*callbackFunction) (param1);
  12430. }
  12431. /** Calls a member function on each listener in the list, with 2 parameters. */
  12432. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12433. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  12434. LL_PARAM(1), LL_PARAM(2))
  12435. {
  12436. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12437. (iter.getListener()->*callbackFunction) (param1, param2);
  12438. }
  12439. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  12440. See the class description for info about writing a bail-out checker. */
  12441. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  12442. void callChecked (const BailOutCheckerType& bailOutChecker,
  12443. void (ListenerClass::*callbackFunction) (P1, P2),
  12444. LL_PARAM(1), LL_PARAM(2))
  12445. {
  12446. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12447. (iter.getListener()->*callbackFunction) (param1, param2);
  12448. }
  12449. /** Calls a member function on each listener in the list, with 3 parameters. */
  12450. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12451. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12452. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12453. {
  12454. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12455. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12456. }
  12457. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  12458. See the class description for info about writing a bail-out checker. */
  12459. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  12460. void callChecked (const BailOutCheckerType& bailOutChecker,
  12461. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  12462. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  12463. {
  12464. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12465. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  12466. }
  12467. /** Calls a member function on each listener in the list, with 4 parameters. */
  12468. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12469. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12470. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12471. {
  12472. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12473. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12474. }
  12475. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  12476. See the class description for info about writing a bail-out checker. */
  12477. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  12478. void callChecked (const BailOutCheckerType& bailOutChecker,
  12479. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  12480. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  12481. {
  12482. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12483. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  12484. }
  12485. /** Calls a member function on each listener in the list, with 5 parameters. */
  12486. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12487. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12488. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12489. {
  12490. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  12491. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12492. }
  12493. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  12494. See the class description for info about writing a bail-out checker. */
  12495. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  12496. void callChecked (const BailOutCheckerType& bailOutChecker,
  12497. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  12498. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  12499. {
  12500. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  12501. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  12502. }
  12503. /** A dummy bail-out checker that always returns false.
  12504. See the ListenerList notes for more info about bail-out checkers.
  12505. */
  12506. class DummyBailOutChecker
  12507. {
  12508. public:
  12509. inline bool shouldBailOut() const throw() { return false; }
  12510. };
  12511. /** Iterates the listeners in a ListenerList. */
  12512. template <class BailOutCheckerType, class ListType>
  12513. class Iterator
  12514. {
  12515. public:
  12516. Iterator (const ListType& list_)
  12517. : list (list_), index (list_.size())
  12518. {}
  12519. ~Iterator() {}
  12520. bool next()
  12521. {
  12522. if (index <= 0)
  12523. return false;
  12524. const int listSize = list.size();
  12525. if (--index < listSize)
  12526. return true;
  12527. index = listSize - 1;
  12528. return index >= 0;
  12529. }
  12530. bool next (const BailOutCheckerType& bailOutChecker)
  12531. {
  12532. return (! bailOutChecker.shouldBailOut()) && next();
  12533. }
  12534. typename ListType::ListenerType* getListener() const throw()
  12535. {
  12536. return list.getListeners().getUnchecked (index);
  12537. }
  12538. private:
  12539. const ListType& list;
  12540. int index;
  12541. JUCE_DECLARE_NON_COPYABLE (Iterator);
  12542. };
  12543. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  12544. typedef ListenerClass ListenerType;
  12545. const ArrayType& getListeners() const throw() { return listeners; }
  12546. private:
  12547. ArrayType listeners;
  12548. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  12549. #undef LL_TEMPLATE
  12550. #undef LL_PARAM
  12551. };
  12552. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  12553. /*** End of inlined file: juce_ListenerList.h ***/
  12554. /**
  12555. Represents a shared variant value.
  12556. A Value object contains a reference to a var object, and can get and set its value.
  12557. Listeners can be attached to be told when the value is changed.
  12558. The Value class is a wrapper around a shared, reference-counted underlying data
  12559. object - this means that multiple Value objects can all refer to the same piece of
  12560. data, allowing all of them to be notified when any of them changes it.
  12561. When you create a Value with its default constructor, it acts as a wrapper around a
  12562. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  12563. you can map the Value onto any kind of underlying data.
  12564. */
  12565. class JUCE_API Value
  12566. {
  12567. public:
  12568. /** Creates an empty Value, containing a void var. */
  12569. Value();
  12570. /** Creates a Value that refers to the same value as another one.
  12571. Note that this doesn't make a copy of the other value - both this and the other
  12572. Value will share the same underlying value, so that when either one alters it, both
  12573. will see it change.
  12574. */
  12575. Value (const Value& other);
  12576. /** Creates a Value that is set to the specified value. */
  12577. explicit Value (const var& initialValue);
  12578. /** Destructor. */
  12579. ~Value();
  12580. /** Returns the current value. */
  12581. const var getValue() const;
  12582. /** Returns the current value. */
  12583. operator const var() const;
  12584. /** Returns the value as a string.
  12585. This is alternative to writing things like "myValue.getValue().toString()".
  12586. */
  12587. const String toString() const;
  12588. /** Sets the current value.
  12589. You can also use operator= to set the value.
  12590. If there are any listeners registered, they will be notified of the
  12591. change asynchronously.
  12592. */
  12593. void setValue (const var& newValue);
  12594. /** Sets the current value.
  12595. This is the same as calling setValue().
  12596. If there are any listeners registered, they will be notified of the
  12597. change asynchronously.
  12598. */
  12599. Value& operator= (const var& newValue);
  12600. /** Makes this object refer to the same underlying ValueSource as another one.
  12601. Once this object has been connected to another one, changing either one
  12602. will update the other.
  12603. Existing listeners will still be registered after you call this method, and
  12604. they'll continue to receive messages when the new value changes.
  12605. */
  12606. void referTo (const Value& valueToReferTo);
  12607. /** Returns true if this value and the other one are references to the same value.
  12608. */
  12609. bool refersToSameSourceAs (const Value& other) const;
  12610. /** Compares two values.
  12611. This is a compare-by-value comparison, so is effectively the same as
  12612. saying (this->getValue() == other.getValue()).
  12613. */
  12614. bool operator== (const Value& other) const;
  12615. /** Compares two values.
  12616. This is a compare-by-value comparison, so is effectively the same as
  12617. saying (this->getValue() != other.getValue()).
  12618. */
  12619. bool operator!= (const Value& other) const;
  12620. /** Receives callbacks when a Value object changes.
  12621. @see Value::addListener
  12622. */
  12623. class JUCE_API Listener
  12624. {
  12625. public:
  12626. Listener() {}
  12627. virtual ~Listener() {}
  12628. /** Called when a Value object is changed.
  12629. Note that the Value object passed as a parameter may not be exactly the same
  12630. object that you registered the listener with - it might be a copy that refers
  12631. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  12632. */
  12633. virtual void valueChanged (Value& value) = 0;
  12634. };
  12635. /** Adds a listener to receive callbacks when the value changes.
  12636. The listener is added to this specific Value object, and not to the shared
  12637. object that it refers to. When this object is deleted, all the listeners will
  12638. be lost, even if other references to the same Value still exist. So when you're
  12639. adding a listener, make sure that you add it to a ValueTree instance that will last
  12640. for as long as you need the listener. In general, you'd never want to add a listener
  12641. to a local stack-based ValueTree, but more likely to one that's a member variable.
  12642. @see removeListener
  12643. */
  12644. void addListener (Listener* listener);
  12645. /** Removes a listener that was previously added with addListener(). */
  12646. void removeListener (Listener* listener);
  12647. /**
  12648. Used internally by the Value class as the base class for its shared value objects.
  12649. The Value class is essentially a reference-counted pointer to a shared instance
  12650. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  12651. ValueSource classes to allow Value objects to represent your own custom data items.
  12652. */
  12653. class JUCE_API ValueSource : public ReferenceCountedObject,
  12654. public AsyncUpdater
  12655. {
  12656. public:
  12657. ValueSource();
  12658. virtual ~ValueSource();
  12659. /** Returns the current value of this object. */
  12660. virtual const var getValue() const = 0;
  12661. /** Changes the current value.
  12662. This must also trigger a change message if the value actually changes.
  12663. */
  12664. virtual void setValue (const var& newValue) = 0;
  12665. /** Delivers a change message to all the listeners that are registered with
  12666. this value.
  12667. If dispatchSynchronously is true, the method will call all the listeners
  12668. before returning; otherwise it'll dispatch a message and make the call later.
  12669. */
  12670. void sendChangeMessage (bool dispatchSynchronously);
  12671. protected:
  12672. friend class Value;
  12673. SortedSet <Value*> valuesWithListeners;
  12674. void handleAsyncUpdate();
  12675. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  12676. };
  12677. /** Creates a Value object that uses this valueSource object as its underlying data. */
  12678. explicit Value (ValueSource* valueSource);
  12679. /** Returns the ValueSource that this value is referring to. */
  12680. ValueSource& getValueSource() throw() { return *value; }
  12681. private:
  12682. friend class ValueSource;
  12683. ReferenceCountedObjectPtr <ValueSource> value;
  12684. ListenerList <Listener> listeners;
  12685. void callListeners();
  12686. // This is disallowed to avoid confusion about whether it should
  12687. // do a by-value or by-reference copy.
  12688. Value& operator= (const Value& other);
  12689. };
  12690. /** Writes a Value to an OutputStream as a UTF8 string. */
  12691. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  12692. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  12693. typedef Value::Listener ValueListener;
  12694. #endif // __JUCE_VALUE_JUCEHEADER__
  12695. /*** End of inlined file: juce_Value.h ***/
  12696. #endif
  12697. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12698. /*** Start of inlined file: juce_ValueTree.h ***/
  12699. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12700. #define __JUCE_VALUETREE_JUCEHEADER__
  12701. /*** Start of inlined file: juce_UndoManager.h ***/
  12702. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  12703. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  12704. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  12705. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12706. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12707. /*** Start of inlined file: juce_ChangeListener.h ***/
  12708. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  12709. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  12710. class ChangeBroadcaster;
  12711. /**
  12712. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  12713. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  12714. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  12715. ChangeListener is used to receive these callbacks.
  12716. Note that the major difference between an ActionListener and a ChangeListener
  12717. is that for a ChangeListener, multiple changes will be coalesced into fewer
  12718. callbacks, but ActionListeners perform one callback for every event posted.
  12719. @see ChangeBroadcaster, ActionListener
  12720. */
  12721. class JUCE_API ChangeListener
  12722. {
  12723. public:
  12724. /** Destructor. */
  12725. virtual ~ChangeListener() {}
  12726. /** Your subclass should implement this method to receive the callback.
  12727. @param source the ChangeBroadcaster that triggered the callback.
  12728. */
  12729. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  12730. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  12731. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  12732. private: virtual int changeListenerCallback (void*) { return 0; }
  12733. #endif
  12734. };
  12735. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  12736. /*** End of inlined file: juce_ChangeListener.h ***/
  12737. /**
  12738. Holds a list of ChangeListeners, and sends messages to them when instructed.
  12739. @see ChangeListener
  12740. */
  12741. class JUCE_API ChangeBroadcaster
  12742. {
  12743. public:
  12744. /** Creates an ChangeBroadcaster. */
  12745. ChangeBroadcaster() throw();
  12746. /** Destructor. */
  12747. virtual ~ChangeBroadcaster();
  12748. /** Registers a listener to receive change callbacks from this broadcaster.
  12749. Trying to add a listener that's already on the list will have no effect.
  12750. */
  12751. void addChangeListener (ChangeListener* listener);
  12752. /** Unregisters a listener from the list.
  12753. If the listener isn't on the list, this won't have any effect.
  12754. */
  12755. void removeChangeListener (ChangeListener* listener);
  12756. /** Removes all listeners from the list. */
  12757. void removeAllChangeListeners();
  12758. /** Causes an asynchronous change message to be sent to all the registered listeners.
  12759. The message will be delivered asynchronously by the main message thread, so this
  12760. method will return immediately. To call the listeners synchronously use
  12761. sendSynchronousChangeMessage().
  12762. */
  12763. void sendChangeMessage();
  12764. /** Sends a synchronous change message to all the registered listeners.
  12765. This will immediately call all the listeners that are registered. For thread-safety
  12766. reasons, you must only call this method on the main message thread.
  12767. @see dispatchPendingMessages
  12768. */
  12769. void sendSynchronousChangeMessage();
  12770. /** If a change message has been sent but not yet dispatched, this will call
  12771. sendSynchronousChangeMessage() to make the callback immediately.
  12772. For thread-safety reasons, you must only call this method on the main message thread.
  12773. */
  12774. void dispatchPendingMessages();
  12775. private:
  12776. class ChangeBroadcasterCallback : public AsyncUpdater
  12777. {
  12778. public:
  12779. ChangeBroadcasterCallback();
  12780. void handleAsyncUpdate();
  12781. ChangeBroadcaster* owner;
  12782. };
  12783. friend class ChangeBroadcasterCallback;
  12784. ChangeBroadcasterCallback callback;
  12785. ListenerList <ChangeListener> changeListeners;
  12786. void callListeners();
  12787. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  12788. };
  12789. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12790. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  12791. /*** Start of inlined file: juce_UndoableAction.h ***/
  12792. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  12793. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  12794. /**
  12795. Used by the UndoManager class to store an action which can be done
  12796. and undone.
  12797. @see UndoManager
  12798. */
  12799. class JUCE_API UndoableAction
  12800. {
  12801. protected:
  12802. /** Creates an action. */
  12803. UndoableAction() throw() {}
  12804. public:
  12805. /** Destructor. */
  12806. virtual ~UndoableAction() {}
  12807. /** Overridden by a subclass to perform the action.
  12808. This method is called by the UndoManager, and shouldn't be used directly by
  12809. applications.
  12810. Be careful not to make any calls in a perform() method that could call
  12811. recursively back into the UndoManager::perform() method
  12812. @returns true if the action could be performed.
  12813. @see UndoManager::perform
  12814. */
  12815. virtual bool perform() = 0;
  12816. /** Overridden by a subclass to undo the action.
  12817. This method is called by the UndoManager, and shouldn't be used directly by
  12818. applications.
  12819. Be careful not to make any calls in an undo() method that could call
  12820. recursively back into the UndoManager::perform() method
  12821. @returns true if the action could be undone without any errors.
  12822. @see UndoManager::perform
  12823. */
  12824. virtual bool undo() = 0;
  12825. /** Returns a value to indicate how much memory this object takes up.
  12826. Because the UndoManager keeps a list of UndoableActions, this is used
  12827. to work out how much space each one will take up, so that the UndoManager
  12828. can work out how many to keep.
  12829. The default value returned here is 10 - units are arbitrary and
  12830. don't have to be accurate.
  12831. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  12832. UndoManager::setMaxNumberOfStoredUnits
  12833. */
  12834. virtual int getSizeInUnits() { return 10; }
  12835. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  12836. If possible, this method should create and return a single action that does the same job as
  12837. this one followed by the supplied action.
  12838. If it's not possible to merge the two actions, the method should return zero.
  12839. */
  12840. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  12841. };
  12842. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  12843. /*** End of inlined file: juce_UndoableAction.h ***/
  12844. /**
  12845. Manages a list of undo/redo commands.
  12846. An UndoManager object keeps a list of past actions and can use these actions
  12847. to move backwards and forwards through an undo history.
  12848. To use it, create subclasses of UndoableAction which perform all the
  12849. actions you need, then when you need to actually perform an action, create one
  12850. and pass it to the UndoManager's perform() method.
  12851. The manager also uses the concept of 'transactions' to group the actions
  12852. together - all actions performed between calls to beginNewTransaction() are
  12853. grouped together and are all undone/redone as a group.
  12854. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  12855. when actions are performed or undone.
  12856. @see UndoableAction
  12857. */
  12858. class JUCE_API UndoManager : public ChangeBroadcaster
  12859. {
  12860. public:
  12861. /** Creates an UndoManager.
  12862. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12863. to indicate how much storage it takes up
  12864. (UndoableAction::getSizeInUnits()), so this
  12865. lets you specify the maximum total number of
  12866. units that the undomanager is allowed to
  12867. keep in memory before letting the older actions
  12868. drop off the end of the list.
  12869. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12870. that will be kept, even if this involves exceeding
  12871. the amount of space specified in maxNumberOfUnitsToKeep
  12872. */
  12873. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  12874. int minimumTransactionsToKeep = 30);
  12875. /** Destructor. */
  12876. ~UndoManager();
  12877. /** Deletes all stored actions in the list. */
  12878. void clearUndoHistory();
  12879. /** Returns the current amount of space to use for storing UndoableAction objects.
  12880. @see setMaxNumberOfStoredUnits
  12881. */
  12882. int getNumberOfUnitsTakenUpByStoredCommands() const;
  12883. /** Sets the amount of space that can be used for storing UndoableAction objects.
  12884. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12885. to indicate how much storage it takes up
  12886. (UndoableAction::getSizeInUnits()), so this
  12887. lets you specify the maximum total number of
  12888. units that the undomanager is allowed to
  12889. keep in memory before letting the older actions
  12890. drop off the end of the list.
  12891. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12892. that will be kept, even if this involves exceeding
  12893. the amount of space specified in maxNumberOfUnitsToKeep
  12894. @see getNumberOfUnitsTakenUpByStoredCommands
  12895. */
  12896. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  12897. int minimumTransactionsToKeep);
  12898. /** Performs an action and adds it to the undo history list.
  12899. @param action the action to perform - this will be deleted by the UndoManager
  12900. when no longer needed
  12901. @param actionName if this string is non-empty, the current transaction will be
  12902. given this name; if it's empty, the current transaction name will
  12903. be left unchanged. See setCurrentTransactionName()
  12904. @returns true if the command succeeds - see UndoableAction::perform
  12905. @see beginNewTransaction
  12906. */
  12907. bool perform (UndoableAction* action,
  12908. const String& actionName = String::empty);
  12909. /** Starts a new group of actions that together will be treated as a single transaction.
  12910. All actions that are passed to the perform() method between calls to this
  12911. method are grouped together and undone/redone together by a single call to
  12912. undo() or redo().
  12913. @param actionName a description of the transaction that is about to be
  12914. performed
  12915. */
  12916. void beginNewTransaction (const String& actionName = String::empty);
  12917. /** Changes the name stored for the current transaction.
  12918. Each transaction is given a name when the beginNewTransaction() method is
  12919. called, but this can be used to change that name without starting a new
  12920. transaction.
  12921. */
  12922. void setCurrentTransactionName (const String& newName);
  12923. /** Returns true if there's at least one action in the list to undo.
  12924. @see getUndoDescription, undo, canRedo
  12925. */
  12926. bool canUndo() const;
  12927. /** Returns the description of the transaction that would be next to get undone.
  12928. The description returned is the one that was passed into beginNewTransaction
  12929. before the set of actions was performed.
  12930. @see undo
  12931. */
  12932. const String getUndoDescription() const;
  12933. /** Tries to roll-back the last transaction.
  12934. @returns true if the transaction can be undone, and false if it fails, or
  12935. if there aren't any transactions to undo
  12936. */
  12937. bool undo();
  12938. /** Tries to roll-back any actions that were added to the current transaction.
  12939. This will perform an undo() only if there are some actions in the undo list
  12940. that were added after the last call to beginNewTransaction().
  12941. This is useful because it lets you call beginNewTransaction(), then
  12942. perform an operation which may or may not actually perform some actions, and
  12943. then call this method to get rid of any actions that might have been done
  12944. without it rolling back the previous transaction if nothing was actually
  12945. done.
  12946. @returns true if any actions were undone.
  12947. */
  12948. bool undoCurrentTransactionOnly();
  12949. /** Returns a list of the UndoableAction objects that have been performed during the
  12950. transaction that is currently open.
  12951. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  12952. were to be called now.
  12953. The first item in the list is the earliest action performed.
  12954. */
  12955. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  12956. /** Returns the number of UndoableAction objects that have been performed during the
  12957. transaction that is currently open.
  12958. @see getActionsInCurrentTransaction
  12959. */
  12960. int getNumActionsInCurrentTransaction() const;
  12961. /** Returns true if there's at least one action in the list to redo.
  12962. @see getRedoDescription, redo, canUndo
  12963. */
  12964. bool canRedo() const;
  12965. /** Returns the description of the transaction that would be next to get redone.
  12966. The description returned is the one that was passed into beginNewTransaction
  12967. before the set of actions was performed.
  12968. @see redo
  12969. */
  12970. const String getRedoDescription() const;
  12971. /** Tries to redo the last transaction that was undone.
  12972. @returns true if the transaction can be redone, and false if it fails, or
  12973. if there aren't any transactions to redo
  12974. */
  12975. bool redo();
  12976. private:
  12977. OwnedArray <OwnedArray <UndoableAction> > transactions;
  12978. StringArray transactionNames;
  12979. String currentTransactionName;
  12980. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  12981. bool newTransaction, reentrancyCheck;
  12982. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  12983. };
  12984. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  12985. /*** End of inlined file: juce_UndoManager.h ***/
  12986. /**
  12987. A powerful tree structure that can be used to hold free-form data, and which can
  12988. handle its own undo and redo behaviour.
  12989. A ValueTree contains a list of named properties as var objects, and also holds
  12990. any number of sub-trees.
  12991. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  12992. they're simply a lightweight reference to a shared data container. Creating a copy
  12993. of another ValueTree simply creates a new reference to the same underlying object - to
  12994. make a separate, deep copy of a tree you should explicitly call createCopy().
  12995. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  12996. and much of the structure of a ValueTree is similar to an XmlElement tree.
  12997. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  12998. contain text elements, the conversion works well and makes a good serialisation
  12999. format. They can also be serialised to a binary format, which is very fast and compact.
  13000. All the methods that change data take an optional UndoManager, which will be used
  13001. to track any changes to the object. For this to work, you have to be careful to
  13002. consistently always use the same UndoManager for all operations to any node inside
  13003. the tree.
  13004. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  13005. one tree to another, be careful to always remove it first, before adding it. This
  13006. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  13007. assertions if you try to do anything dangerous, but there are still plenty of ways it
  13008. could go wrong.
  13009. Listeners can be added to a ValueTree to be told when properies change and when
  13010. nodes are added or removed.
  13011. @see var, XmlElement
  13012. */
  13013. class JUCE_API ValueTree
  13014. {
  13015. public:
  13016. /** Creates an empty, invalid ValueTree.
  13017. A ValueTree that is created with this constructor can't actually be used for anything,
  13018. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  13019. To create a real one, use the constructor that takes a string.
  13020. @see ValueTree::invalid
  13021. */
  13022. ValueTree() throw();
  13023. /** Creates an empty ValueTree with the given type name.
  13024. Like an XmlElement, each ValueTree node has a type, which you can access with
  13025. getType() and hasType().
  13026. */
  13027. explicit ValueTree (const Identifier& type);
  13028. /** Creates a reference to another ValueTree. */
  13029. ValueTree (const ValueTree& other);
  13030. /** Makes this object reference another node. */
  13031. ValueTree& operator= (const ValueTree& other);
  13032. /** Destructor. */
  13033. ~ValueTree();
  13034. /** Returns true if both this and the other tree node refer to the same underlying structure.
  13035. Note that this isn't a value comparison - two independently-created trees which
  13036. contain identical data are not considered equal.
  13037. */
  13038. bool operator== (const ValueTree& other) const throw();
  13039. /** Returns true if this and the other node refer to different underlying structures.
  13040. Note that this isn't a value comparison - two independently-created trees which
  13041. contain identical data are not considered equal.
  13042. */
  13043. bool operator!= (const ValueTree& other) const throw();
  13044. /** Performs a deep comparison between the properties and children of two trees.
  13045. If all the properties and children of the two trees are the same (recursively), this
  13046. returns true.
  13047. The normal operator==() only checks whether two trees refer to the same shared data
  13048. structure, so use this method if you need to do a proper value comparison.
  13049. */
  13050. bool isEquivalentTo (const ValueTree& other) const;
  13051. /** Returns true if this node refers to some valid data.
  13052. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  13053. call to getChild().
  13054. */
  13055. bool isValid() const { return object != 0; }
  13056. /** Returns a deep copy of this tree and all its sub-nodes. */
  13057. ValueTree createCopy() const;
  13058. /** Returns the type of this node.
  13059. The type is specified when the ValueTree is created.
  13060. @see hasType
  13061. */
  13062. const Identifier getType() const;
  13063. /** Returns true if the node has this type.
  13064. The comparison is case-sensitive.
  13065. */
  13066. bool hasType (const Identifier& typeName) const;
  13067. /** Returns the value of a named property.
  13068. If no such property has been set, this will return a void variant.
  13069. You can also use operator[] to get a property.
  13070. @see var, setProperty, hasProperty
  13071. */
  13072. const var& getProperty (const Identifier& name) const;
  13073. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  13074. If no such property has been set, this will return the value of defaultReturnValue.
  13075. You can also use operator[] and getProperty to get a property.
  13076. @see var, getProperty, setProperty, hasProperty
  13077. */
  13078. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13079. /** Returns the value of a named property.
  13080. If no such property has been set, this will return a void variant. This is the same as
  13081. calling getProperty().
  13082. @see getProperty
  13083. */
  13084. const var& operator[] (const Identifier& name) const;
  13085. /** Changes a named property of the node.
  13086. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13087. so that this change can be undone.
  13088. @see var, getProperty, removeProperty
  13089. */
  13090. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  13091. /** Returns true if the node contains a named property. */
  13092. bool hasProperty (const Identifier& name) const;
  13093. /** Removes a property from the node.
  13094. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13095. so that this change can be undone.
  13096. */
  13097. void removeProperty (const Identifier& name, UndoManager* undoManager);
  13098. /** Removes all properties from the node.
  13099. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13100. so that this change can be undone.
  13101. */
  13102. void removeAllProperties (UndoManager* undoManager);
  13103. /** Returns the total number of properties that the node contains.
  13104. @see getProperty.
  13105. */
  13106. int getNumProperties() const;
  13107. /** Returns the identifier of the property with a given index.
  13108. @see getNumProperties
  13109. */
  13110. const Identifier getPropertyName (int index) const;
  13111. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  13112. The Value object will maintain a reference to this tree, and will use the undo manager when
  13113. it needs to change the value. Attaching a Value::Listener to the value object will provide
  13114. callbacks whenever the property changes.
  13115. */
  13116. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  13117. /** Returns the number of child nodes belonging to this one.
  13118. @see getChild
  13119. */
  13120. int getNumChildren() const;
  13121. /** Returns one of this node's child nodes.
  13122. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  13123. whether a node is valid).
  13124. */
  13125. ValueTree getChild (int index) const;
  13126. /** Returns the first child node with the speficied type name.
  13127. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13128. whether a node is valid).
  13129. @see getOrCreateChildWithName
  13130. */
  13131. ValueTree getChildWithName (const Identifier& type) const;
  13132. /** Returns the first child node with the speficied type name, creating and adding
  13133. a child with this name if there wasn't already one there.
  13134. The only time this will return an invalid object is when the object that you're calling
  13135. the method on is itself invalid.
  13136. @see getChildWithName
  13137. */
  13138. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13139. /** Looks for the first child node that has the speficied property value.
  13140. This will scan the child nodes in order, until it finds one that has property that matches
  13141. the specified value.
  13142. If no such node is found, it'll return an invalid node. (See isValid() to find out
  13143. whether a node is valid).
  13144. */
  13145. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13146. /** Adds a child to this node.
  13147. Make sure that the child is removed from any former parent node before calling this, or
  13148. you'll hit an assertion.
  13149. If the index is < 0 or greater than the current number of child nodes, the new node will
  13150. be added at the end of the list.
  13151. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13152. so that this change can be undone.
  13153. */
  13154. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  13155. /** Removes the specified child from this node's child-list.
  13156. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13157. so that this change can be undone.
  13158. */
  13159. void removeChild (const ValueTree& child, UndoManager* undoManager);
  13160. /** Removes a child from this node's child-list.
  13161. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13162. so that this change can be undone.
  13163. */
  13164. void removeChild (int childIndex, UndoManager* undoManager);
  13165. /** Removes all child-nodes from this node.
  13166. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  13167. so that this change can be undone.
  13168. */
  13169. void removeAllChildren (UndoManager* undoManager);
  13170. /** Moves one of the children to a different index.
  13171. This will move the child to a specified index, shuffling along any intervening
  13172. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  13173. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  13174. @param currentIndex the index of the item to be moved. If this isn't a
  13175. valid index, then nothing will be done
  13176. @param newIndex the index at which you'd like this item to end up. If this
  13177. is less than zero, the value will be moved to the end
  13178. of the list
  13179. @param undoManager the optional UndoManager to use to store this transaction
  13180. */
  13181. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  13182. /** Returns true if this node is anywhere below the specified parent node.
  13183. This returns true if the node is a child-of-a-child, as well as a direct child.
  13184. */
  13185. bool isAChildOf (const ValueTree& possibleParent) const;
  13186. /** Returns the index of a child item in this parent.
  13187. If the child isn't found, this returns -1.
  13188. */
  13189. int indexOf (const ValueTree& child) const;
  13190. /** Returns the parent node that contains this one.
  13191. If the node has no parent, this will return an invalid node. (See isValid() to find out
  13192. whether a node is valid).
  13193. */
  13194. ValueTree getParent() const;
  13195. /** Returns one of this node's siblings in its parent's child list.
  13196. The delta specifies how far to move through the list, so a value of 1 would return the node
  13197. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  13198. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  13199. */
  13200. ValueTree getSibling (int delta) const;
  13201. /** Creates an XmlElement that holds a complete image of this node and all its children.
  13202. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  13203. be used to recreate a similar node by calling fromXml()
  13204. @see fromXml
  13205. */
  13206. XmlElement* createXml() const;
  13207. /** Tries to recreate a node from its XML representation.
  13208. This isn't designed to cope with random XML data - for a sensible result, it should only
  13209. be fed XML that was created by the createXml() method.
  13210. */
  13211. static ValueTree fromXml (const XmlElement& xml);
  13212. /** Stores this tree (and all its children) in a binary format.
  13213. Once written, the data can be read back with readFromStream().
  13214. It's much faster to load/save your tree in binary form than as XML, but
  13215. obviously isn't human-readable.
  13216. */
  13217. void writeToStream (OutputStream& output);
  13218. /** Reloads a tree from a stream that was written with writeToStream(). */
  13219. static ValueTree readFromStream (InputStream& input);
  13220. /** Reloads a tree from a data block that was written with writeToStream(). */
  13221. static ValueTree readFromData (const void* data, size_t numBytes);
  13222. /** Listener class for events that happen to a ValueTree.
  13223. To get events from a ValueTree, make your class implement this interface, and use
  13224. ValueTree::addListener() and ValueTree::removeListener() to register it.
  13225. */
  13226. class JUCE_API Listener
  13227. {
  13228. public:
  13229. /** Destructor. */
  13230. virtual ~Listener() {}
  13231. /** This method is called when a property of this node (or of one of its sub-nodes) has
  13232. changed.
  13233. The tree parameter indicates which tree has had its property changed, and the property
  13234. parameter indicates the property.
  13235. Note that when you register a listener to a tree, it will receive this callback for
  13236. property changes in that tree, and also for any of its children, (recursively, at any depth).
  13237. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13238. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  13239. */
  13240. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  13241. const Identifier& property) = 0;
  13242. /** This method is called when a child sub-tree is added.
  13243. Note that when you register a listener to a tree, it will receive this callback for
  13244. child changes in both that tree and any of its children, (recursively, at any depth).
  13245. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13246. just check the parentTree parameter to make sure it's the one that you're interested in.
  13247. */
  13248. virtual void valueTreeChildAdded (ValueTree& parentTree,
  13249. ValueTree& childWhichHasBeenAdded) = 0;
  13250. /** This method is called when a child sub-tree is removed.
  13251. Note that when you register a listener to a tree, it will receive this callback for
  13252. child changes in both that tree and any of its children, (recursively, at any depth).
  13253. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13254. just check the parentTree parameter to make sure it's the one that you're interested in.
  13255. */
  13256. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  13257. ValueTree& childWhichHasBeenRemoved) = 0;
  13258. /** This method is called when a tree's children have been re-shuffled.
  13259. Note that when you register a listener to a tree, it will receive this callback for
  13260. child changes in both that tree and any of its children, (recursively, at any depth).
  13261. If your tree has sub-trees but you only want to know about changes to the top level tree,
  13262. just check the parameter to make sure it's the tree that you're interested in.
  13263. */
  13264. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  13265. /** This method is called when a tree has been added or removed from a parent node.
  13266. This callback happens when the tree to which the listener was registered is added or
  13267. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  13268. the listener is registered, and not to any of its children.
  13269. */
  13270. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  13271. };
  13272. /** Adds a listener to receive callbacks when this node is changed.
  13273. The listener is added to this specific ValueTree object, and not to the shared
  13274. object that it refers to. When this object is deleted, all the listeners will
  13275. be lost, even if other references to the same ValueTree still exist. And if you
  13276. use the operator= to make this refer to a different ValueTree, any listeners will
  13277. begin listening to changes to the new tree instead of the old one.
  13278. When you're adding a listener, make sure that you add it to a ValueTree instance that
  13279. will last for as long as you need the listener. In general, you'd never want to add a
  13280. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  13281. @see removeListener
  13282. */
  13283. void addListener (Listener* listener);
  13284. /** Removes a listener that was previously added with addListener(). */
  13285. void removeListener (Listener* listener);
  13286. /** This method uses a comparator object to sort the tree's children into order.
  13287. The object provided must have a method of the form:
  13288. @code
  13289. int compareElements (const ValueTree& first, const ValueTree& second);
  13290. @endcode
  13291. ..and this method must return:
  13292. - a value of < 0 if the first comes before the second
  13293. - a value of 0 if the two objects are equivalent
  13294. - a value of > 0 if the second comes before the first
  13295. To improve performance, the compareElements() method can be declared as static or const.
  13296. @param comparator the comparator to use for comparing elements.
  13297. @param undoManager optional UndoManager for storing the changes
  13298. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  13299. equivalent will be kept in the order in which they currently appear in the array.
  13300. This is slower to perform, but may be important in some cases. If it's false, a
  13301. faster algorithm is used, but equivalent elements may be rearranged.
  13302. */
  13303. template <typename ElementComparator>
  13304. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  13305. {
  13306. if (object != 0)
  13307. {
  13308. ReferenceCountedArray <SharedObject> sortedList (object->children);
  13309. ComparatorAdapter <ElementComparator> adapter (comparator);
  13310. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  13311. object->reorderChildren (sortedList, undoManager);
  13312. }
  13313. }
  13314. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  13315. This invalid object is equivalent to ValueTree created with its default constructor.
  13316. */
  13317. static const ValueTree invalid;
  13318. private:
  13319. class SetPropertyAction;
  13320. friend class SetPropertyAction;
  13321. class AddOrRemoveChildAction;
  13322. friend class AddOrRemoveChildAction;
  13323. class MoveChildAction;
  13324. friend class MoveChildAction;
  13325. class JUCE_API SharedObject : public ReferenceCountedObject
  13326. {
  13327. public:
  13328. explicit SharedObject (const Identifier& type);
  13329. SharedObject (const SharedObject& other);
  13330. ~SharedObject();
  13331. const Identifier type;
  13332. NamedValueSet properties;
  13333. ReferenceCountedArray <SharedObject> children;
  13334. SortedSet <ValueTree*> valueTreesWithListeners;
  13335. SharedObject* parent;
  13336. void sendPropertyChangeMessage (const Identifier& property);
  13337. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  13338. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  13339. void sendChildAddedMessage (ValueTree child);
  13340. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  13341. void sendChildRemovedMessage (ValueTree child);
  13342. void sendChildOrderChangedMessage (ValueTree& parent);
  13343. void sendChildOrderChangedMessage();
  13344. void sendParentChangeMessage();
  13345. const var& getProperty (const Identifier& name) const;
  13346. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  13347. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  13348. bool hasProperty (const Identifier& name) const;
  13349. void removeProperty (const Identifier& name, UndoManager*);
  13350. void removeAllProperties (UndoManager*);
  13351. bool isAChildOf (const SharedObject* possibleParent) const;
  13352. int indexOf (const ValueTree& child) const;
  13353. ValueTree getChildWithName (const Identifier& type) const;
  13354. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  13355. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  13356. void addChild (SharedObject* child, int index, UndoManager*);
  13357. void removeChild (int childIndex, UndoManager*);
  13358. void removeAllChildren (UndoManager*);
  13359. void moveChild (int currentIndex, int newIndex, UndoManager*);
  13360. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  13361. bool isEquivalentTo (const SharedObject& other) const;
  13362. XmlElement* createXml() const;
  13363. private:
  13364. SharedObject& operator= (const SharedObject&);
  13365. JUCE_LEAK_DETECTOR (SharedObject);
  13366. };
  13367. template <typename ElementComparator>
  13368. class ComparatorAdapter
  13369. {
  13370. public:
  13371. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  13372. int compareElements (SharedObject* const first, SharedObject* const second)
  13373. {
  13374. return comparator.compareElements (ValueTree (first), ValueTree (second));
  13375. }
  13376. private:
  13377. ElementComparator& comparator;
  13378. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  13379. };
  13380. friend class SharedObject;
  13381. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  13382. SharedObjectPtr object;
  13383. ListenerList <Listener> listeners;
  13384. #if JUCE_MSVC && ! DOXYGEN
  13385. public: // (workaround for VC6)
  13386. #endif
  13387. explicit ValueTree (SharedObject*);
  13388. };
  13389. #endif // __JUCE_VALUETREE_JUCEHEADER__
  13390. /*** End of inlined file: juce_ValueTree.h ***/
  13391. #endif
  13392. #ifndef __JUCE_VARIANT_JUCEHEADER__
  13393. #endif
  13394. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13395. /*** Start of inlined file: juce_FileLogger.h ***/
  13396. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  13397. #define __JUCE_FILELOGGER_JUCEHEADER__
  13398. /**
  13399. A simple implemenation of a Logger that writes to a file.
  13400. @see Logger
  13401. */
  13402. class JUCE_API FileLogger : public Logger
  13403. {
  13404. public:
  13405. /** Creates a FileLogger for a given file.
  13406. @param fileToWriteTo the file that to use - new messages will be appended
  13407. to the file. If the file doesn't exist, it will be created,
  13408. along with any parent directories that are needed.
  13409. @param welcomeMessage when opened, the logger will write a header to the log, along
  13410. with the current date and time, and this welcome message
  13411. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  13412. but is larger than this number of bytes, then the start of the
  13413. file will be truncated to keep the size down. This prevents a log
  13414. file getting ridiculously large over time. The file will be truncated
  13415. at a new-line boundary. If this value is less than zero, no size limit
  13416. will be imposed; if it's zero, the file will always be deleted. Note that
  13417. the size is only checked once when this object is created - any logging
  13418. that is done later will be appended without any checking
  13419. */
  13420. FileLogger (const File& fileToWriteTo,
  13421. const String& welcomeMessage,
  13422. const int maxInitialFileSizeBytes = 128 * 1024);
  13423. /** Destructor. */
  13424. ~FileLogger();
  13425. void logMessage (const String& message);
  13426. const File getLogFile() const { return logFile; }
  13427. /** Helper function to create a log file in the correct place for this platform.
  13428. On Windows this will return a logger with a path such as:
  13429. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  13430. On the Mac it'll create something like:
  13431. ~/Library/Logs/[logFileName]
  13432. The method might return 0 if the file can't be created for some reason.
  13433. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  13434. it's best to use the something like the name of your application here.
  13435. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  13436. call it "log.txt" because if it goes in a directory with logs
  13437. from other applications (as it will do on the Mac) then no-one
  13438. will know which one is yours!
  13439. @param welcomeMessage a message that will be written to the log when it's opened.
  13440. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  13441. */
  13442. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  13443. const String& logFileName,
  13444. const String& welcomeMessage,
  13445. const int maxInitialFileSizeBytes = 128 * 1024);
  13446. private:
  13447. File logFile;
  13448. CriticalSection logLock;
  13449. void trimFileSize (int maxFileSizeBytes) const;
  13450. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  13451. };
  13452. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  13453. /*** End of inlined file: juce_FileLogger.h ***/
  13454. #endif
  13455. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13456. /*** Start of inlined file: juce_Initialisation.h ***/
  13457. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  13458. #define __JUCE_INITIALISATION_JUCEHEADER__
  13459. /** Initialises Juce's GUI classes.
  13460. If you're embedding Juce into an application that uses its own event-loop rather
  13461. than using the START_JUCE_APPLICATION macro, call this function before making any
  13462. Juce calls, to make sure things are initialised correctly.
  13463. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13464. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  13465. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  13466. */
  13467. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  13468. /** Clears up any static data being used by Juce's GUI classes.
  13469. If you're embedding Juce into an application that uses its own event-loop rather
  13470. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  13471. code to clean up any juce objects that might be lying around.
  13472. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  13473. */
  13474. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  13475. /** Initialises the core parts of Juce.
  13476. If you're embedding Juce into either a command-line program, call this function
  13477. at the start of your main() function to make sure that Juce is initialised correctly.
  13478. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  13479. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  13480. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  13481. */
  13482. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI();
  13483. /** Clears up any static data being used by Juce's non-gui core classes.
  13484. If you're embedding Juce into either a command-line program, call this function
  13485. at the end of your main() function if you want to make sure any Juce objects are
  13486. cleaned up correctly.
  13487. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  13488. */
  13489. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI();
  13490. /** A utility object that helps you initialise and shutdown Juce correctly
  13491. using an RAII pattern.
  13492. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  13493. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  13494. make sure that these functions are matched correctly.
  13495. This class is particularly handy to use at the beginning of a console app's
  13496. main() function, because it'll take care of shutting down whenever you return
  13497. from the main() call.
  13498. @see ScopedJuceInitialiser_GUI
  13499. */
  13500. class ScopedJuceInitialiser_NonGUI
  13501. {
  13502. public:
  13503. /** The constructor simply calls initialiseJuce_NonGUI(). */
  13504. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  13505. /** The destructor simply calls shutdownJuce_NonGUI(). */
  13506. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  13507. };
  13508. /** A utility object that helps you initialise and shutdown Juce correctly
  13509. using an RAII pattern.
  13510. When an instance of this class is created, it calls initialiseJuce_GUI(),
  13511. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  13512. make sure that these functions are matched correctly.
  13513. This class is particularly handy to use at the beginning of a console app's
  13514. main() function, because it'll take care of shutting down whenever you return
  13515. from the main() call.
  13516. @see ScopedJuceInitialiser_NonGUI
  13517. */
  13518. class ScopedJuceInitialiser_GUI
  13519. {
  13520. public:
  13521. /** The constructor simply calls initialiseJuce_GUI(). */
  13522. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  13523. /** The destructor simply calls shutdownJuce_GUI(). */
  13524. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  13525. };
  13526. /*
  13527. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  13528. AppSubClass is the name of a class derived from JUCEApplication.
  13529. See the JUCEApplication class documentation (juce_Application.h) for more details.
  13530. */
  13531. #if JUCE_ANDROID
  13532. #define START_JUCE_APPLICATION(AppClass) \
  13533. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  13534. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  13535. #define START_JUCE_APPLICATION(AppClass) \
  13536. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13537. int main (int argc, char* argv[]) \
  13538. { \
  13539. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13540. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  13541. }
  13542. #elif JUCE_WINDOWS
  13543. #ifdef _CONSOLE
  13544. #define START_JUCE_APPLICATION(AppClass) \
  13545. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13546. int main (int, char* argv[]) \
  13547. { \
  13548. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13549. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13550. }
  13551. #elif ! defined (_AFXDLL)
  13552. #ifdef _WINDOWS_
  13553. #define START_JUCE_APPLICATION(AppClass) \
  13554. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13555. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  13556. { \
  13557. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13558. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13559. }
  13560. #else
  13561. #define START_JUCE_APPLICATION(AppClass) \
  13562. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13563. int __stdcall WinMain (int, int, const char*, int) \
  13564. { \
  13565. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13566. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13567. }
  13568. #endif
  13569. #endif
  13570. #endif
  13571. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  13572. /*** End of inlined file: juce_Initialisation.h ***/
  13573. #endif
  13574. #ifndef __JUCE_LOGGER_JUCEHEADER__
  13575. #endif
  13576. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13577. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  13578. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13579. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13580. /** A timer for measuring performance of code and dumping the results to a file.
  13581. e.g. @code
  13582. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  13583. for (;;)
  13584. {
  13585. pc.start();
  13586. doSomethingFishy();
  13587. pc.stop();
  13588. }
  13589. @endcode
  13590. In this example, the time of each period between calling start/stop will be
  13591. measured and averaged over 50 runs, and the results printed to a file
  13592. every 50 times round the loop.
  13593. */
  13594. class JUCE_API PerformanceCounter
  13595. {
  13596. public:
  13597. /** Creates a PerformanceCounter object.
  13598. @param counterName the name used when printing out the statistics
  13599. @param runsPerPrintout the number of start/stop iterations before calling
  13600. printStatistics()
  13601. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  13602. the results are just written to the debugger output
  13603. */
  13604. PerformanceCounter (const String& counterName,
  13605. int runsPerPrintout = 100,
  13606. const File& loggingFile = File::nonexistent);
  13607. /** Destructor. */
  13608. ~PerformanceCounter();
  13609. /** Starts timing.
  13610. @see stop
  13611. */
  13612. void start();
  13613. /** Stops timing and prints out the results.
  13614. The number of iterations before doing a printout of the
  13615. results is set in the constructor.
  13616. @see start
  13617. */
  13618. void stop();
  13619. /** Dumps the current metrics to the debugger output and to a file.
  13620. As well as using Logger::outputDebugString to print the results,
  13621. this will write then to the file specified in the constructor (if
  13622. this was valid).
  13623. */
  13624. void printStatistics();
  13625. private:
  13626. String name;
  13627. int numRuns, runsPerPrint;
  13628. double totalTime;
  13629. int64 started;
  13630. File outputFile;
  13631. };
  13632. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13633. /*** End of inlined file: juce_PerformanceCounter.h ***/
  13634. #endif
  13635. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  13636. #endif
  13637. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13638. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  13639. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13640. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13641. /**
  13642. A collection of miscellaneous platform-specific utilities.
  13643. */
  13644. class JUCE_API PlatformUtilities
  13645. {
  13646. public:
  13647. /** Plays the operating system's default alert 'beep' sound. */
  13648. static void beep();
  13649. /** Tries to launch the system's default reader for a given file or URL. */
  13650. static bool openDocument (const String& documentURL, const String& parameters);
  13651. /** Tries to launch the system's default email app to let the user create an email.
  13652. */
  13653. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  13654. const String& emailSubject,
  13655. const String& bodyText,
  13656. const StringArray& filesToAttach);
  13657. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13658. /** MAC ONLY - Turns a Core CF String into a juce one. */
  13659. static const String cfStringToJuceString (CFStringRef cfString);
  13660. /** MAC ONLY - Turns a juce string into a Core CF one. */
  13661. static CFStringRef juceStringToCFString (const String& s);
  13662. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  13663. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  13664. /** MAC ONLY - Turns an FSRef into a juce string path. */
  13665. static const String makePathFromFSRef (FSRef* file);
  13666. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  13667. their precomposed equivalents.
  13668. */
  13669. static const String convertToPrecomposedUnicode (const String& s);
  13670. /** MAC ONLY - Gets the type of a file from the file's resources. */
  13671. static OSType getTypeOfFile (const String& filename);
  13672. /** MAC ONLY - Returns true if this file is actually a bundle. */
  13673. static bool isBundle (const String& filename);
  13674. /** MAC ONLY - Adds an item to the dock */
  13675. static void addItemToDock (const File& file);
  13676. /** MAC ONLY - Returns the current OS version number.
  13677. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  13678. */
  13679. static int getOSXMinorVersionNumber();
  13680. #endif
  13681. #if JUCE_WINDOWS || DOXYGEN
  13682. // Some registry helper functions:
  13683. /** WIN32 ONLY - Returns a string from the registry.
  13684. The path is a string for the entire path of a value in the registry,
  13685. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  13686. */
  13687. static const String getRegistryValue (const String& regValuePath,
  13688. const String& defaultValue = String::empty);
  13689. /** WIN32 ONLY - Sets a registry value as a string.
  13690. This will take care of creating any groups needed to get to the given
  13691. registry value.
  13692. */
  13693. static void setRegistryValue (const String& regValuePath,
  13694. const String& value);
  13695. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  13696. static bool registryValueExists (const String& regValuePath);
  13697. /** WIN32 ONLY - Deletes a registry value. */
  13698. static void deleteRegistryValue (const String& regValuePath);
  13699. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  13700. static void deleteRegistryKey (const String& regKeyPath);
  13701. /** WIN32 ONLY - Creates a file association in the registry.
  13702. This lets you set the exe that should be launched by a given file extension.
  13703. @param fileExtension the file extension to associate, including the
  13704. initial dot, e.g. ".txt"
  13705. @param symbolicDescription a space-free short token to identify the file type
  13706. @param fullDescription a human-readable description of the file type
  13707. @param targetExecutable the executable that should be launched
  13708. @param iconResourceNumber the icon that gets displayed for the file type will be
  13709. found by looking up this resource number in the
  13710. executable. Pass 0 here to not use an icon
  13711. */
  13712. static void registerFileAssociation (const String& fileExtension,
  13713. const String& symbolicDescription,
  13714. const String& fullDescription,
  13715. const File& targetExecutable,
  13716. int iconResourceNumber);
  13717. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  13718. In a normal Juce application this will be set to the module handle
  13719. of the application executable.
  13720. If you're writing a DLL using Juce and plan to use any Juce messaging or
  13721. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  13722. to set the correct module handle in your DllMain() function, because
  13723. the win32 system relies on the correct instance handle when opening windows.
  13724. */
  13725. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  13726. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  13727. @see getCurrentModuleInstanceHandle()
  13728. */
  13729. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  13730. /** WIN32 ONLY - Gets the command-line params as a string.
  13731. This is needed to avoid unicode problems with the argc type params.
  13732. */
  13733. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  13734. #endif
  13735. /** Clears the floating point unit's flags.
  13736. Only has an effect under win32, currently.
  13737. */
  13738. static void fpuReset();
  13739. #if JUCE_LINUX || JUCE_WINDOWS
  13740. /** Loads a dynamically-linked library into the process's address space.
  13741. @param pathOrFilename the platform-dependent name and search path
  13742. @returns a handle which can be used by getProcedureEntryPoint(), or
  13743. zero if it fails.
  13744. @see freeDynamicLibrary, getProcedureEntryPoint
  13745. */
  13746. static void* loadDynamicLibrary (const String& pathOrFilename);
  13747. /** Frees a dynamically-linked library.
  13748. @param libraryHandle a handle created by loadDynamicLibrary
  13749. @see loadDynamicLibrary, getProcedureEntryPoint
  13750. */
  13751. static void freeDynamicLibrary (void* libraryHandle);
  13752. /** Finds a procedure call in a dynamically-linked library.
  13753. @param libraryHandle a library handle returned by loadDynamicLibrary
  13754. @param procedureName the name of the procedure call to try to load
  13755. @returns a pointer to the function if found, or 0 if it fails
  13756. @see loadDynamicLibrary
  13757. */
  13758. static void* getProcedureEntryPoint (void* libraryHandle,
  13759. const String& procedureName);
  13760. #endif
  13761. private:
  13762. PlatformUtilities();
  13763. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  13764. };
  13765. #if JUCE_MAC || JUCE_IOS
  13766. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII.
  13767. */
  13768. class JUCE_API ScopedAutoReleasePool
  13769. {
  13770. public:
  13771. ScopedAutoReleasePool();
  13772. ~ScopedAutoReleasePool();
  13773. private:
  13774. void* pool;
  13775. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  13776. };
  13777. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool pool;
  13778. #else
  13779. #define JUCE_AUTORELEASEPOOL
  13780. #endif
  13781. #if JUCE_LINUX
  13782. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  13783. using an RAII approach.
  13784. */
  13785. class ScopedXLock
  13786. {
  13787. public:
  13788. /** Creating a ScopedXLock object locks the X display.
  13789. This uses XLockDisplay() to grab the display that Juce is using.
  13790. */
  13791. ScopedXLock();
  13792. /** Deleting a ScopedXLock object unlocks the X display.
  13793. This calls XUnlockDisplay() to release the lock.
  13794. */
  13795. ~ScopedXLock();
  13796. };
  13797. #endif
  13798. #if JUCE_MAC
  13799. /**
  13800. A wrapper class for picking up events from an Apple IR remote control device.
  13801. To use it, just create a subclass of this class, implementing the buttonPressed()
  13802. callback, then call start() and stop() to start or stop receiving events.
  13803. */
  13804. class JUCE_API AppleRemoteDevice
  13805. {
  13806. public:
  13807. AppleRemoteDevice();
  13808. virtual ~AppleRemoteDevice();
  13809. /** The set of buttons that may be pressed.
  13810. @see buttonPressed
  13811. */
  13812. enum ButtonType
  13813. {
  13814. menuButton = 0, /**< The menu button (if it's held for a short time). */
  13815. playButton, /**< The play button. */
  13816. plusButton, /**< The plus or volume-up button. */
  13817. minusButton, /**< The minus or volume-down button. */
  13818. rightButton, /**< The right button (if it's held for a short time). */
  13819. leftButton, /**< The left button (if it's held for a short time). */
  13820. rightButton_Long, /**< The right button (if it's held for a long time). */
  13821. leftButton_Long, /**< The menu button (if it's held for a long time). */
  13822. menuButton_Long, /**< The menu button (if it's held for a long time). */
  13823. playButtonSleepMode,
  13824. switched
  13825. };
  13826. /** Override this method to receive the callback about a button press.
  13827. The callback will happen on the application's message thread.
  13828. Some buttons trigger matching up and down events, in which the isDown parameter
  13829. will be true and then false. Others only send a single event when the
  13830. button is pressed.
  13831. */
  13832. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  13833. /** Starts the device running and responding to events.
  13834. Returns true if it managed to open the device.
  13835. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  13836. and will not be available to any other part of the system. If
  13837. false, it will be shared with other apps.
  13838. @see stop
  13839. */
  13840. bool start (bool inExclusiveMode);
  13841. /** Stops the device running.
  13842. @see start
  13843. */
  13844. void stop();
  13845. /** Returns true if the device has been started successfully.
  13846. */
  13847. bool isActive() const;
  13848. /** Returns the ID number of the remote, if it has sent one.
  13849. */
  13850. int getRemoteId() const { return remoteId; }
  13851. /** @internal */
  13852. void handleCallbackInternal();
  13853. private:
  13854. void* device;
  13855. void* queue;
  13856. int remoteId;
  13857. bool open (bool openInExclusiveMode);
  13858. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  13859. };
  13860. #endif
  13861. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13862. /*** End of inlined file: juce_PlatformUtilities.h ***/
  13863. #endif
  13864. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  13865. #endif
  13866. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13867. /*** Start of inlined file: juce_Singleton.h ***/
  13868. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13869. #define __JUCE_SINGLETON_JUCEHEADER__
  13870. /**
  13871. Macro to declare member variables and methods for a singleton class.
  13872. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  13873. to the class's definition.
  13874. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  13875. implementation code.
  13876. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  13877. destructor, in case it is deleted by other means than deleteInstance()
  13878. Clients can then call the static method MyClass::getInstance() to get a pointer
  13879. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  13880. no instance currently exists.
  13881. e.g. @code
  13882. class MySingleton
  13883. {
  13884. public:
  13885. MySingleton()
  13886. {
  13887. }
  13888. ~MySingleton()
  13889. {
  13890. // this ensures that no dangling pointers are left when the
  13891. // singleton is deleted.
  13892. clearSingletonInstance();
  13893. }
  13894. juce_DeclareSingleton (MySingleton, false)
  13895. };
  13896. juce_ImplementSingleton (MySingleton)
  13897. // example of usage:
  13898. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  13899. ...
  13900. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  13901. @endcode
  13902. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13903. than once during the process's lifetime - i.e. after you've created and deleted the
  13904. object, getInstance() will refuse to create another one. This can be useful to stop
  13905. objects being accidentally re-created during your app's shutdown code.
  13906. If you know that your object will only be created and deleted by a single thread, you
  13907. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  13908. of this one.
  13909. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  13910. */
  13911. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  13912. \
  13913. static classname* _singletonInstance; \
  13914. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  13915. \
  13916. static classname* JUCE_CALLTYPE getInstance() \
  13917. { \
  13918. if (_singletonInstance == 0) \
  13919. {\
  13920. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13921. \
  13922. if (_singletonInstance == 0) \
  13923. { \
  13924. static bool alreadyInside = false; \
  13925. static bool createdOnceAlready = false; \
  13926. \
  13927. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  13928. jassert (! problem); \
  13929. if (! problem) \
  13930. { \
  13931. createdOnceAlready = true; \
  13932. alreadyInside = true; \
  13933. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  13934. alreadyInside = false; \
  13935. \
  13936. _singletonInstance = newObject; \
  13937. } \
  13938. } \
  13939. } \
  13940. \
  13941. return _singletonInstance; \
  13942. } \
  13943. \
  13944. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() throw() \
  13945. { \
  13946. return _singletonInstance; \
  13947. } \
  13948. \
  13949. static void JUCE_CALLTYPE deleteInstance() \
  13950. { \
  13951. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13952. if (_singletonInstance != 0) \
  13953. { \
  13954. classname* const old = _singletonInstance; \
  13955. _singletonInstance = 0; \
  13956. delete old; \
  13957. } \
  13958. } \
  13959. \
  13960. void clearSingletonInstance() throw() \
  13961. { \
  13962. if (_singletonInstance == this) \
  13963. _singletonInstance = 0; \
  13964. }
  13965. /** This is a counterpart to the juce_DeclareSingleton macro.
  13966. After adding the juce_DeclareSingleton to the class definition, this macro has
  13967. to be used in the cpp file.
  13968. */
  13969. #define juce_ImplementSingleton(classname) \
  13970. \
  13971. classname* classname::_singletonInstance = 0; \
  13972. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  13973. /**
  13974. Macro to declare member variables and methods for a singleton class.
  13975. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  13976. section to make access to it thread-safe. If you know that your object will
  13977. only ever be created or deleted by a single thread, then this is a
  13978. more efficient version to use.
  13979. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13980. than once during the process's lifetime - i.e. after you've created and deleted the
  13981. object, getInstance() will refuse to create another one. This can be useful to stop
  13982. objects being accidentally re-created during your app's shutdown code.
  13983. See the documentation for juce_DeclareSingleton for more information about
  13984. how to use it, the only difference being that you have to use
  13985. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  13986. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  13987. */
  13988. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  13989. \
  13990. static classname* _singletonInstance; \
  13991. \
  13992. static classname* getInstance() \
  13993. { \
  13994. if (_singletonInstance == 0) \
  13995. { \
  13996. static bool alreadyInside = false; \
  13997. static bool createdOnceAlready = false; \
  13998. \
  13999. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  14000. jassert (! problem); \
  14001. if (! problem) \
  14002. { \
  14003. createdOnceAlready = true; \
  14004. alreadyInside = true; \
  14005. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  14006. alreadyInside = false; \
  14007. \
  14008. _singletonInstance = newObject; \
  14009. } \
  14010. } \
  14011. \
  14012. return _singletonInstance; \
  14013. } \
  14014. \
  14015. static inline classname* getInstanceWithoutCreating() throw() \
  14016. { \
  14017. return _singletonInstance; \
  14018. } \
  14019. \
  14020. static void deleteInstance() \
  14021. { \
  14022. if (_singletonInstance != 0) \
  14023. { \
  14024. classname* const old = _singletonInstance; \
  14025. _singletonInstance = 0; \
  14026. delete old; \
  14027. } \
  14028. } \
  14029. \
  14030. void clearSingletonInstance() throw() \
  14031. { \
  14032. if (_singletonInstance == this) \
  14033. _singletonInstance = 0; \
  14034. }
  14035. /**
  14036. Macro to declare member variables and methods for a singleton class.
  14037. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  14038. for recursion or repeated instantiation. It's intended for use as a lightweight
  14039. version of a singleton, where you're using it in very straightforward
  14040. circumstances and don't need the extra checking.
  14041. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  14042. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  14043. See the documentation for juce_DeclareSingleton for more information about
  14044. how to use it, the only difference being that you have to use
  14045. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  14046. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  14047. */
  14048. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  14049. \
  14050. static classname* _singletonInstance; \
  14051. \
  14052. static classname* getInstance() \
  14053. { \
  14054. if (_singletonInstance == 0) \
  14055. _singletonInstance = new classname(); \
  14056. \
  14057. return _singletonInstance; \
  14058. } \
  14059. \
  14060. static inline classname* getInstanceWithoutCreating() throw() \
  14061. { \
  14062. return _singletonInstance; \
  14063. } \
  14064. \
  14065. static void deleteInstance() \
  14066. { \
  14067. if (_singletonInstance != 0) \
  14068. { \
  14069. classname* const old = _singletonInstance; \
  14070. _singletonInstance = 0; \
  14071. delete old; \
  14072. } \
  14073. } \
  14074. \
  14075. void clearSingletonInstance() throw() \
  14076. { \
  14077. if (_singletonInstance == this) \
  14078. _singletonInstance = 0; \
  14079. }
  14080. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  14081. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  14082. to the class definition, this macro has to be used somewhere in the cpp file.
  14083. */
  14084. #define juce_ImplementSingleton_SingleThreaded(classname) \
  14085. \
  14086. classname* classname::_singletonInstance = 0;
  14087. #endif // __JUCE_SINGLETON_JUCEHEADER__
  14088. /*** End of inlined file: juce_Singleton.h ***/
  14089. #endif
  14090. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  14091. #endif
  14092. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14093. /*** Start of inlined file: juce_SystemStats.h ***/
  14094. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  14095. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  14096. /**
  14097. Contains methods for finding out about the current hardware and OS configuration.
  14098. */
  14099. class JUCE_API SystemStats
  14100. {
  14101. public:
  14102. /** Returns the current version of JUCE,
  14103. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  14104. */
  14105. static const String getJUCEVersion();
  14106. /** The set of possible results of the getOperatingSystemType() method.
  14107. */
  14108. enum OperatingSystemType
  14109. {
  14110. UnknownOS = 0,
  14111. MacOSX = 0x1000,
  14112. Linux = 0x2000,
  14113. Android = 0x3000,
  14114. Win95 = 0x4001,
  14115. Win98 = 0x4002,
  14116. WinNT351 = 0x4103,
  14117. WinNT40 = 0x4104,
  14118. Win2000 = 0x4105,
  14119. WinXP = 0x4106,
  14120. WinVista = 0x4107,
  14121. Windows7 = 0x4108,
  14122. Windows = 0x4000, /**< To test whether any version of Windows is running,
  14123. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  14124. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  14125. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  14126. };
  14127. /** Returns the type of operating system we're running on.
  14128. @returns one of the values from the OperatingSystemType enum.
  14129. @see getOperatingSystemName
  14130. */
  14131. static OperatingSystemType getOperatingSystemType();
  14132. /** Returns the name of the type of operating system we're running on.
  14133. @returns a string describing the OS type.
  14134. @see getOperatingSystemType
  14135. */
  14136. static const String getOperatingSystemName();
  14137. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  14138. */
  14139. static bool isOperatingSystem64Bit();
  14140. /** Returns the current user's name, if available.
  14141. @see getFullUserName()
  14142. */
  14143. static const String getLogonName();
  14144. /** Returns the current user's full name, if available.
  14145. On some OSes, this may just return the same value as getLogonName().
  14146. @see getLogonName()
  14147. */
  14148. static const String getFullUserName();
  14149. // CPU and memory information..
  14150. /** Returns the approximate CPU speed.
  14151. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  14152. what year you're reading this...)
  14153. */
  14154. static int getCpuSpeedInMegaherz();
  14155. /** Returns a string to indicate the CPU vendor.
  14156. Might not be known on some systems.
  14157. */
  14158. static const String getCpuVendor();
  14159. /** Checks whether Intel MMX instructions are available. */
  14160. static bool hasMMX() throw() { return cpuFlags.hasMMX; }
  14161. /** Checks whether Intel SSE instructions are available. */
  14162. static bool hasSSE() throw() { return cpuFlags.hasSSE; }
  14163. /** Checks whether Intel SSE2 instructions are available. */
  14164. static bool hasSSE2() throw() { return cpuFlags.hasSSE2; }
  14165. /** Checks whether AMD 3DNOW instructions are available. */
  14166. static bool has3DNow() throw() { return cpuFlags.has3DNow; }
  14167. /** Returns the number of CPUs. */
  14168. static int getNumCpus() throw() { return cpuFlags.numCpus; }
  14169. /** Finds out how much RAM is in the machine.
  14170. @returns the approximate number of megabytes of memory, or zero if
  14171. something goes wrong when finding out.
  14172. */
  14173. static int getMemorySizeInMegabytes();
  14174. /** Returns the system page-size.
  14175. This is only used by programmers with beards.
  14176. */
  14177. static int getPageSize();
  14178. // not-for-public-use platform-specific method gets called at startup to initialise things.
  14179. static void initialiseStats();
  14180. private:
  14181. struct CPUFlags
  14182. {
  14183. int numCpus;
  14184. bool hasMMX : 1;
  14185. bool hasSSE : 1;
  14186. bool hasSSE2 : 1;
  14187. bool has3DNow : 1;
  14188. };
  14189. static CPUFlags cpuFlags;
  14190. SystemStats();
  14191. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  14192. };
  14193. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  14194. /*** End of inlined file: juce_SystemStats.h ***/
  14195. #endif
  14196. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  14197. #endif
  14198. #ifndef __JUCE_TIME_JUCEHEADER__
  14199. #endif
  14200. #ifndef __JUCE_UUID_JUCEHEADER__
  14201. /*** Start of inlined file: juce_Uuid.h ***/
  14202. #ifndef __JUCE_UUID_JUCEHEADER__
  14203. #define __JUCE_UUID_JUCEHEADER__
  14204. /**
  14205. A universally unique 128-bit identifier.
  14206. This class generates very random unique numbers based on the system time
  14207. and MAC addresses if any are available. It's extremely unlikely that two identical
  14208. UUIDs would ever be created by chance.
  14209. The class includes methods for saving the ID as a string or as raw binary data.
  14210. */
  14211. class JUCE_API Uuid
  14212. {
  14213. public:
  14214. /** Creates a new unique ID. */
  14215. Uuid();
  14216. /** Destructor. */
  14217. ~Uuid() throw();
  14218. /** Creates a copy of another UUID. */
  14219. Uuid (const Uuid& other);
  14220. /** Copies another UUID. */
  14221. Uuid& operator= (const Uuid& other);
  14222. /** Returns true if the ID is zero. */
  14223. bool isNull() const throw();
  14224. /** Compares two UUIDs. */
  14225. bool operator== (const Uuid& other) const;
  14226. /** Compares two UUIDs. */
  14227. bool operator!= (const Uuid& other) const;
  14228. /** Returns a stringified version of this UUID.
  14229. A Uuid object can later be reconstructed from this string using operator= or
  14230. the constructor that takes a string parameter.
  14231. @returns a 32 character hex string.
  14232. */
  14233. const String toString() const;
  14234. /** Creates an ID from an encoded string version.
  14235. @see toString
  14236. */
  14237. Uuid (const String& uuidString);
  14238. /** Copies from a stringified UUID.
  14239. The string passed in should be one that was created with the toString() method.
  14240. */
  14241. Uuid& operator= (const String& uuidString);
  14242. /** Returns a pointer to the internal binary representation of the ID.
  14243. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  14244. the constructor or operator= method that takes an array of uint8s.
  14245. */
  14246. const uint8* getRawData() const throw() { return value.asBytes; }
  14247. /** Creates a UUID from a 16-byte array.
  14248. @see getRawData
  14249. */
  14250. Uuid (const uint8* rawData);
  14251. /** Sets this UUID from 16-bytes of raw data. */
  14252. Uuid& operator= (const uint8* rawData);
  14253. private:
  14254. #ifndef DOXYGEN
  14255. union
  14256. {
  14257. uint8 asBytes [16];
  14258. int asInt[4];
  14259. int64 asInt64[2];
  14260. } value;
  14261. #endif
  14262. JUCE_LEAK_DETECTOR (Uuid);
  14263. };
  14264. #endif // __JUCE_UUID_JUCEHEADER__
  14265. /*** End of inlined file: juce_Uuid.h ***/
  14266. #endif
  14267. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14268. /*** Start of inlined file: juce_BlowFish.h ***/
  14269. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  14270. #define __JUCE_BLOWFISH_JUCEHEADER__
  14271. /**
  14272. BlowFish encryption class.
  14273. */
  14274. class JUCE_API BlowFish
  14275. {
  14276. public:
  14277. /** Creates an object that can encode/decode based on the specified key.
  14278. The key data can be up to 72 bytes long.
  14279. */
  14280. BlowFish (const void* keyData, int keyBytes);
  14281. /** Creates a copy of another blowfish object. */
  14282. BlowFish (const BlowFish& other);
  14283. /** Copies another blowfish object. */
  14284. BlowFish& operator= (const BlowFish& other);
  14285. /** Destructor. */
  14286. ~BlowFish();
  14287. /** Encrypts a pair of 32-bit integers. */
  14288. void encrypt (uint32& data1, uint32& data2) const throw();
  14289. /** Decrypts a pair of 32-bit integers. */
  14290. void decrypt (uint32& data1, uint32& data2) const throw();
  14291. private:
  14292. uint32 p[18];
  14293. HeapBlock <uint32> s[4];
  14294. uint32 F (uint32 x) const throw();
  14295. JUCE_LEAK_DETECTOR (BlowFish);
  14296. };
  14297. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  14298. /*** End of inlined file: juce_BlowFish.h ***/
  14299. #endif
  14300. #ifndef __JUCE_MD5_JUCEHEADER__
  14301. /*** Start of inlined file: juce_MD5.h ***/
  14302. #ifndef __JUCE_MD5_JUCEHEADER__
  14303. #define __JUCE_MD5_JUCEHEADER__
  14304. /**
  14305. MD5 checksum class.
  14306. Create one of these with a block of source data or a string, and it calculates the
  14307. MD5 checksum of that data.
  14308. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  14309. */
  14310. class JUCE_API MD5
  14311. {
  14312. public:
  14313. /** Creates a null MD5 object. */
  14314. MD5();
  14315. /** Creates a copy of another MD5. */
  14316. MD5 (const MD5& other);
  14317. /** Copies another MD5. */
  14318. MD5& operator= (const MD5& other);
  14319. /** Creates a checksum for a block of binary data. */
  14320. explicit MD5 (const MemoryBlock& data);
  14321. /** Creates a checksum for a block of binary data. */
  14322. MD5 (const void* data, size_t numBytes);
  14323. /** Creates a checksum for a string.
  14324. Note that this operates on the string as a block of unicode characters, so the
  14325. result you get will differ from the value you'd get if the string was treated
  14326. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  14327. of this method with a checksum created by a different framework, which may have
  14328. used a different encoding.
  14329. */
  14330. explicit MD5 (const String& text);
  14331. /** Creates a checksum for the input from a stream.
  14332. This will read up to the given number of bytes from the stream, and produce the
  14333. checksum of that. If the number of bytes to read is negative, it'll read
  14334. until the stream is exhausted.
  14335. */
  14336. MD5 (InputStream& input, int64 numBytesToRead = -1);
  14337. /** Creates a checksum for a file. */
  14338. explicit MD5 (const File& file);
  14339. /** Destructor. */
  14340. ~MD5();
  14341. /** Returns the checksum as a 16-byte block of data. */
  14342. const MemoryBlock getRawChecksumData() const;
  14343. /** Returns the checksum as a 32-digit hex string. */
  14344. const String toHexString() const;
  14345. /** Compares this to another MD5. */
  14346. bool operator== (const MD5& other) const;
  14347. /** Compares this to another MD5. */
  14348. bool operator!= (const MD5& other) const;
  14349. private:
  14350. uint8 result [16];
  14351. struct ProcessContext
  14352. {
  14353. uint8 buffer [64];
  14354. uint32 state [4];
  14355. uint32 count [2];
  14356. ProcessContext();
  14357. void processBlock (const void* data, size_t dataSize);
  14358. void transform (const void* buffer);
  14359. void finish (void* result);
  14360. };
  14361. void processStream (InputStream& input, int64 numBytesToRead);
  14362. JUCE_LEAK_DETECTOR (MD5);
  14363. };
  14364. #endif // __JUCE_MD5_JUCEHEADER__
  14365. /*** End of inlined file: juce_MD5.h ***/
  14366. #endif
  14367. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14368. /*** Start of inlined file: juce_Primes.h ***/
  14369. #ifndef __JUCE_PRIMES_JUCEHEADER__
  14370. #define __JUCE_PRIMES_JUCEHEADER__
  14371. /*** Start of inlined file: juce_BigInteger.h ***/
  14372. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  14373. #define __JUCE_BIGINTEGER_JUCEHEADER__
  14374. class MemoryBlock;
  14375. /**
  14376. An arbitrarily large integer class.
  14377. A BigInteger can be used in a similar way to a normal integer, but has no size
  14378. limit (except for memory and performance constraints).
  14379. Negative values are possible, but the value isn't stored as 2s-complement, so
  14380. be careful if you use negative values and look at the values of individual bits.
  14381. */
  14382. class JUCE_API BigInteger
  14383. {
  14384. public:
  14385. /** Creates an empty BigInteger */
  14386. BigInteger();
  14387. /** Creates a BigInteger containing an integer value in its low bits.
  14388. The low 32 bits of the number are initialised with this value.
  14389. */
  14390. BigInteger (uint32 value);
  14391. /** Creates a BigInteger containing an integer value in its low bits.
  14392. The low 32 bits of the number are initialised with the absolute value
  14393. passed in, and its sign is set to reflect the sign of the number.
  14394. */
  14395. BigInteger (int32 value);
  14396. /** Creates a BigInteger containing an integer value in its low bits.
  14397. The low 64 bits of the number are initialised with the absolute value
  14398. passed in, and its sign is set to reflect the sign of the number.
  14399. */
  14400. BigInteger (int64 value);
  14401. /** Creates a copy of another BigInteger. */
  14402. BigInteger (const BigInteger& other);
  14403. /** Destructor. */
  14404. ~BigInteger();
  14405. /** Copies another BigInteger onto this one. */
  14406. BigInteger& operator= (const BigInteger& other);
  14407. /** Swaps the internal contents of this with another object. */
  14408. void swapWith (BigInteger& other) throw();
  14409. /** Returns the value of a specified bit in the number.
  14410. If the index is out-of-range, the result will be false.
  14411. */
  14412. bool operator[] (int bit) const throw();
  14413. /** Returns true if no bits are set. */
  14414. bool isZero() const throw();
  14415. /** Returns true if the value is 1. */
  14416. bool isOne() const throw();
  14417. /** Attempts to get the lowest bits of the value as an integer.
  14418. If the value is bigger than the integer limits, this will return only the lower bits.
  14419. */
  14420. int toInteger() const throw();
  14421. /** Resets the value to 0. */
  14422. void clear();
  14423. /** Clears a particular bit in the number. */
  14424. void clearBit (int bitNumber) throw();
  14425. /** Sets a specified bit to 1. */
  14426. void setBit (int bitNumber);
  14427. /** Sets or clears a specified bit. */
  14428. void setBit (int bitNumber, bool shouldBeSet);
  14429. /** Sets a range of bits to be either on or off.
  14430. @param startBit the first bit to change
  14431. @param numBits the number of bits to change
  14432. @param shouldBeSet whether to turn these bits on or off
  14433. */
  14434. void setRange (int startBit, int numBits, bool shouldBeSet);
  14435. /** Inserts a bit an a given position, shifting up any bits above it. */
  14436. void insertBit (int bitNumber, bool shouldBeSet);
  14437. /** Returns a range of bits as a new BigInteger.
  14438. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  14439. @see getBitRangeAsInt
  14440. */
  14441. const BigInteger getBitRange (int startBit, int numBits) const;
  14442. /** Returns a range of bits as an integer value.
  14443. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  14444. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  14445. getBitRange().
  14446. */
  14447. int getBitRangeAsInt (int startBit, int numBits) const throw();
  14448. /** Sets a range of bits to an integer value.
  14449. Copies the given integer onto a range of bits, starting at startBit,
  14450. and using up to numBits of the available bits.
  14451. */
  14452. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  14453. /** Shifts a section of bits left or right.
  14454. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  14455. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  14456. */
  14457. void shiftBits (int howManyBitsLeft, int startBit);
  14458. /** Returns the total number of set bits in the value. */
  14459. int countNumberOfSetBits() const throw();
  14460. /** Looks for the index of the next set bit after a given starting point.
  14461. This searches from startIndex (inclusive) upwards for the first set bit,
  14462. and returns its index. If no set bits are found, it returns -1.
  14463. */
  14464. int findNextSetBit (int startIndex = 0) const throw();
  14465. /** Looks for the index of the next clear bit after a given starting point.
  14466. This searches from startIndex (inclusive) upwards for the first clear bit,
  14467. and returns its index.
  14468. */
  14469. int findNextClearBit (int startIndex = 0) const throw();
  14470. /** Returns the index of the highest set bit in the number.
  14471. If the value is zero, this will return -1.
  14472. */
  14473. int getHighestBit() const throw();
  14474. // All the standard arithmetic ops...
  14475. BigInteger& operator+= (const BigInteger& other);
  14476. BigInteger& operator-= (const BigInteger& other);
  14477. BigInteger& operator*= (const BigInteger& other);
  14478. BigInteger& operator/= (const BigInteger& other);
  14479. BigInteger& operator|= (const BigInteger& other);
  14480. BigInteger& operator&= (const BigInteger& other);
  14481. BigInteger& operator^= (const BigInteger& other);
  14482. BigInteger& operator%= (const BigInteger& other);
  14483. BigInteger& operator<<= (int numBitsToShift);
  14484. BigInteger& operator>>= (int numBitsToShift);
  14485. BigInteger& operator++();
  14486. BigInteger& operator--();
  14487. const BigInteger operator++ (int);
  14488. const BigInteger operator-- (int);
  14489. const BigInteger operator-() const;
  14490. const BigInteger operator+ (const BigInteger& other) const;
  14491. const BigInteger operator- (const BigInteger& other) const;
  14492. const BigInteger operator* (const BigInteger& other) const;
  14493. const BigInteger operator/ (const BigInteger& other) const;
  14494. const BigInteger operator| (const BigInteger& other) const;
  14495. const BigInteger operator& (const BigInteger& other) const;
  14496. const BigInteger operator^ (const BigInteger& other) const;
  14497. const BigInteger operator% (const BigInteger& other) const;
  14498. const BigInteger operator<< (int numBitsToShift) const;
  14499. const BigInteger operator>> (int numBitsToShift) const;
  14500. bool operator== (const BigInteger& other) const throw();
  14501. bool operator!= (const BigInteger& other) const throw();
  14502. bool operator< (const BigInteger& other) const throw();
  14503. bool operator<= (const BigInteger& other) const throw();
  14504. bool operator> (const BigInteger& other) const throw();
  14505. bool operator>= (const BigInteger& other) const throw();
  14506. /** Does a signed comparison of two BigIntegers.
  14507. Return values are:
  14508. - 0 if the numbers are the same
  14509. - < 0 if this number is smaller than the other
  14510. - > 0 if this number is bigger than the other
  14511. */
  14512. int compare (const BigInteger& other) const throw();
  14513. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  14514. Return values are:
  14515. - 0 if the numbers are the same
  14516. - < 0 if this number is smaller than the other
  14517. - > 0 if this number is bigger than the other
  14518. */
  14519. int compareAbsolute (const BigInteger& other) const throw();
  14520. /** Divides this value by another one and returns the remainder.
  14521. This number is divided by other, leaving the quotient in this number,
  14522. with the remainder being copied to the other BigInteger passed in.
  14523. */
  14524. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  14525. /** Returns the largest value that will divide both this value and the one passed-in.
  14526. */
  14527. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  14528. /** Performs a combined exponent and modulo operation.
  14529. This BigInteger's value becomes (this ^ exponent) % modulus.
  14530. */
  14531. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  14532. /** Performs an inverse modulo on the value.
  14533. i.e. the result is (this ^ -1) mod (modulus).
  14534. */
  14535. void inverseModulo (const BigInteger& modulus);
  14536. /** Returns true if the value is less than zero.
  14537. @see setNegative, negate
  14538. */
  14539. bool isNegative() const throw();
  14540. /** Changes the sign of the number to be positive or negative.
  14541. @see isNegative, negate
  14542. */
  14543. void setNegative (bool shouldBeNegative) throw();
  14544. /** Inverts the sign of the number.
  14545. @see isNegative, setNegative
  14546. */
  14547. void negate() throw();
  14548. /** Converts the number to a string.
  14549. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14550. If minimumNumCharacters is greater than 0, the returned string will be
  14551. padded with leading zeros to reach at least that length.
  14552. */
  14553. const String toString (int base, int minimumNumCharacters = 1) const;
  14554. /** Reads the numeric value from a string.
  14555. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14556. Any invalid characters will be ignored.
  14557. */
  14558. void parseString (const String& text, int base);
  14559. /** Turns the number into a block of binary data.
  14560. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14561. of the number, and so on.
  14562. @see loadFromMemoryBlock
  14563. */
  14564. const MemoryBlock toMemoryBlock() const;
  14565. /** Converts a block of raw data into a number.
  14566. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14567. of the number, and so on.
  14568. @see toMemoryBlock
  14569. */
  14570. void loadFromMemoryBlock (const MemoryBlock& data);
  14571. private:
  14572. HeapBlock <uint32> values;
  14573. int numValues, highestBit;
  14574. bool negative;
  14575. void ensureSize (int numVals);
  14576. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  14577. static inline int bitToIndex (const int bit) throw() { return bit >> 5; }
  14578. static inline uint32 bitToMask (const int bit) throw() { return 1 << (bit & 31); }
  14579. JUCE_LEAK_DETECTOR (BigInteger);
  14580. };
  14581. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  14582. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  14583. #ifndef DOXYGEN
  14584. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  14585. typedef BigInteger BitArray;
  14586. #endif
  14587. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  14588. /*** End of inlined file: juce_BigInteger.h ***/
  14589. /**
  14590. Prime number creation class.
  14591. This class contains static methods for generating and testing prime numbers.
  14592. @see BigInteger
  14593. */
  14594. class JUCE_API Primes
  14595. {
  14596. public:
  14597. /** Creates a random prime number with a given bit-length.
  14598. The certainty parameter specifies how many iterations to use when testing
  14599. for primality. A safe value might be anything over about 20-30.
  14600. The randomSeeds parameter lets you optionally pass it a set of values with
  14601. which to seed the random number generation, improving the security of the
  14602. keys generated.
  14603. */
  14604. static const BigInteger createProbablePrime (int bitLength,
  14605. int certainty,
  14606. const int* randomSeeds = 0,
  14607. int numRandomSeeds = 0);
  14608. /** Tests a number to see if it's prime.
  14609. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  14610. whether the number is prime.
  14611. The certainty parameter specifies how many iterations to use when testing - a
  14612. safe value might be anything over about 20-30.
  14613. */
  14614. static bool isProbablyPrime (const BigInteger& number, int certainty);
  14615. private:
  14616. Primes();
  14617. JUCE_DECLARE_NON_COPYABLE (Primes);
  14618. };
  14619. #endif // __JUCE_PRIMES_JUCEHEADER__
  14620. /*** End of inlined file: juce_Primes.h ***/
  14621. #endif
  14622. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14623. /*** Start of inlined file: juce_RSAKey.h ***/
  14624. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14625. #define __JUCE_RSAKEY_JUCEHEADER__
  14626. /**
  14627. RSA public/private key-pair encryption class.
  14628. An object of this type makes up one half of a public/private RSA key pair. Use the
  14629. createKeyPair() method to create a matching pair for encoding/decoding.
  14630. */
  14631. class JUCE_API RSAKey
  14632. {
  14633. public:
  14634. /** Creates a null key object.
  14635. Initialise a pair of objects for use with the createKeyPair() method.
  14636. */
  14637. RSAKey();
  14638. /** Loads a key from an encoded string representation.
  14639. This reloads a key from a string created by the toString() method.
  14640. */
  14641. explicit RSAKey (const String& stringRepresentation);
  14642. /** Destructor. */
  14643. ~RSAKey();
  14644. bool operator== (const RSAKey& other) const throw();
  14645. bool operator!= (const RSAKey& other) const throw();
  14646. /** Turns the key into a string representation.
  14647. This can be reloaded using the constructor that takes a string.
  14648. */
  14649. const String toString() const;
  14650. /** Encodes or decodes a value.
  14651. Call this on the public key object to encode some data, then use the matching
  14652. private key object to decode it.
  14653. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14654. initialised correctly.
  14655. NOTE: This method dumbly applies this key to this data. If you encode some data
  14656. and then try to decode it with a key that doesn't match, this method will still
  14657. happily do its job and return true, but the result won't be what you were expecting.
  14658. It's your responsibility to check that the result is what you wanted.
  14659. */
  14660. bool applyToValue (BigInteger& value) const;
  14661. /** Creates a public/private key-pair.
  14662. Each key will perform one-way encryption that can only be reversed by
  14663. using the other key.
  14664. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14665. sizes are more secure, but this method will take longer to execute.
  14666. The randomSeeds parameter lets you optionally pass it a set of values with
  14667. which to seed the random number generation, improving the security of the
  14668. keys generated. If you supply these, make sure you provide more than 2 values,
  14669. and the more your provide, the better the security.
  14670. */
  14671. static void createKeyPair (RSAKey& publicKey,
  14672. RSAKey& privateKey,
  14673. int numBits,
  14674. const int* randomSeeds = 0,
  14675. int numRandomSeeds = 0);
  14676. protected:
  14677. BigInteger part1, part2;
  14678. private:
  14679. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14680. JUCE_LEAK_DETECTOR (RSAKey);
  14681. };
  14682. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14683. /*** End of inlined file: juce_RSAKey.h ***/
  14684. #endif
  14685. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14686. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14687. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14688. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14689. /**
  14690. Searches through a the files in a directory, returning each file that is found.
  14691. A DirectoryIterator will search through a directory and its subdirectories using
  14692. a wildcard filepattern match.
  14693. If you may be finding a large number of files, this is better than
  14694. using File::findChildFiles() because it doesn't block while it finds them
  14695. all, and this is more memory-efficient.
  14696. It can also guess how far it's got using a wildly inaccurate algorithm.
  14697. */
  14698. class JUCE_API DirectoryIterator
  14699. {
  14700. public:
  14701. /** Creates a DirectoryIterator for a given directory.
  14702. After creating one of these, call its next() method to get the
  14703. first file - e.g. @code
  14704. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14705. while (iter.next())
  14706. {
  14707. File theFileItFound (iter.getFile());
  14708. ... etc
  14709. }
  14710. @endcode
  14711. @param directory the directory to search in
  14712. @param isRecursive whether all the subdirectories should also be searched
  14713. @param wildCard the file pattern to match
  14714. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14715. whether to look for files, directories, or both.
  14716. */
  14717. DirectoryIterator (const File& directory,
  14718. bool isRecursive,
  14719. const String& wildCard = "*",
  14720. int whatToLookFor = File::findFiles);
  14721. /** Destructor. */
  14722. ~DirectoryIterator();
  14723. /** Moves the iterator along to the next file.
  14724. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14725. false if there are no more matching files.
  14726. */
  14727. bool next();
  14728. /** Moves the iterator along to the next file, and returns various properties of that file.
  14729. If you need to find out details about the file, it's more efficient to call this method than
  14730. to call the normal next() method and then find out the details afterwards.
  14731. All the parameters are optional, so pass null pointers for any items that you're not
  14732. interested in.
  14733. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14734. false if there are no more matching files. If it returns false, then none of the
  14735. parameters will be filled-in.
  14736. */
  14737. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  14738. Time* modTime, Time* creationTime, bool* isReadOnly);
  14739. /** Returns the file that the iterator is currently pointing at.
  14740. The result of this call is only valid after a call to next() has returned true.
  14741. */
  14742. const File getFile() const;
  14743. /** Returns a guess of how far through the search the iterator has got.
  14744. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14745. very accurate.
  14746. */
  14747. float getEstimatedProgress() const;
  14748. private:
  14749. class NativeIterator
  14750. {
  14751. public:
  14752. NativeIterator (const File& directory, const String& wildCard);
  14753. ~NativeIterator();
  14754. bool next (String& filenameFound,
  14755. bool* isDirectory, bool* isHidden, int64* fileSize,
  14756. Time* modTime, Time* creationTime, bool* isReadOnly);
  14757. class Pimpl;
  14758. private:
  14759. friend class DirectoryIterator;
  14760. friend class ScopedPointer<Pimpl>;
  14761. ScopedPointer<Pimpl> pimpl;
  14762. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14763. };
  14764. friend class ScopedPointer<NativeIterator::Pimpl>;
  14765. NativeIterator fileFinder;
  14766. String wildCard, path;
  14767. int index;
  14768. mutable int totalNumFiles;
  14769. const int whatToLookFor;
  14770. const bool isRecursive;
  14771. bool hasBeenAdvanced;
  14772. ScopedPointer <DirectoryIterator> subIterator;
  14773. File currentFile;
  14774. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14775. };
  14776. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14777. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14778. #endif
  14779. #ifndef __JUCE_FILE_JUCEHEADER__
  14780. #endif
  14781. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14782. /*** Start of inlined file: juce_FileInputStream.h ***/
  14783. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14784. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14785. /**
  14786. An input stream that reads from a local file.
  14787. @see InputStream, FileOutputStream, File::createInputStream
  14788. */
  14789. class JUCE_API FileInputStream : public InputStream
  14790. {
  14791. public:
  14792. /** Creates a FileInputStream.
  14793. @param fileToRead the file to read from - if the file can't be accessed for some
  14794. reason, then the stream will just contain no data
  14795. */
  14796. explicit FileInputStream (const File& fileToRead);
  14797. /** Destructor. */
  14798. ~FileInputStream();
  14799. const File& getFile() const throw() { return file; }
  14800. int64 getTotalLength();
  14801. int read (void* destBuffer, int maxBytesToRead);
  14802. bool isExhausted();
  14803. int64 getPosition();
  14804. bool setPosition (int64 pos);
  14805. private:
  14806. File file;
  14807. void* fileHandle;
  14808. int64 currentPosition, totalSize;
  14809. bool needToSeek;
  14810. void openHandle();
  14811. void closeHandle();
  14812. size_t readInternal (void* buffer, size_t numBytes);
  14813. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  14814. };
  14815. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14816. /*** End of inlined file: juce_FileInputStream.h ***/
  14817. #endif
  14818. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14819. /*** Start of inlined file: juce_FileOutputStream.h ***/
  14820. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14821. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14822. /**
  14823. An output stream that writes into a local file.
  14824. @see OutputStream, FileInputStream, File::createOutputStream
  14825. */
  14826. class JUCE_API FileOutputStream : public OutputStream
  14827. {
  14828. public:
  14829. /** Creates a FileOutputStream.
  14830. If the file doesn't exist, it will first be created. If the file can't be
  14831. created or opened, the failedToOpen() method will return
  14832. true.
  14833. If the file already exists when opened, the stream's write-postion will
  14834. be set to the end of the file. To overwrite an existing file,
  14835. use File::deleteFile() before opening the stream, or use setPosition(0)
  14836. after it's opened (although this won't truncate the file).
  14837. It's better to use File::createOutputStream() to create one of these, rather
  14838. than using the class directly.
  14839. @see TemporaryFile
  14840. */
  14841. FileOutputStream (const File& fileToWriteTo,
  14842. int bufferSizeToUse = 16384);
  14843. /** Destructor. */
  14844. ~FileOutputStream();
  14845. /** Returns the file that this stream is writing to.
  14846. */
  14847. const File& getFile() const { return file; }
  14848. /** Returns true if the stream couldn't be opened for some reason.
  14849. */
  14850. bool failedToOpen() const { return fileHandle == 0; }
  14851. void flush();
  14852. int64 getPosition();
  14853. bool setPosition (int64 pos);
  14854. bool write (const void* data, int numBytes);
  14855. private:
  14856. File file;
  14857. void* fileHandle;
  14858. int64 currentPosition;
  14859. int bufferSize, bytesInBuffer;
  14860. HeapBlock <char> buffer;
  14861. void openHandle();
  14862. void closeHandle();
  14863. void flushInternal();
  14864. int64 setPositionInternal (int64 newPosition);
  14865. int writeInternal (const void* data, int numBytes);
  14866. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  14867. };
  14868. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14869. /*** End of inlined file: juce_FileOutputStream.h ***/
  14870. #endif
  14871. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14872. /*** Start of inlined file: juce_FileSearchPath.h ***/
  14873. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14874. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  14875. /**
  14876. Encapsulates a set of folders that make up a search path.
  14877. @see File
  14878. */
  14879. class JUCE_API FileSearchPath
  14880. {
  14881. public:
  14882. /** Creates an empty search path. */
  14883. FileSearchPath();
  14884. /** Creates a search path from a string of pathnames.
  14885. The path can be semicolon- or comma-separated, e.g.
  14886. "/foo/bar;/foo/moose;/fish/moose"
  14887. The separate folders are tokenised and added to the search path.
  14888. */
  14889. FileSearchPath (const String& path);
  14890. /** Creates a copy of another search path. */
  14891. FileSearchPath (const FileSearchPath& other);
  14892. /** Destructor. */
  14893. ~FileSearchPath();
  14894. /** Uses a string containing a list of pathnames to re-initialise this list.
  14895. This search path is cleared and the semicolon- or comma-separated folders
  14896. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  14897. */
  14898. FileSearchPath& operator= (const String& path);
  14899. /** Returns the number of folders in this search path.
  14900. @see operator[]
  14901. */
  14902. int getNumPaths() const;
  14903. /** Returns one of the folders in this search path.
  14904. The file returned isn't guaranteed to actually be a valid directory.
  14905. @see getNumPaths
  14906. */
  14907. const File operator[] (int index) const;
  14908. /** Returns the search path as a semicolon-separated list of directories. */
  14909. const String toString() const;
  14910. /** Adds a new directory to the search path.
  14911. The new directory is added to the end of the list if the insertIndex parameter is
  14912. less than zero, otherwise it is inserted at the given index.
  14913. */
  14914. void add (const File& directoryToAdd,
  14915. int insertIndex = -1);
  14916. /** Adds a new directory to the search path if it's not already in there. */
  14917. void addIfNotAlreadyThere (const File& directoryToAdd);
  14918. /** Removes a directory from the search path. */
  14919. void remove (int indexToRemove);
  14920. /** Merges another search path into this one.
  14921. This will remove any duplicate directories.
  14922. */
  14923. void addPath (const FileSearchPath& other);
  14924. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  14925. If the search is intended to be recursive, there's no point having nested folders in the search
  14926. path, because they'll just get searched twice and you'll get duplicate results.
  14927. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  14928. */
  14929. void removeRedundantPaths();
  14930. /** Removes any directories that don't actually exist. */
  14931. void removeNonExistentPaths();
  14932. /** Searches the path for a wildcard.
  14933. This will search all the directories in the search path in order, adding any
  14934. matching files to the results array.
  14935. @param results an array to append the results to
  14936. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  14937. return files, directories, or both.
  14938. @param searchRecursively whether to recursively search the subdirectories too
  14939. @param wildCardPattern a pattern to match against the filenames
  14940. @returns the number of files added to the array
  14941. @see File::findChildFiles
  14942. */
  14943. int findChildFiles (Array<File>& results,
  14944. int whatToLookFor,
  14945. bool searchRecursively,
  14946. const String& wildCardPattern = "*") const;
  14947. /** Finds out whether a file is inside one of the path's directories.
  14948. This will return true if the specified file is a child of one of the
  14949. directories specified by this path. Note that this doesn't actually do any
  14950. searching or check that the files exist - it just looks at the pathnames
  14951. to work out whether the file would be inside a directory.
  14952. @param fileToCheck the file to look for
  14953. @param checkRecursively if true, then this will return true if the file is inside a
  14954. subfolder of one of the path's directories (at any depth). If false
  14955. it will only return true if the file is actually a direct child
  14956. of one of the directories.
  14957. @see File::isAChildOf
  14958. */
  14959. bool isFileInPath (const File& fileToCheck,
  14960. bool checkRecursively) const;
  14961. private:
  14962. StringArray directories;
  14963. void init (const String& path);
  14964. JUCE_LEAK_DETECTOR (FileSearchPath);
  14965. };
  14966. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  14967. /*** End of inlined file: juce_FileSearchPath.h ***/
  14968. #endif
  14969. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  14970. /*** Start of inlined file: juce_NamedPipe.h ***/
  14971. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  14972. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  14973. /**
  14974. A cross-process pipe that can have data written to and read from it.
  14975. Two or more processes can use these for inter-process communication.
  14976. @see InterprocessConnection
  14977. */
  14978. class JUCE_API NamedPipe
  14979. {
  14980. public:
  14981. /** Creates a NamedPipe. */
  14982. NamedPipe();
  14983. /** Destructor. */
  14984. ~NamedPipe();
  14985. /** Tries to open a pipe that already exists.
  14986. Returns true if it succeeds.
  14987. */
  14988. bool openExisting (const String& pipeName);
  14989. /** Tries to create a new pipe.
  14990. Returns true if it succeeds.
  14991. */
  14992. bool createNewPipe (const String& pipeName);
  14993. /** Closes the pipe, if it's open. */
  14994. void close();
  14995. /** True if the pipe is currently open. */
  14996. bool isOpen() const;
  14997. /** Returns the last name that was used to try to open this pipe. */
  14998. const String getName() const;
  14999. /** Reads data from the pipe.
  15000. This will block until another thread has written enough data into the pipe to fill
  15001. the number of bytes specified, or until another thread calls the cancelPendingReads()
  15002. method.
  15003. If the operation fails, it returns -1, otherwise, it will return the number of
  15004. bytes read.
  15005. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  15006. this is a maximum timeout for reading from the pipe.
  15007. */
  15008. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  15009. /** Writes some data to the pipe.
  15010. If the operation fails, it returns -1, otherwise, it will return the number of
  15011. bytes written.
  15012. */
  15013. int write (const void* sourceBuffer, int numBytesToWrite,
  15014. int timeOutMilliseconds = 2000);
  15015. /** If any threads are currently blocked on a read operation, this tells them to abort.
  15016. */
  15017. void cancelPendingReads();
  15018. private:
  15019. void* internal;
  15020. String currentPipeName;
  15021. CriticalSection lock;
  15022. bool openInternal (const String& pipeName, const bool createPipe);
  15023. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  15024. };
  15025. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  15026. /*** End of inlined file: juce_NamedPipe.h ***/
  15027. #endif
  15028. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15029. /*** Start of inlined file: juce_TemporaryFile.h ***/
  15030. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  15031. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  15032. /**
  15033. Manages a temporary file, which will be deleted when this object is deleted.
  15034. This object is intended to be used as a stack based object, using its scope
  15035. to make sure the temporary file isn't left lying around.
  15036. For example:
  15037. @code
  15038. {
  15039. File myTargetFile ("~/myfile.txt");
  15040. // this will choose a file called something like "~/myfile_temp239348.txt"
  15041. // which definitely doesn't exist at the time the constructor is called.
  15042. TemporaryFile temp (myTargetFile);
  15043. // create a stream to the temporary file, and write some data to it...
  15044. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  15045. if (out != 0)
  15046. {
  15047. out->write ( ...etc )
  15048. out->flush();
  15049. out = 0; // (deletes the stream)
  15050. // ..now we've finished writing, this will rename the temp file to
  15051. // make it replace the target file we specified above.
  15052. bool succeeded = temp.overwriteTargetFileWithTemporary();
  15053. }
  15054. // ..and even if something went wrong and our overwrite failed,
  15055. // as the TemporaryFile object goes out of scope here, it'll make sure
  15056. // that the temp file gets deleted.
  15057. }
  15058. @endcode
  15059. @see File, FileOutputStream
  15060. */
  15061. class JUCE_API TemporaryFile
  15062. {
  15063. public:
  15064. enum OptionFlags
  15065. {
  15066. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  15067. i.e. its name should start with a dot. */
  15068. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  15069. the file is unique, they should go in brackets rather
  15070. than just being appended (see File::getNonexistentSibling() )*/
  15071. };
  15072. /** Creates a randomly-named temporary file in the default temp directory.
  15073. @param suffix a file suffix to use for the file
  15074. @param optionFlags a combination of the values listed in the OptionFlags enum
  15075. The file will not be created until you write to it. And remember that when
  15076. this object is deleted, the file will also be deleted!
  15077. */
  15078. TemporaryFile (const String& suffix = String::empty,
  15079. int optionFlags = 0);
  15080. /** Creates a temporary file in the same directory as a specified file.
  15081. This is useful if you have a file that you want to overwrite, but don't
  15082. want to harm the original file if the write operation fails. You can
  15083. use this to create a temporary file next to the target file, then
  15084. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  15085. to replace the target file with the one you've just written.
  15086. This class won't create any files until you actually write to them. And remember
  15087. that when this object is deleted, the temporary file will also be deleted!
  15088. @param targetFile the file that you intend to overwrite - the temporary
  15089. file will be created in the same directory as this
  15090. @param optionFlags a combination of the values listed in the OptionFlags enum
  15091. */
  15092. TemporaryFile (const File& targetFile,
  15093. int optionFlags = 0);
  15094. /** Destructor.
  15095. When this object is deleted it will make sure that its temporary file is
  15096. also deleted! If the operation fails, it'll throw an assertion in debug
  15097. mode.
  15098. */
  15099. ~TemporaryFile();
  15100. /** Returns the temporary file. */
  15101. const File getFile() const { return temporaryFile; }
  15102. /** Returns the target file that was specified in the constructor. */
  15103. const File getTargetFile() const { return targetFile; }
  15104. /** Tries to move the temporary file to overwrite the target file that was
  15105. specified in the constructor.
  15106. If you used the constructor that specified a target file, this will attempt
  15107. to replace that file with the temporary one.
  15108. Before calling this, make sure:
  15109. - that you've actually written to the temporary file
  15110. - that you've closed any open streams that you were using to write to it
  15111. - and that you don't have any streams open to the target file, which would
  15112. prevent it being overwritten
  15113. If the file move succeeds, this returns false, and the temporary file will
  15114. have disappeared. If it fails, the temporary file will probably still exist,
  15115. but will be deleted when this object is destroyed.
  15116. */
  15117. bool overwriteTargetFileWithTemporary() const;
  15118. /** Attempts to delete the temporary file, if it exists.
  15119. @returns true if the file is successfully deleted (or if it didn't exist).
  15120. */
  15121. bool deleteTemporaryFile() const;
  15122. private:
  15123. File temporaryFile, targetFile;
  15124. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  15125. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  15126. };
  15127. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  15128. /*** End of inlined file: juce_TemporaryFile.h ***/
  15129. #endif
  15130. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15131. /*** Start of inlined file: juce_ZipFile.h ***/
  15132. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  15133. #define __JUCE_ZIPFILE_JUCEHEADER__
  15134. /*** Start of inlined file: juce_InputSource.h ***/
  15135. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15136. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  15137. /**
  15138. A lightweight object that can create a stream to read some kind of resource.
  15139. This may be used to refer to a file, or some other kind of source, allowing a
  15140. caller to create an input stream that can read from it when required.
  15141. @see FileInputSource
  15142. */
  15143. class JUCE_API InputSource
  15144. {
  15145. public:
  15146. InputSource() throw() {}
  15147. /** Destructor. */
  15148. virtual ~InputSource() {}
  15149. /** Returns a new InputStream to read this item.
  15150. @returns an inputstream that the caller will delete, or 0 if
  15151. the filename isn't found.
  15152. */
  15153. virtual InputStream* createInputStream() = 0;
  15154. /** Returns a new InputStream to read an item, relative.
  15155. @param relatedItemPath the relative pathname of the resource that is required
  15156. @returns an inputstream that the caller will delete, or 0 if
  15157. the item isn't found.
  15158. */
  15159. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  15160. /** Returns a hash code that uniquely represents this item.
  15161. */
  15162. virtual int64 hashCode() const = 0;
  15163. private:
  15164. JUCE_LEAK_DETECTOR (InputSource);
  15165. };
  15166. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  15167. /*** End of inlined file: juce_InputSource.h ***/
  15168. /**
  15169. Decodes a ZIP file from a stream.
  15170. This can enumerate the items in a ZIP file and can create suitable stream objects
  15171. to read each one.
  15172. */
  15173. class JUCE_API ZipFile
  15174. {
  15175. public:
  15176. /** Creates a ZipFile for a given stream.
  15177. @param inputStream the stream to read from
  15178. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  15179. will be deleted when this ZipFile object is deleted
  15180. */
  15181. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  15182. /** Creates a ZipFile based for a file. */
  15183. ZipFile (const File& file);
  15184. /** Creates a ZipFile for an input source.
  15185. The inputSource object will be owned by the zip file, which will delete
  15186. it later when not needed.
  15187. */
  15188. ZipFile (InputSource* inputSource);
  15189. /** Destructor. */
  15190. ~ZipFile();
  15191. /**
  15192. Contains information about one of the entries in a ZipFile.
  15193. @see ZipFile::getEntry
  15194. */
  15195. struct ZipEntry
  15196. {
  15197. /** The name of the file, which may also include a partial pathname. */
  15198. String filename;
  15199. /** The file's original size. */
  15200. unsigned int uncompressedSize;
  15201. /** The last time the file was modified. */
  15202. Time fileTime;
  15203. };
  15204. /** Returns the number of items in the zip file. */
  15205. int getNumEntries() const throw();
  15206. /** Returns a structure that describes one of the entries in the zip file.
  15207. This may return zero if the index is out of range.
  15208. @see ZipFile::ZipEntry
  15209. */
  15210. const ZipEntry* getEntry (int index) const throw();
  15211. /** Returns the index of the first entry with a given filename.
  15212. This uses a case-sensitive comparison to look for a filename in the
  15213. list of entries. It might return -1 if no match is found.
  15214. @see ZipFile::ZipEntry
  15215. */
  15216. int getIndexOfFileName (const String& fileName) const throw();
  15217. /** Returns a structure that describes one of the entries in the zip file.
  15218. This uses a case-sensitive comparison to look for a filename in the
  15219. list of entries. It might return 0 if no match is found.
  15220. @see ZipFile::ZipEntry
  15221. */
  15222. const ZipEntry* getEntry (const String& fileName) const throw();
  15223. /** Sorts the list of entries, based on the filename.
  15224. */
  15225. void sortEntriesByFilename();
  15226. /** Creates a stream that can read from one of the zip file's entries.
  15227. The stream that is returned must be deleted by the caller (and
  15228. zero might be returned if a stream can't be opened for some reason).
  15229. The stream must not be used after the ZipFile object that created
  15230. has been deleted.
  15231. */
  15232. InputStream* createStreamForEntry (int index);
  15233. /** Creates a stream that can read from one of the zip file's entries.
  15234. The stream that is returned must be deleted by the caller (and
  15235. zero might be returned if a stream can't be opened for some reason).
  15236. The stream must not be used after the ZipFile object that created
  15237. has been deleted.
  15238. */
  15239. InputStream* createStreamForEntry (ZipEntry& entry);
  15240. /** Uncompresses all of the files in the zip file.
  15241. This will expand all the entries into a target directory. The relative
  15242. paths of the entries are used.
  15243. @param targetDirectory the root folder to uncompress to
  15244. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15245. @returns true if all the files are successfully unzipped
  15246. */
  15247. bool uncompressTo (const File& targetDirectory,
  15248. bool shouldOverwriteFiles = true);
  15249. /** Uncompresses one of the entries from the zip file.
  15250. This will expand the entry and write it in a target directory. The entry's path is used to
  15251. determine which subfolder of the target should contain the new file.
  15252. @param index the index of the entry to uncompress
  15253. @param targetDirectory the root folder to uncompress into
  15254. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  15255. @returns true if the files is successfully unzipped
  15256. */
  15257. bool uncompressEntry (int index,
  15258. const File& targetDirectory,
  15259. bool shouldOverwriteFiles = true);
  15260. /** Used to create a new zip file.
  15261. Create a ZipFile::Builder object, and call its addFile() method to add some files,
  15262. then you can write it to a stream with write().
  15263. Currently this just stores the files with no compression.. That will be added
  15264. soon!
  15265. */
  15266. class Builder
  15267. {
  15268. public:
  15269. Builder();
  15270. ~Builder();
  15271. /** Adds a file while should be added to the archive.
  15272. The file isn't read immediately, all the files will be read later when the writeToStream()
  15273. method is called.
  15274. The compressionLevel can be between 0 (no compression), and 9 (maximum compression).
  15275. If the storedPathName parameter is specified, you can customise the partial pathname that
  15276. will be stored for this file.
  15277. */
  15278. void addFile (const File& fileToAdd, int compressionLevel,
  15279. const String& storedPathName = String::empty);
  15280. /** Generates the zip file, writing it to the specified stream. */
  15281. bool writeToStream (OutputStream& target) const;
  15282. private:
  15283. class Item;
  15284. friend class OwnedArray<Item>;
  15285. OwnedArray<Item> items;
  15286. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Builder);
  15287. };
  15288. private:
  15289. class ZipInputStream;
  15290. class ZipFilenameComparator;
  15291. class ZipEntryInfo;
  15292. friend class ZipInputStream;
  15293. friend class ZipFilenameComparator;
  15294. friend class ZipEntryInfo;
  15295. OwnedArray <ZipEntryInfo> entries;
  15296. CriticalSection lock;
  15297. InputStream* inputStream;
  15298. ScopedPointer <InputStream> streamToDelete;
  15299. ScopedPointer <InputSource> inputSource;
  15300. #if JUCE_DEBUG
  15301. int numOpenStreams;
  15302. #endif
  15303. void init();
  15304. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  15305. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  15306. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  15307. };
  15308. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  15309. /*** End of inlined file: juce_ZipFile.h ***/
  15310. #endif
  15311. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15312. /*** Start of inlined file: juce_MACAddress.h ***/
  15313. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  15314. #define __JUCE_MACADDRESS_JUCEHEADER__
  15315. /**
  15316. A wrapper for a streaming (TCP) socket.
  15317. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15318. sockets, you could also try the InterprocessConnection class.
  15319. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15320. */
  15321. class JUCE_API MACAddress
  15322. {
  15323. public:
  15324. /** Populates a list of the MAC addresses of all the available network cards. */
  15325. static void findAllAddresses (Array<MACAddress>& results);
  15326. /** Creates a null address (00-00-00-00-00-00). */
  15327. MACAddress();
  15328. /** Creates a copy of another address. */
  15329. MACAddress (const MACAddress& other);
  15330. /** Creates a copy of another address. */
  15331. MACAddress& operator= (const MACAddress& other);
  15332. /** Creates an address from 6 bytes. */
  15333. explicit MACAddress (const uint8 bytes[6]);
  15334. /** Returns a pointer to the 6 bytes that make up this address. */
  15335. const uint8* getBytes() const throw() { return asBytes; }
  15336. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  15337. const String toString() const;
  15338. /** Returns the address in the lower 6 bytes of an int64.
  15339. This uses a little-endian arrangement, with the first byte of the address being
  15340. stored in the least-significant byte of the result value.
  15341. */
  15342. int64 toInt64() const throw();
  15343. /** Returns true if this address is null (00-00-00-00-00-00). */
  15344. bool isNull() const throw();
  15345. bool operator== (const MACAddress& other) const throw();
  15346. bool operator!= (const MACAddress& other) const throw();
  15347. private:
  15348. #ifndef DOXYGEN
  15349. union
  15350. {
  15351. uint64 asInt64;
  15352. uint8 asBytes[6];
  15353. };
  15354. #endif
  15355. };
  15356. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  15357. /*** End of inlined file: juce_MACAddress.h ***/
  15358. #endif
  15359. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15360. /*** Start of inlined file: juce_Socket.h ***/
  15361. #ifndef __JUCE_SOCKET_JUCEHEADER__
  15362. #define __JUCE_SOCKET_JUCEHEADER__
  15363. /**
  15364. A wrapper for a streaming (TCP) socket.
  15365. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15366. sockets, you could also try the InterprocessConnection class.
  15367. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  15368. */
  15369. class JUCE_API StreamingSocket
  15370. {
  15371. public:
  15372. /** Creates an uninitialised socket.
  15373. To connect it, use the connect() method, after which you can read() or write()
  15374. to it.
  15375. To wait for other sockets to connect to this one, the createListener() method
  15376. enters "listener" mode, and can be used to spawn new sockets for each connection
  15377. that comes along.
  15378. */
  15379. StreamingSocket();
  15380. /** Destructor. */
  15381. ~StreamingSocket();
  15382. /** Binds the socket to the specified local port.
  15383. @returns true on success; false may indicate that another socket is already bound
  15384. on the same port
  15385. */
  15386. bool bindToPort (int localPortNumber);
  15387. /** Tries to connect the socket to hostname:port.
  15388. If timeOutMillisecs is 0, then this method will block until the operating system
  15389. rejects the connection (which could take a long time).
  15390. @returns true if it succeeds.
  15391. @see isConnected
  15392. */
  15393. bool connect (const String& remoteHostname,
  15394. int remotePortNumber,
  15395. int timeOutMillisecs = 3000);
  15396. /** True if the socket is currently connected. */
  15397. bool isConnected() const throw() { return connected; }
  15398. /** Closes the connection. */
  15399. void close();
  15400. /** Returns the name of the currently connected host. */
  15401. const String& getHostName() const throw() { return hostName; }
  15402. /** Returns the port number that's currently open. */
  15403. int getPort() const throw() { return portNumber; }
  15404. /** True if the socket is connected to this machine rather than over the network. */
  15405. bool isLocal() const throw();
  15406. /** Waits until the socket is ready for reading or writing.
  15407. If readyForReading is true, it will wait until the socket is ready for
  15408. reading; if false, it will wait until it's ready for writing.
  15409. If the timeout is < 0, it will wait forever, or else will give up after
  15410. the specified time.
  15411. If the socket is ready on return, this returns 1. If it times-out before
  15412. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15413. */
  15414. int waitUntilReady (bool readyForReading,
  15415. int timeoutMsecs) const;
  15416. /** Reads bytes from the socket.
  15417. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15418. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15419. flag is false, the method will return as much data as is currently available
  15420. without blocking.
  15421. @returns the number of bytes read, or -1 if there was an error.
  15422. @see waitUntilReady
  15423. */
  15424. int read (void* destBuffer, int maxBytesToRead,
  15425. bool blockUntilSpecifiedAmountHasArrived);
  15426. /** Writes bytes to the socket from a buffer.
  15427. Note that this method will block unless you have checked the socket is ready
  15428. for writing before calling it (see the waitUntilReady() method).
  15429. @returns the number of bytes written, or -1 if there was an error.
  15430. */
  15431. int write (const void* sourceBuffer, int numBytesToWrite);
  15432. /** Puts this socket into "listener" mode.
  15433. When in this mode, your thread can call waitForNextConnection() repeatedly,
  15434. which will spawn new sockets for each new connection, so that these can
  15435. be handled in parallel by other threads.
  15436. @param portNumber the port number to listen on
  15437. @param localHostName the interface address to listen on - pass an empty
  15438. string to listen on all addresses
  15439. @returns true if it manages to open the socket successfully.
  15440. @see waitForNextConnection
  15441. */
  15442. bool createListener (int portNumber, const String& localHostName = String::empty);
  15443. /** When in "listener" mode, this waits for a connection and spawns it as a new
  15444. socket.
  15445. The object that gets returned will be owned by the caller.
  15446. This method can only be called after using createListener().
  15447. @see createListener
  15448. */
  15449. StreamingSocket* waitForNextConnection() const;
  15450. private:
  15451. String hostName;
  15452. int volatile portNumber, handle;
  15453. bool connected, isListener;
  15454. StreamingSocket (const String& hostname, int portNumber, int handle);
  15455. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  15456. };
  15457. /**
  15458. A wrapper for a datagram (UDP) socket.
  15459. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  15460. sockets, you could also try the InterprocessConnection class.
  15461. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  15462. */
  15463. class JUCE_API DatagramSocket
  15464. {
  15465. public:
  15466. /**
  15467. Creates an (uninitialised) datagram socket.
  15468. The localPortNumber is the port on which to bind this socket. If this value is 0,
  15469. the port number is assigned by the operating system.
  15470. To use the socket for sending, call the connect() method. This will not immediately
  15471. make a connection, but will save the destination you've provided. After this, you can
  15472. call read() or write().
  15473. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  15474. (may require extra privileges on linux)
  15475. To wait for other sockets to connect to this one, call waitForNextConnection().
  15476. */
  15477. DatagramSocket (int localPortNumber,
  15478. bool enableBroadcasting = false);
  15479. /** Destructor. */
  15480. ~DatagramSocket();
  15481. /** Binds the socket to the specified local port.
  15482. @returns true on success; false may indicate that another socket is already bound
  15483. on the same port
  15484. */
  15485. bool bindToPort (int localPortNumber);
  15486. /** Tries to connect the socket to hostname:port.
  15487. If timeOutMillisecs is 0, then this method will block until the operating system
  15488. rejects the connection (which could take a long time).
  15489. @returns true if it succeeds.
  15490. @see isConnected
  15491. */
  15492. bool connect (const String& remoteHostname,
  15493. int remotePortNumber,
  15494. int timeOutMillisecs = 3000);
  15495. /** True if the socket is currently connected. */
  15496. bool isConnected() const throw() { return connected; }
  15497. /** Closes the connection. */
  15498. void close();
  15499. /** Returns the name of the currently connected host. */
  15500. const String& getHostName() const throw() { return hostName; }
  15501. /** Returns the port number that's currently open. */
  15502. int getPort() const throw() { return portNumber; }
  15503. /** True if the socket is connected to this machine rather than over the network. */
  15504. bool isLocal() const throw();
  15505. /** Waits until the socket is ready for reading or writing.
  15506. If readyForReading is true, it will wait until the socket is ready for
  15507. reading; if false, it will wait until it's ready for writing.
  15508. If the timeout is < 0, it will wait forever, or else will give up after
  15509. the specified time.
  15510. If the socket is ready on return, this returns 1. If it times-out before
  15511. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15512. */
  15513. int waitUntilReady (bool readyForReading,
  15514. int timeoutMsecs) const;
  15515. /** Reads bytes from the socket.
  15516. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15517. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15518. flag is false, the method will return as much data as is currently available
  15519. without blocking.
  15520. @returns the number of bytes read, or -1 if there was an error.
  15521. @see waitUntilReady
  15522. */
  15523. int read (void* destBuffer, int maxBytesToRead,
  15524. bool blockUntilSpecifiedAmountHasArrived);
  15525. /** Writes bytes to the socket from a buffer.
  15526. Note that this method will block unless you have checked the socket is ready
  15527. for writing before calling it (see the waitUntilReady() method).
  15528. @returns the number of bytes written, or -1 if there was an error.
  15529. */
  15530. int write (const void* sourceBuffer, int numBytesToWrite);
  15531. /** This waits for incoming data to be sent, and returns a socket that can be used
  15532. to read it.
  15533. The object that gets returned is owned by the caller, and can't be used for
  15534. sending, but can be used to read the data.
  15535. */
  15536. DatagramSocket* waitForNextConnection() const;
  15537. private:
  15538. String hostName;
  15539. int volatile portNumber, handle;
  15540. bool connected, allowBroadcast;
  15541. void* serverAddress;
  15542. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  15543. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  15544. };
  15545. #endif // __JUCE_SOCKET_JUCEHEADER__
  15546. /*** End of inlined file: juce_Socket.h ***/
  15547. #endif
  15548. #ifndef __JUCE_URL_JUCEHEADER__
  15549. /*** Start of inlined file: juce_URL.h ***/
  15550. #ifndef __JUCE_URL_JUCEHEADER__
  15551. #define __JUCE_URL_JUCEHEADER__
  15552. /**
  15553. Represents a URL and has a bunch of useful functions to manipulate it.
  15554. This class can be used to launch URLs in browsers, and also to create
  15555. InputStreams that can read from remote http or ftp sources.
  15556. */
  15557. class JUCE_API URL
  15558. {
  15559. public:
  15560. /** Creates an empty URL. */
  15561. URL();
  15562. /** Creates a URL from a string. */
  15563. URL (const String& url);
  15564. /** Creates a copy of another URL. */
  15565. URL (const URL& other);
  15566. /** Destructor. */
  15567. ~URL();
  15568. /** Copies this URL from another one. */
  15569. URL& operator= (const URL& other);
  15570. /** Returns a string version of the URL.
  15571. If includeGetParameters is true and any parameters have been set with the
  15572. withParameter() method, then the string will have these appended on the
  15573. end and url-encoded.
  15574. */
  15575. const String toString (bool includeGetParameters) const;
  15576. /** True if it seems to be valid. */
  15577. bool isWellFormed() const;
  15578. /** Returns just the domain part of the URL.
  15579. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  15580. */
  15581. const String getDomain() const;
  15582. /** Returns the path part of the URL.
  15583. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  15584. */
  15585. const String getSubPath() const;
  15586. /** Returns the scheme of the URL.
  15587. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  15588. include the colon).
  15589. */
  15590. const String getScheme() const;
  15591. /** Returns a new version of this URL that uses a different sub-path.
  15592. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  15593. "bar", it'll return "http://www.xyz.com/bar?x=1".
  15594. */
  15595. const URL withNewSubPath (const String& newPath) const;
  15596. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  15597. Any control characters in the value will be encoded.
  15598. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  15599. would produce a new url whose toString(true) method would return
  15600. "www.fish.com?amount=some+fish".
  15601. */
  15602. const URL withParameter (const String& parameterName,
  15603. const String& parameterValue) const;
  15604. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  15605. When performing a POST where one of your parameters is a binary file, this
  15606. lets you specify the file.
  15607. Note that the filename is stored, but the file itself won't actually be read
  15608. until this URL is later used to create a network input stream.
  15609. */
  15610. const URL withFileToUpload (const String& parameterName,
  15611. const File& fileToUpload,
  15612. const String& mimeType) const;
  15613. /** Returns a set of all the parameters encoded into the url.
  15614. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  15615. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  15616. The values returned will have been cleaned up to remove any escape characters.
  15617. @see getNamedParameter, withParameter
  15618. */
  15619. const StringPairArray& getParameters() const;
  15620. /** Returns the set of files that should be uploaded as part of a POST operation.
  15621. This is the set of files that were added to the URL with the withFileToUpload()
  15622. method.
  15623. */
  15624. const StringPairArray& getFilesToUpload() const;
  15625. /** Returns the set of mime types associated with each of the upload files.
  15626. */
  15627. const StringPairArray& getMimeTypesOfUploadFiles() const;
  15628. /** Returns a copy of this URL, with a block of data to send as the POST data.
  15629. If you're setting the POST data, be careful not to have any parameters set
  15630. as well, otherwise it'll all get thrown in together, and might not have the
  15631. desired effect.
  15632. If the URL already contains some POST data, this will replace it, rather
  15633. than being appended to it.
  15634. This data will only be used if you specify a post operation when you call
  15635. createInputStream().
  15636. */
  15637. const URL withPOSTData (const String& postData) const;
  15638. /** Returns the data that was set using withPOSTData().
  15639. */
  15640. const String getPostData() const { return postData; }
  15641. /** Tries to launch the system's default browser to open the URL.
  15642. Returns true if this seems to have worked.
  15643. */
  15644. bool launchInDefaultBrowser() const;
  15645. /** Takes a guess as to whether a string might be a valid website address.
  15646. This isn't foolproof!
  15647. */
  15648. static bool isProbablyAWebsiteURL (const String& possibleURL);
  15649. /** Takes a guess as to whether a string might be a valid email address.
  15650. This isn't foolproof!
  15651. */
  15652. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  15653. /** This callback function can be used by the createInputStream() method.
  15654. It allows your app to receive progress updates during a lengthy POST operation. If you
  15655. want to continue the operation, this should return true, or false to abort.
  15656. */
  15657. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  15658. /** Attempts to open a stream that can read from this URL.
  15659. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  15660. the paramters, otherwise it'll encode them into the
  15661. URL and do a 'GET'.
  15662. @param progressCallback if this is non-zero, it lets you supply a callback function
  15663. to keep track of the operation's progress. This can be useful
  15664. for lengthy POST operations, so that you can provide user feedback.
  15665. @param progressCallbackContext if a callback is specified, this value will be passed to
  15666. the function
  15667. @param extraHeaders if not empty, this string is appended onto the headers that
  15668. are used for the request. It must therefore be a valid set of HTML
  15669. header directives, separated by newlines.
  15670. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15671. a negative number, it will be infinite. Otherwise it specifies a
  15672. time in milliseconds.
  15673. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15674. in the response will be stored in this array
  15675. @returns an input stream that the caller must delete, or a null pointer if there was an
  15676. error trying to open it.
  15677. */
  15678. InputStream* createInputStream (bool usePostCommand,
  15679. OpenStreamProgressCallback* progressCallback = 0,
  15680. void* progressCallbackContext = 0,
  15681. const String& extraHeaders = String::empty,
  15682. int connectionTimeOutMs = 0,
  15683. StringPairArray* responseHeaders = 0) const;
  15684. /** Tries to download the entire contents of this URL into a binary data block.
  15685. If it succeeds, this will return true and append the data it read onto the end
  15686. of the memory block.
  15687. @param destData the memory block to append the new data to
  15688. @param usePostCommand whether to use a POST command to get the data (uses
  15689. a GET command if this is false)
  15690. @see readEntireTextStream, readEntireXmlStream
  15691. */
  15692. bool readEntireBinaryStream (MemoryBlock& destData,
  15693. bool usePostCommand = false) const;
  15694. /** Tries to download the entire contents of this URL as a string.
  15695. If it fails, this will return an empty string, otherwise it will return the
  15696. contents of the downloaded file. If you need to distinguish between a read
  15697. operation that fails and one that returns an empty string, you'll need to use
  15698. a different method, such as readEntireBinaryStream().
  15699. @param usePostCommand whether to use a POST command to get the data (uses
  15700. a GET command if this is false)
  15701. @see readEntireBinaryStream, readEntireXmlStream
  15702. */
  15703. const String readEntireTextStream (bool usePostCommand = false) const;
  15704. /** Tries to download the entire contents of this URL and parse it as XML.
  15705. If it fails, or if the text that it reads can't be parsed as XML, this will
  15706. return 0.
  15707. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15708. this object when no longer needed.
  15709. @param usePostCommand whether to use a POST command to get the data (uses
  15710. a GET command if this is false)
  15711. @see readEntireBinaryStream, readEntireTextStream
  15712. */
  15713. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15714. /** Adds escape sequences to a string to encode any characters that aren't
  15715. legal in a URL.
  15716. E.g. any spaces will be replaced with "%20".
  15717. This is the opposite of removeEscapeChars().
  15718. If isParameter is true, it means that the string is going to be used
  15719. as a parameter, so it also encodes '$' and ',' (which would otherwise
  15720. be legal in a URL.
  15721. @see removeEscapeChars
  15722. */
  15723. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  15724. bool isParameter);
  15725. /** Replaces any escape character sequences in a string with their original
  15726. character codes.
  15727. E.g. any instances of "%20" will be replaced by a space.
  15728. This is the opposite of addEscapeChars().
  15729. @see addEscapeChars
  15730. */
  15731. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  15732. private:
  15733. String url, postData;
  15734. StringPairArray parameters, filesToUpload, mimeTypes;
  15735. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  15736. OpenStreamProgressCallback* progressCallback,
  15737. void* progressCallbackContext, const String& headers,
  15738. const int timeOutMs, StringPairArray* responseHeaders);
  15739. JUCE_LEAK_DETECTOR (URL);
  15740. };
  15741. #endif // __JUCE_URL_JUCEHEADER__
  15742. /*** End of inlined file: juce_URL.h ***/
  15743. #endif
  15744. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15745. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  15746. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15747. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15748. /*** Start of inlined file: juce_OptionalScopedPointer.h ***/
  15749. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15750. #define __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15751. /**
  15752. Holds a pointer to an object which can optionally be deleted when this pointer
  15753. goes out of scope.
  15754. This acts in many ways like a ScopedPointer, but allows you to specify whether or
  15755. not the object is deleted.
  15756. @see ScopedPointer
  15757. */
  15758. template <class ObjectType>
  15759. class OptionalScopedPointer
  15760. {
  15761. public:
  15762. /** Creates an empty OptionalScopedPointer. */
  15763. OptionalScopedPointer() : shouldDelete (false) {}
  15764. /** Creates an OptionalScopedPointer to point to a given object, and specifying whether
  15765. the OptionalScopedPointer will delete it.
  15766. If takeOwnership is true, then the OptionalScopedPointer will act like a ScopedPointer,
  15767. deleting the object when it is itself deleted. If this parameter is false, then the
  15768. OptionalScopedPointer just holds a normal pointer to the object, and won't delete it.
  15769. */
  15770. OptionalScopedPointer (ObjectType* objectToHold, bool takeOwnership)
  15771. : object (objectToHold), shouldDelete (takeOwnership)
  15772. {
  15773. }
  15774. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15775. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15776. as ownership of the managed object is transferred to this object.
  15777. The flag to indicate whether or not to delete the managed object is also
  15778. copied from the source object.
  15779. */
  15780. OptionalScopedPointer (OptionalScopedPointer& objectToTransferFrom)
  15781. : object (objectToTransferFrom.release()),
  15782. shouldDelete (objectToTransferFrom.shouldDelete)
  15783. {
  15784. }
  15785. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15786. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15787. as ownership of the managed object is transferred to this object.
  15788. The ownership flag that says whether or not to delete the managed object is also
  15789. copied from the source object.
  15790. */
  15791. OptionalScopedPointer& operator= (OptionalScopedPointer& objectToTransferFrom)
  15792. {
  15793. if (object != objectToTransferFrom.object)
  15794. {
  15795. clear();
  15796. object = objectToTransferFrom.object;
  15797. }
  15798. shouldDelete = objectToTransferFrom.shouldDelete;
  15799. return *this;
  15800. }
  15801. /** The destructor may or may not delete the object that is being held, depending on the
  15802. takeOwnership flag that was specified when the object was first passed into an
  15803. OptionalScopedPointer constructor.
  15804. */
  15805. ~OptionalScopedPointer()
  15806. {
  15807. clear();
  15808. }
  15809. /** Returns the object that this pointer is managing. */
  15810. inline operator ObjectType*() const throw() { return object; }
  15811. /** Returns the object that this pointer is managing. */
  15812. inline ObjectType& operator*() const throw() { return *object; }
  15813. /** Lets you access methods and properties of the object that this pointer is holding. */
  15814. inline ObjectType* operator->() const throw() { return object; }
  15815. /** Removes the current object from this OptionalScopedPointer without deleting it.
  15816. This will return the current object, and set this OptionalScopedPointer to a null pointer.
  15817. */
  15818. ObjectType* release() throw() { return object.release(); }
  15819. /** Resets this pointer to null, possibly deleting the object that it holds, if it has
  15820. ownership of it.
  15821. */
  15822. void clear()
  15823. {
  15824. if (! shouldDelete)
  15825. object.release();
  15826. }
  15827. /** Swaps this object with another OptionalScopedPointer.
  15828. The two objects simply exchange their states.
  15829. */
  15830. void swapWith (OptionalScopedPointer<ObjectType>& other) throw()
  15831. {
  15832. object.swapWith (other.object);
  15833. swapVariables (shouldDelete, other.shouldDelete);
  15834. }
  15835. private:
  15836. ScopedPointer<ObjectType> object;
  15837. bool shouldDelete;
  15838. };
  15839. #endif // __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15840. /*** End of inlined file: juce_OptionalScopedPointer.h ***/
  15841. /** Wraps another input stream, and reads from it using an intermediate buffer
  15842. If you're using an input stream such as a file input stream, and making lots of
  15843. small read accesses to it, it's probably sensible to wrap it in one of these,
  15844. so that the source stream gets accessed in larger chunk sizes, meaning less
  15845. work for the underlying stream.
  15846. */
  15847. class JUCE_API BufferedInputStream : public InputStream
  15848. {
  15849. public:
  15850. /** Creates a BufferedInputStream from an input source.
  15851. @param sourceStream the source stream to read from
  15852. @param bufferSize the size of reservoir to use to buffer the source
  15853. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15854. deleted by this object when it is itself deleted.
  15855. */
  15856. BufferedInputStream (InputStream* sourceStream,
  15857. int bufferSize,
  15858. bool deleteSourceWhenDestroyed);
  15859. /** Creates a BufferedInputStream from an input source.
  15860. @param sourceStream the source stream to read from - the source stream must not
  15861. be deleted until this object has been destroyed.
  15862. @param bufferSize the size of reservoir to use to buffer the source
  15863. */
  15864. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  15865. /** Destructor.
  15866. This may also delete the source stream, if that option was chosen when the
  15867. buffered stream was created.
  15868. */
  15869. ~BufferedInputStream();
  15870. int64 getTotalLength();
  15871. int64 getPosition();
  15872. bool setPosition (int64 newPosition);
  15873. int read (void* destBuffer, int maxBytesToRead);
  15874. const String readString();
  15875. bool isExhausted();
  15876. private:
  15877. OptionalScopedPointer<InputStream> source;
  15878. int bufferSize;
  15879. int64 position, lastReadPos, bufferStart, bufferOverlap;
  15880. HeapBlock <char> buffer;
  15881. void ensureBuffered();
  15882. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  15883. };
  15884. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15885. /*** End of inlined file: juce_BufferedInputStream.h ***/
  15886. #endif
  15887. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15888. /*** Start of inlined file: juce_FileInputSource.h ***/
  15889. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15890. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15891. /**
  15892. A type of InputSource that represents a normal file.
  15893. @see InputSource
  15894. */
  15895. class JUCE_API FileInputSource : public InputSource
  15896. {
  15897. public:
  15898. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  15899. ~FileInputSource();
  15900. InputStream* createInputStream();
  15901. InputStream* createInputStreamFor (const String& relatedItemPath);
  15902. int64 hashCode() const;
  15903. private:
  15904. const File file;
  15905. bool useFileTimeInHashGeneration;
  15906. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  15907. };
  15908. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15909. /*** End of inlined file: juce_FileInputSource.h ***/
  15910. #endif
  15911. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15912. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15913. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15914. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15915. /**
  15916. A stream which uses zlib to compress the data written into it.
  15917. @see GZIPDecompressorInputStream
  15918. */
  15919. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  15920. {
  15921. public:
  15922. /** Creates a compression stream.
  15923. @param destStream the stream into which the compressed data should
  15924. be written
  15925. @param compressionLevel how much to compress the data, between 1 and 9, where
  15926. 1 is the fastest/lowest compression, and 9 is the
  15927. slowest/highest compression. Any value outside this range
  15928. indicates that a default compression level should be used.
  15929. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  15930. this stream is destroyed
  15931. @param windowBits this is used internally to change the window size used
  15932. by zlib - leave it as 0 unless you specifically need to set
  15933. its value for some reason
  15934. */
  15935. GZIPCompressorOutputStream (OutputStream* destStream,
  15936. int compressionLevel = 0,
  15937. bool deleteDestStreamWhenDestroyed = false,
  15938. int windowBits = 0);
  15939. /** Destructor. */
  15940. ~GZIPCompressorOutputStream();
  15941. void flush();
  15942. int64 getPosition();
  15943. bool setPosition (int64 newPosition);
  15944. bool write (const void* destBuffer, int howMany);
  15945. /** These are preset values that can be used for the constructor's windowBits paramter.
  15946. For more info about this, see the zlib documentation for its windowBits parameter.
  15947. */
  15948. enum WindowBitsValues
  15949. {
  15950. windowBitsRaw = -15,
  15951. windowBitsGZIP = 15 + 16
  15952. };
  15953. private:
  15954. OptionalScopedPointer<OutputStream> destStream;
  15955. HeapBlock <uint8> buffer;
  15956. class GZIPCompressorHelper;
  15957. friend class ScopedPointer <GZIPCompressorHelper>;
  15958. ScopedPointer <GZIPCompressorHelper> helper;
  15959. bool doNextBlock();
  15960. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  15961. };
  15962. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15963. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15964. #endif
  15965. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15966. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  15967. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15968. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15969. /**
  15970. This stream will decompress a source-stream using zlib.
  15971. Tip: if you're reading lots of small items from one of these streams, you
  15972. can increase the performance enormously by passing it through a
  15973. BufferedInputStream, so that it has to read larger blocks less often.
  15974. @see GZIPCompressorOutputStream
  15975. */
  15976. class JUCE_API GZIPDecompressorInputStream : public InputStream
  15977. {
  15978. public:
  15979. /** Creates a decompressor stream.
  15980. @param sourceStream the stream to read from
  15981. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  15982. when this object is destroyed
  15983. @param noWrap this is used internally by the ZipFile class
  15984. and should be ignored by user applications
  15985. @param uncompressedStreamLength if the creator knows the length that the
  15986. uncompressed stream will be, then it can supply this
  15987. value, which will be returned by getTotalLength()
  15988. */
  15989. GZIPDecompressorInputStream (InputStream* sourceStream,
  15990. bool deleteSourceWhenDestroyed,
  15991. bool noWrap = false,
  15992. int64 uncompressedStreamLength = -1);
  15993. /** Creates a decompressor stream.
  15994. @param sourceStream the stream to read from - the source stream must not be
  15995. deleted until this object has been destroyed
  15996. */
  15997. GZIPDecompressorInputStream (InputStream& sourceStream);
  15998. /** Destructor. */
  15999. ~GZIPDecompressorInputStream();
  16000. int64 getPosition();
  16001. bool setPosition (int64 pos);
  16002. int64 getTotalLength();
  16003. bool isExhausted();
  16004. int read (void* destBuffer, int maxBytesToRead);
  16005. private:
  16006. OptionalScopedPointer<InputStream> sourceStream;
  16007. const int64 uncompressedStreamLength;
  16008. const bool noWrap;
  16009. bool isEof;
  16010. int activeBufferSize;
  16011. int64 originalSourcePos, currentPos;
  16012. HeapBlock <uint8> buffer;
  16013. class GZIPDecompressHelper;
  16014. friend class ScopedPointer <GZIPDecompressHelper>;
  16015. ScopedPointer <GZIPDecompressHelper> helper;
  16016. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  16017. };
  16018. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  16019. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  16020. #endif
  16021. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  16022. #endif
  16023. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  16024. #endif
  16025. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16026. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  16027. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16028. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16029. /**
  16030. Allows a block of data and to be accessed as a stream.
  16031. This can either be used to refer to a shared block of memory, or can make its
  16032. own internal copy of the data when the MemoryInputStream is created.
  16033. */
  16034. class JUCE_API MemoryInputStream : public InputStream
  16035. {
  16036. public:
  16037. /** Creates a MemoryInputStream.
  16038. @param sourceData the block of data to use as the stream's source
  16039. @param sourceDataSize the number of bytes in the source data block
  16040. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  16041. the source data, so this data shouldn't be changed
  16042. for the lifetime of the stream; if this parameter is
  16043. true, the stream will make its own copy of the
  16044. data and use that.
  16045. */
  16046. MemoryInputStream (const void* sourceData,
  16047. size_t sourceDataSize,
  16048. bool keepInternalCopyOfData);
  16049. /** Creates a MemoryInputStream.
  16050. @param data a block of data to use as the stream's source
  16051. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  16052. the source data, so this data shouldn't be changed
  16053. for the lifetime of the stream; if this parameter is
  16054. true, the stream will make its own copy of the
  16055. data and use that.
  16056. */
  16057. MemoryInputStream (const MemoryBlock& data,
  16058. bool keepInternalCopyOfData);
  16059. /** Destructor. */
  16060. ~MemoryInputStream();
  16061. int64 getPosition();
  16062. bool setPosition (int64 pos);
  16063. int64 getTotalLength();
  16064. bool isExhausted();
  16065. int read (void* destBuffer, int maxBytesToRead);
  16066. private:
  16067. const char* data;
  16068. size_t dataSize, position;
  16069. MemoryBlock internalCopy;
  16070. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  16071. };
  16072. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  16073. /*** End of inlined file: juce_MemoryInputStream.h ***/
  16074. #endif
  16075. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16076. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  16077. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16078. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16079. /**
  16080. Writes data to an internal memory buffer, which grows as required.
  16081. The data that was written into the stream can then be accessed later as
  16082. a contiguous block of memory.
  16083. */
  16084. class JUCE_API MemoryOutputStream : public OutputStream
  16085. {
  16086. public:
  16087. /** Creates an empty memory stream ready for writing into.
  16088. @param initialSize the intial amount of capacity to allocate for writing into
  16089. */
  16090. MemoryOutputStream (size_t initialSize = 256);
  16091. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  16092. Note that the destination block will always be larger than the amount of data
  16093. that has been written to the stream, because the MemoryOutputStream keeps some
  16094. spare capactity at its end. To trim the block's size down to fit the actual
  16095. data, call flush(), or delete the MemoryOutputStream.
  16096. @param memoryBlockToWriteTo the block into which new data will be written.
  16097. @param appendToExistingBlockContent if this is true, the contents of the block will be
  16098. kept, and new data will be appended to it. If false,
  16099. the block will be cleared before use
  16100. */
  16101. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  16102. bool appendToExistingBlockContent);
  16103. /** Destructor.
  16104. This will free any data that was written to it.
  16105. */
  16106. ~MemoryOutputStream();
  16107. /** Returns a pointer to the data that has been written to the stream.
  16108. @see getDataSize
  16109. */
  16110. const void* getData() const throw();
  16111. /** Returns the number of bytes of data that have been written to the stream.
  16112. @see getData
  16113. */
  16114. size_t getDataSize() const throw() { return size; }
  16115. /** Resets the stream, clearing any data that has been written to it so far. */
  16116. void reset() throw();
  16117. /** Increases the internal storage capacity to be able to contain at least the specified
  16118. amount of data without needing to be resized.
  16119. */
  16120. void preallocate (size_t bytesToPreallocate);
  16121. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  16122. const String toUTF8() const;
  16123. /** Attempts to detect the encoding of the data and convert it to a string.
  16124. @see String::createStringFromData
  16125. */
  16126. const String toString() const;
  16127. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  16128. capacity off the block, so that its length matches the amount of actual data that
  16129. has been written so far.
  16130. */
  16131. void flush();
  16132. bool write (const void* buffer, int howMany);
  16133. int64 getPosition() { return position; }
  16134. bool setPosition (int64 newPosition);
  16135. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  16136. private:
  16137. MemoryBlock& data;
  16138. MemoryBlock internalBlock;
  16139. size_t position, size;
  16140. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  16141. };
  16142. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  16143. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  16144. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  16145. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  16146. #endif
  16147. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  16148. #endif
  16149. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16150. /*** Start of inlined file: juce_SubregionStream.h ***/
  16151. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16152. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16153. /** Wraps another input stream, and reads from a specific part of it.
  16154. This lets you take a subsection of a stream and present it as an entire
  16155. stream in its own right.
  16156. */
  16157. class JUCE_API SubregionStream : public InputStream
  16158. {
  16159. public:
  16160. /** Creates a SubregionStream from an input source.
  16161. @param sourceStream the source stream to read from
  16162. @param startPositionInSourceStream this is the position in the source stream that
  16163. corresponds to position 0 in this stream
  16164. @param lengthOfSourceStream this specifies the maximum number of bytes
  16165. from the source stream that will be passed through
  16166. by this stream. When the position of this stream
  16167. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  16168. If the length passed in here is greater than the length
  16169. of the source stream (as returned by getTotalLength()),
  16170. then the smaller value will be used.
  16171. Passing a negative value for this parameter means it
  16172. will keep reading until the source's end-of-stream.
  16173. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  16174. deleted by this object when it is itself deleted.
  16175. */
  16176. SubregionStream (InputStream* sourceStream,
  16177. int64 startPositionInSourceStream,
  16178. int64 lengthOfSourceStream,
  16179. bool deleteSourceWhenDestroyed);
  16180. /** Destructor.
  16181. This may also delete the source stream, if that option was chosen when the
  16182. buffered stream was created.
  16183. */
  16184. ~SubregionStream();
  16185. int64 getTotalLength();
  16186. int64 getPosition();
  16187. bool setPosition (int64 newPosition);
  16188. int read (void* destBuffer, int maxBytesToRead);
  16189. bool isExhausted();
  16190. private:
  16191. OptionalScopedPointer<InputStream> source;
  16192. const int64 startPositionInSourceStream, lengthOfSourceStream;
  16193. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  16194. };
  16195. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  16196. /*** End of inlined file: juce_SubregionStream.h ***/
  16197. #endif
  16198. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  16199. #endif
  16200. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16201. /*** Start of inlined file: juce_Expression.h ***/
  16202. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  16203. #define __JUCE_EXPRESSION_JUCEHEADER__
  16204. /**
  16205. A class for dynamically evaluating simple numeric expressions.
  16206. This class can parse a simple C-style string expression involving floating point
  16207. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  16208. are supported, as well as parentheses, and any alphanumeric identifiers are
  16209. assumed to be named symbols which will be resolved when the expression is
  16210. evaluated.
  16211. Expressions which use identifiers and functions require a subclass of
  16212. Expression::Scope to be supplied when evaluating them, and this object
  16213. is expected to be able to resolve the symbol names and perform the functions that
  16214. are used.
  16215. */
  16216. class JUCE_API Expression
  16217. {
  16218. public:
  16219. /** Creates a simple expression with a value of 0. */
  16220. Expression();
  16221. /** Destructor. */
  16222. ~Expression();
  16223. /** Creates a simple expression with a specified constant value. */
  16224. explicit Expression (double constant);
  16225. /** Creates a copy of an expression. */
  16226. Expression (const Expression& other);
  16227. /** Copies another expression. */
  16228. Expression& operator= (const Expression& other);
  16229. /** Creates an expression by parsing a string.
  16230. If there's a syntax error in the string, this will throw a ParseError exception.
  16231. @throws ParseError
  16232. */
  16233. explicit Expression (const String& stringToParse);
  16234. /** Returns a string version of the expression. */
  16235. const String toString() const;
  16236. /** Returns an expression which is an addtion operation of two existing expressions. */
  16237. const Expression operator+ (const Expression& other) const;
  16238. /** Returns an expression which is a subtraction operation of two existing expressions. */
  16239. const Expression operator- (const Expression& other) const;
  16240. /** Returns an expression which is a multiplication operation of two existing expressions. */
  16241. const Expression operator* (const Expression& other) const;
  16242. /** Returns an expression which is a division operation of two existing expressions. */
  16243. const Expression operator/ (const Expression& other) const;
  16244. /** Returns an expression which performs a negation operation on an existing expression. */
  16245. const Expression operator-() const;
  16246. /** Returns an Expression which is an identifier reference. */
  16247. static const Expression symbol (const String& symbol);
  16248. /** Returns an Expression which is a function call. */
  16249. static const Expression function (const String& functionName, const Array<Expression>& parameters);
  16250. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  16251. to indicate where it finished.
  16252. The pointer is incremented so that on return, it indicates the character that follows
  16253. the end of the expression that was parsed.
  16254. If there's a syntax error in the string, this will throw a ParseError exception.
  16255. @throws ParseError
  16256. */
  16257. static const Expression parse (String::CharPointerType& stringToParse);
  16258. /** When evaluating an Expression object, this class is used to resolve symbols and
  16259. perform functions that the expression uses.
  16260. */
  16261. class JUCE_API Scope
  16262. {
  16263. public:
  16264. Scope();
  16265. virtual ~Scope();
  16266. /** Returns some kind of globally unique ID that identifies this scope. */
  16267. virtual const String getScopeUID() const;
  16268. /** Returns the value of a symbol.
  16269. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  16270. The member value is set to the part of the symbol that followed the dot, if there is
  16271. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  16272. @throws Expression::EvaluationError
  16273. */
  16274. virtual const Expression getSymbolValue (const String& symbol) const;
  16275. /** Executes a named function.
  16276. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  16277. @throws Expression::EvaluationError
  16278. */
  16279. virtual double evaluateFunction (const String& functionName,
  16280. const double* parameters, int numParameters) const;
  16281. /** Used as a callback by the Scope::visitRelativeScope() method.
  16282. You should never create an instance of this class yourself, it's used by the
  16283. expression evaluation code.
  16284. */
  16285. class Visitor
  16286. {
  16287. public:
  16288. virtual ~Visitor() {}
  16289. virtual void visit (const Scope&) = 0;
  16290. };
  16291. /** Creates a Scope object for a named scope, and then calls a visitor
  16292. to do some kind of processing with this new scope.
  16293. If the name is valid, this method must create a suitable (temporary) Scope
  16294. object to represent it, and must call the Visitor::visit() method with this
  16295. new scope.
  16296. */
  16297. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  16298. };
  16299. /** Evaluates this expression, without using a Scope.
  16300. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  16301. min, max are available.
  16302. To find out about any errors during evaluation, use the other version of this method which
  16303. takes a String parameter.
  16304. */
  16305. double evaluate() const;
  16306. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16307. or functions that it uses.
  16308. To find out about any errors during evaluation, use the other version of this method which
  16309. takes a String parameter.
  16310. */
  16311. double evaluate (const Scope& scope) const;
  16312. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  16313. or functions that it uses.
  16314. */
  16315. double evaluate (const Scope& scope, String& evaluationError) const;
  16316. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  16317. to make the expression resolve to a target value.
  16318. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  16319. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  16320. case they might just be adjusted by adding a constant to the original expression.
  16321. @throws Expression::EvaluationError
  16322. */
  16323. const Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  16324. /** Represents a symbol that is used in an Expression. */
  16325. struct Symbol
  16326. {
  16327. Symbol (const String& scopeUID, const String& symbolName);
  16328. bool operator== (const Symbol&) const throw();
  16329. bool operator!= (const Symbol&) const throw();
  16330. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  16331. String symbolName; /**< The name of the symbol. */
  16332. };
  16333. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  16334. const Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  16335. /** Returns true if this expression makes use of the specified symbol.
  16336. If a suitable scope is supplied, the search will dereference and recursively check
  16337. all symbols, so that it can be determined whether this expression relies on the given
  16338. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  16339. whether the expression contains any direct references to the symbol.
  16340. @throws Expression::EvaluationError
  16341. */
  16342. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  16343. /** Returns true if this expression contains any symbols. */
  16344. bool usesAnySymbols() const;
  16345. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  16346. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  16347. /** An exception that can be thrown by Expression::parse(). */
  16348. class ParseError : public std::exception
  16349. {
  16350. public:
  16351. ParseError (const String& message);
  16352. String description;
  16353. };
  16354. /** Expression type.
  16355. @see Expression::getType()
  16356. */
  16357. enum Type
  16358. {
  16359. constantType,
  16360. functionType,
  16361. operatorType,
  16362. symbolType
  16363. };
  16364. /** Returns the type of this expression. */
  16365. Type getType() const throw();
  16366. /** If this expression is a symbol, function or operator, this returns its identifier. */
  16367. const String getSymbolOrFunction() const;
  16368. /** Returns the number of inputs to this expression.
  16369. @see getInput
  16370. */
  16371. int getNumInputs() const;
  16372. /** Retrieves one of the inputs to this expression.
  16373. @see getNumInputs
  16374. */
  16375. const Expression getInput (int index) const;
  16376. private:
  16377. class Term;
  16378. class Helpers;
  16379. friend class Term;
  16380. friend class Helpers;
  16381. friend class ScopedPointer<Term>;
  16382. friend class ReferenceCountedObjectPtr<Term>;
  16383. ReferenceCountedObjectPtr<Term> term;
  16384. explicit Expression (Term* term);
  16385. };
  16386. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  16387. /*** End of inlined file: juce_Expression.h ***/
  16388. #endif
  16389. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  16390. #endif
  16391. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16392. /*** Start of inlined file: juce_Random.h ***/
  16393. #ifndef __JUCE_RANDOM_JUCEHEADER__
  16394. #define __JUCE_RANDOM_JUCEHEADER__
  16395. /**
  16396. A random number generator.
  16397. You can create a Random object and use it to generate a sequence of random numbers.
  16398. As a handy shortcut to avoid having to create and seed one yourself, you can call
  16399. Random::getSystemRandom() to return a global RNG that is seeded randomly when the
  16400. app launches.
  16401. */
  16402. class JUCE_API Random
  16403. {
  16404. public:
  16405. /** Creates a Random object based on a seed value.
  16406. For a given seed value, the subsequent numbers generated by this object
  16407. will be predictable, so a good idea is to set this value based
  16408. on the time, e.g.
  16409. new Random (Time::currentTimeMillis())
  16410. */
  16411. explicit Random (int64 seedValue) throw();
  16412. /** Destructor. */
  16413. ~Random() throw();
  16414. /** Returns the next random 32 bit integer.
  16415. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  16416. */
  16417. int nextInt() throw();
  16418. /** Returns the next random number, limited to a given range.
  16419. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  16420. */
  16421. int nextInt (int maxValue) throw();
  16422. /** Returns the next 64-bit random number.
  16423. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  16424. */
  16425. int64 nextInt64() throw();
  16426. /** Returns the next random floating-point number.
  16427. @returns a random value in the range 0 to 1.0
  16428. */
  16429. float nextFloat() throw();
  16430. /** Returns the next random floating-point number.
  16431. @returns a random value in the range 0 to 1.0
  16432. */
  16433. double nextDouble() throw();
  16434. /** Returns the next random boolean value.
  16435. */
  16436. bool nextBool() throw();
  16437. /** Returns a BigInteger containing a random number.
  16438. @returns a random value in the range 0 to (maximumValue - 1).
  16439. */
  16440. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  16441. /** Sets a range of bits in a BigInteger to random values. */
  16442. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  16443. /** To avoid the overhead of having to create a new Random object whenever
  16444. you need a number, this is a shared application-wide object that
  16445. can be used.
  16446. It's not thread-safe though, so threads should use their own Random object.
  16447. */
  16448. static Random& getSystemRandom() throw();
  16449. /** Resets this Random object to a given seed value. */
  16450. void setSeed (int64 newSeed) throw();
  16451. /** Merges this object's seed with another value.
  16452. This sets the seed to be a value created by combining the current seed and this
  16453. new value.
  16454. */
  16455. void combineSeed (int64 seedValue) throw();
  16456. /** Reseeds this generator using a value generated from various semi-random system
  16457. properties like the current time, etc.
  16458. Because this function convolves the time with the last seed value, calling
  16459. it repeatedly will increase the randomness of the final result.
  16460. */
  16461. void setSeedRandomly();
  16462. private:
  16463. int64 seed;
  16464. JUCE_LEAK_DETECTOR (Random);
  16465. };
  16466. #endif // __JUCE_RANDOM_JUCEHEADER__
  16467. /*** End of inlined file: juce_Random.h ***/
  16468. #endif
  16469. #ifndef __JUCE_RANGE_JUCEHEADER__
  16470. #endif
  16471. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  16472. #endif
  16473. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  16474. #endif
  16475. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  16476. #endif
  16477. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  16478. #endif
  16479. #ifndef __JUCE_MEMORY_JUCEHEADER__
  16480. #endif
  16481. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  16482. #endif
  16483. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16484. #endif
  16485. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  16486. #endif
  16487. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  16488. #endif
  16489. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16490. /*** Start of inlined file: juce_WeakReference.h ***/
  16491. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16492. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  16493. /**
  16494. This class acts as a pointer which will automatically become null if the object
  16495. to which it points is deleted.
  16496. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  16497. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  16498. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  16499. E.g.
  16500. @code
  16501. class MyObject
  16502. {
  16503. public:
  16504. MyObject()
  16505. {
  16506. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  16507. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  16508. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  16509. // the first call to getWeakReference().
  16510. }
  16511. ~MyObject()
  16512. {
  16513. // This will zero all the references - you need to call this in your destructor.
  16514. masterReference.clear();
  16515. }
  16516. // Your object must provide a method that looks pretty much identical to this (except
  16517. // for the templated class name, of course).
  16518. const WeakReference<MyObject>::SharedRef& getWeakReference()
  16519. {
  16520. return masterReference (this);
  16521. }
  16522. private:
  16523. // You need to embed one of these inside your object. It can be private.
  16524. WeakReference<MyObject>::Master masterReference;
  16525. };
  16526. // Here's an example of using a pointer..
  16527. MyObject* n = new MyObject();
  16528. WeakReference<MyObject> myObjectRef = n;
  16529. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  16530. delete n;
  16531. MyObject* pointer2 = myObjectRef; // returns a null pointer
  16532. @endcode
  16533. @see WeakReference::Master
  16534. */
  16535. template <class ObjectType>
  16536. class WeakReference
  16537. {
  16538. public:
  16539. /** Creates a null SafePointer. */
  16540. WeakReference() throw() {}
  16541. /** Creates a WeakReference that points at the given object. */
  16542. WeakReference (ObjectType* const object) : holder (object != 0 ? object->getWeakReference() : 0) {}
  16543. /** Creates a copy of another WeakReference. */
  16544. WeakReference (const WeakReference& other) throw() : holder (other.holder) {}
  16545. /** Copies another pointer to this one. */
  16546. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  16547. /** Copies another pointer to this one. */
  16548. WeakReference& operator= (ObjectType* const newObject) { holder = newObject != 0 ? newObject->getWeakReference() : 0; return *this; }
  16549. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16550. ObjectType* get() const throw() { return holder != 0 ? holder->get() : 0; }
  16551. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16552. operator ObjectType*() const throw() { return get(); }
  16553. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16554. ObjectType* operator->() throw() { return get(); }
  16555. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16556. const ObjectType* operator->() const throw() { return get(); }
  16557. /** This returns true if this reference has been pointing at an object, but that object has
  16558. since been deleted.
  16559. If this reference was only ever pointing at a null pointer, this will return false. Using
  16560. operator=() to make this refer to a different object will reset this flag to match the status
  16561. of the reference from which you're copying.
  16562. */
  16563. bool wasObjectDeleted() const throw() { return holder != 0 && holder->get() == 0; }
  16564. bool operator== (ObjectType* const object) const throw() { return get() == object; }
  16565. bool operator!= (ObjectType* const object) const throw() { return get() != object; }
  16566. /** This class is used internally by the WeakReference class - don't use it directly
  16567. in your code!
  16568. @see WeakReference
  16569. */
  16570. class SharedPointer : public ReferenceCountedObject
  16571. {
  16572. public:
  16573. explicit SharedPointer (ObjectType* const owner_) throw() : owner (owner_) {}
  16574. inline ObjectType* get() const throw() { return owner; }
  16575. void clearPointer() throw() { owner = 0; }
  16576. private:
  16577. ObjectType* volatile owner;
  16578. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  16579. };
  16580. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  16581. /**
  16582. This class is embedded inside an object to which you want to attach WeakReference pointers.
  16583. See the WeakReference class notes for an example of how to use this class.
  16584. @see WeakReference
  16585. */
  16586. class Master
  16587. {
  16588. public:
  16589. Master() throw() {}
  16590. ~Master()
  16591. {
  16592. // You must remember to call clear() in your source object's destructor! See the notes
  16593. // for the WeakReference class for an example of how to do this.
  16594. jassert (sharedPointer == 0 || sharedPointer->get() == 0);
  16595. }
  16596. /** The first call to this method will create an internal object that is shared by all weak
  16597. references to the object.
  16598. You need to call this from your main object's getWeakReference() method - see the WeakReference
  16599. class notes for an example.
  16600. */
  16601. const SharedRef& operator() (ObjectType* const object)
  16602. {
  16603. if (sharedPointer == 0)
  16604. {
  16605. sharedPointer = new SharedPointer (object);
  16606. }
  16607. else
  16608. {
  16609. // You're trying to create a weak reference to an object that has already been deleted!!
  16610. jassert (sharedPointer->get() != 0);
  16611. }
  16612. return sharedPointer;
  16613. }
  16614. /** The object that owns this master pointer should call this before it gets destroyed,
  16615. to zero all the references to this object that may be out there. See the WeakReference
  16616. class notes for an example of how to do this.
  16617. */
  16618. void clear()
  16619. {
  16620. if (sharedPointer != 0)
  16621. sharedPointer->clearPointer();
  16622. }
  16623. private:
  16624. SharedRef sharedPointer;
  16625. JUCE_DECLARE_NON_COPYABLE (Master);
  16626. };
  16627. private:
  16628. SharedRef holder;
  16629. };
  16630. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  16631. /*** End of inlined file: juce_WeakReference.h ***/
  16632. #endif
  16633. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  16634. #endif
  16635. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  16636. #endif
  16637. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  16638. #endif
  16639. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  16640. #endif
  16641. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  16642. #endif
  16643. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  16644. #endif
  16645. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16646. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  16647. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16648. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16649. /** Used in the same way as the T(text) macro, this will attempt to translate a
  16650. string into a localised version using the LocalisedStrings class.
  16651. @see LocalisedStrings
  16652. */
  16653. #define TRANS(stringLiteral) \
  16654. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  16655. /**
  16656. Used to convert strings to localised foreign-language versions.
  16657. This is basically a look-up table of strings and their translated equivalents.
  16658. It can be loaded from a text file, so that you can supply a set of localised
  16659. versions of strings that you use in your app.
  16660. To use it in your code, simply call the translate() method on each string that
  16661. might have foreign versions, and if none is found, the method will just return
  16662. the original string.
  16663. The translation file should start with some lines specifying a description of
  16664. the language it contains, and also a list of ISO country codes where it might
  16665. be appropriate to use the file. After that, each line of the file should contain
  16666. a pair of quoted strings with an '=' sign.
  16667. E.g. for a french translation, the file might be:
  16668. @code
  16669. language: French
  16670. countries: fr be mc ch lu
  16671. "hello" = "bonjour"
  16672. "goodbye" = "au revoir"
  16673. @endcode
  16674. If the strings need to contain a quote character, they can use '\"' instead, and
  16675. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  16676. (you can use this to add comments).
  16677. Note that this is a singleton class, so don't create or destroy the object directly.
  16678. There's also a TRANS(text) macro defined to make it easy to use the this.
  16679. E.g. @code
  16680. printSomething (TRANS("hello"));
  16681. @endcode
  16682. This macro is used in the Juce classes themselves, so your application has a chance to
  16683. intercept and translate any internal Juce text strings that might be shown. (You can easily
  16684. get a list of all the messages by searching for the TRANS() macro in the Juce source
  16685. code).
  16686. */
  16687. class JUCE_API LocalisedStrings
  16688. {
  16689. public:
  16690. /** Creates a set of translations from the text of a translation file.
  16691. When you create one of these, you can call setCurrentMappings() to make it
  16692. the set of mappings that the system's using.
  16693. */
  16694. LocalisedStrings (const String& fileContents);
  16695. /** Creates a set of translations from a file.
  16696. When you create one of these, you can call setCurrentMappings() to make it
  16697. the set of mappings that the system's using.
  16698. */
  16699. LocalisedStrings (const File& fileToLoad);
  16700. /** Destructor. */
  16701. ~LocalisedStrings();
  16702. /** Selects the current set of mappings to be used by the system.
  16703. The object you pass in will be automatically deleted when no longer needed, so
  16704. don't keep a pointer to it. You can also pass in zero to remove the current
  16705. mappings.
  16706. See also the TRANS() macro, which uses the current set to do its translation.
  16707. @see translateWithCurrentMappings
  16708. */
  16709. static void setCurrentMappings (LocalisedStrings* newTranslations);
  16710. /** Returns the currently selected set of mappings.
  16711. This is the object that was last passed to setCurrentMappings(). It may
  16712. be 0 if none has been created.
  16713. */
  16714. static LocalisedStrings* getCurrentMappings();
  16715. /** Tries to translate a string using the currently selected set of mappings.
  16716. If no mapping has been set, or if the mapping doesn't contain a translation
  16717. for the string, this will just return the original string.
  16718. See also the TRANS() macro, which uses this method to do its translation.
  16719. @see setCurrentMappings, getCurrentMappings
  16720. */
  16721. static const String translateWithCurrentMappings (const String& text);
  16722. /** Tries to translate a string using the currently selected set of mappings.
  16723. If no mapping has been set, or if the mapping doesn't contain a translation
  16724. for the string, this will just return the original string.
  16725. See also the TRANS() macro, which uses this method to do its translation.
  16726. @see setCurrentMappings, getCurrentMappings
  16727. */
  16728. static const String translateWithCurrentMappings (const char* text);
  16729. /** Attempts to look up a string and return its localised version.
  16730. If the string isn't found in the list, the original string will be returned.
  16731. */
  16732. const String translate (const String& text) const;
  16733. /** Returns the name of the language specified in the translation file.
  16734. This is specified in the file using a line starting with "language:", e.g.
  16735. @code
  16736. language: german
  16737. @endcode
  16738. */
  16739. const String getLanguageName() const { return languageName; }
  16740. /** Returns the list of suitable country codes listed in the translation file.
  16741. These is specified in the file using a line starting with "countries:", e.g.
  16742. @code
  16743. countries: fr be mc ch lu
  16744. @endcode
  16745. The country codes are supposed to be 2-character ISO complient codes.
  16746. */
  16747. const StringArray getCountryCodes() const { return countryCodes; }
  16748. /** Indicates whether to use a case-insensitive search when looking up a string.
  16749. This defaults to true.
  16750. */
  16751. void setIgnoresCase (bool shouldIgnoreCase);
  16752. private:
  16753. String languageName;
  16754. StringArray countryCodes;
  16755. StringPairArray translations;
  16756. void loadFromText (const String& fileContents);
  16757. JUCE_LEAK_DETECTOR (LocalisedStrings);
  16758. };
  16759. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16760. /*** End of inlined file: juce_LocalisedStrings.h ***/
  16761. #endif
  16762. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  16763. #endif
  16764. #ifndef __JUCE_STRING_JUCEHEADER__
  16765. #endif
  16766. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  16767. #endif
  16768. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  16769. #endif
  16770. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  16771. #endif
  16772. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16773. /*** Start of inlined file: juce_XmlDocument.h ***/
  16774. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16775. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  16776. /**
  16777. Parses a text-based XML document and creates an XmlElement object from it.
  16778. The parser will parse DTDs to load external entities but won't
  16779. check the document for validity against the DTD.
  16780. e.g.
  16781. @code
  16782. XmlDocument myDocument (File ("myfile.xml"));
  16783. XmlElement* mainElement = myDocument.getDocumentElement();
  16784. if (mainElement == 0)
  16785. {
  16786. String error = myDocument.getLastParseError();
  16787. }
  16788. else
  16789. {
  16790. ..use the element
  16791. }
  16792. @endcode
  16793. Or you can use the static helper methods for quick parsing..
  16794. @code
  16795. XmlElement* xml = XmlDocument::parse (myXmlFile);
  16796. if (xml != 0 && xml->hasTagName ("foobar"))
  16797. {
  16798. ...etc
  16799. @endcode
  16800. @see XmlElement
  16801. */
  16802. class JUCE_API XmlDocument
  16803. {
  16804. public:
  16805. /** Creates an XmlDocument from the xml text.
  16806. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16807. */
  16808. XmlDocument (const String& documentText);
  16809. /** Creates an XmlDocument from a file.
  16810. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16811. */
  16812. XmlDocument (const File& file);
  16813. /** Destructor. */
  16814. ~XmlDocument();
  16815. /** Creates an XmlElement object to represent the main document node.
  16816. This method will do the actual parsing of the text, and if there's a
  16817. parse error, it may returns 0 (and you can find out the error using
  16818. the getLastParseError() method).
  16819. See also the parse() methods, which provide a shorthand way to quickly
  16820. parse a file or string.
  16821. @param onlyReadOuterDocumentElement if true, the parser will only read the
  16822. first section of the file, and will only
  16823. return the outer document element - this
  16824. allows quick checking of large files to
  16825. see if they contain the correct type of
  16826. tag, without having to parse the entire file
  16827. @returns a new XmlElement which the caller will need to delete, or null if
  16828. there was an error.
  16829. @see getLastParseError
  16830. */
  16831. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  16832. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  16833. @returns the error, or an empty string if there was no error.
  16834. */
  16835. const String& getLastParseError() const throw();
  16836. /** Sets an input source object to use for parsing documents that reference external entities.
  16837. If the document has been created from a file, this probably won't be needed, but
  16838. if you're parsing some text and there might be a DTD that references external
  16839. files, you may need to create a custom input source that can retrieve the
  16840. other files it needs.
  16841. The object that is passed-in will be deleted automatically when no longer needed.
  16842. @see InputSource
  16843. */
  16844. void setInputSource (InputSource* newSource) throw();
  16845. /** Sets a flag to change the treatment of empty text elements.
  16846. If this is true (the default state), then any text elements that contain only
  16847. whitespace characters will be ingored during parsing. If you need to catch
  16848. whitespace-only text, then you should set this to false before calling the
  16849. getDocumentElement() method.
  16850. */
  16851. void setEmptyTextElementsIgnored (bool shouldBeIgnored) throw();
  16852. /** A handy static method that parses a file.
  16853. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16854. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16855. */
  16856. static XmlElement* parse (const File& file);
  16857. /** A handy static method that parses some XML data.
  16858. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16859. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16860. */
  16861. static XmlElement* parse (const String& xmlData);
  16862. private:
  16863. String originalText;
  16864. String::CharPointerType input;
  16865. bool outOfData, errorOccurred;
  16866. String lastError, dtdText;
  16867. StringArray tokenisedDTD;
  16868. bool needToLoadDTD, ignoreEmptyTextElements;
  16869. ScopedPointer <InputSource> inputSource;
  16870. void setLastError (const String& desc, bool carryOn);
  16871. void skipHeader();
  16872. void skipNextWhiteSpace();
  16873. juce_wchar readNextChar() throw();
  16874. XmlElement* readNextElement (bool alsoParseSubElements);
  16875. void readChildElements (XmlElement* parent);
  16876. int findNextTokenLength() throw();
  16877. void readQuotedString (String& result);
  16878. void readEntity (String& result);
  16879. const String getFileContents (const String& filename) const;
  16880. const String expandEntity (const String& entity);
  16881. const String expandExternalEntity (const String& entity);
  16882. const String getParameterEntity (const String& entity);
  16883. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  16884. };
  16885. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  16886. /*** End of inlined file: juce_XmlDocument.h ***/
  16887. #endif
  16888. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  16889. #endif
  16890. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  16891. #endif
  16892. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16893. /*** Start of inlined file: juce_InterProcessLock.h ***/
  16894. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16895. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16896. /**
  16897. Acts as a critical section which processes can use to block each other.
  16898. @see CriticalSection
  16899. */
  16900. class JUCE_API InterProcessLock
  16901. {
  16902. public:
  16903. /** Creates a lock object.
  16904. @param name a name that processes will use to identify this lock object
  16905. */
  16906. explicit InterProcessLock (const String& name);
  16907. /** Destructor.
  16908. This will also release the lock if it's currently held by this process.
  16909. */
  16910. ~InterProcessLock();
  16911. /** Attempts to lock the critical section.
  16912. @param timeOutMillisecs how many milliseconds to wait if the lock
  16913. is already held by another process - a value of
  16914. 0 will return immediately, negative values will wait
  16915. forever
  16916. @returns true if the lock could be gained within the timeout period, or
  16917. false if the timeout expired.
  16918. */
  16919. bool enter (int timeOutMillisecs = -1);
  16920. /** Releases the lock if it's currently held by this process.
  16921. */
  16922. void exit();
  16923. /**
  16924. Automatically locks and unlocks an InterProcessLock object.
  16925. This works like a ScopedLock, but using an InterprocessLock rather than
  16926. a CriticalSection.
  16927. @see ScopedLock
  16928. */
  16929. class ScopedLockType
  16930. {
  16931. public:
  16932. /** Creates a scoped lock.
  16933. As soon as it is created, this will lock the InterProcessLock, and
  16934. when the ScopedLockType object is deleted, the InterProcessLock will
  16935. be unlocked.
  16936. Note that since an InterprocessLock can fail due to errors, you should check
  16937. isLocked() to make sure that the lock was successful before using it.
  16938. Make sure this object is created and deleted by the same thread,
  16939. otherwise there are no guarantees what will happen! Best just to use it
  16940. as a local stack object, rather than creating one with the new() operator.
  16941. */
  16942. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  16943. /** Destructor.
  16944. The InterProcessLock will be unlocked when the destructor is called.
  16945. Make sure this object is created and deleted by the same thread,
  16946. otherwise there are no guarantees what will happen!
  16947. */
  16948. inline ~ScopedLockType() { lock_.exit(); }
  16949. /** Returns true if the InterProcessLock was successfully locked. */
  16950. bool isLocked() const throw() { return lockWasSuccessful; }
  16951. private:
  16952. InterProcessLock& lock_;
  16953. bool lockWasSuccessful;
  16954. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  16955. };
  16956. private:
  16957. class Pimpl;
  16958. friend class ScopedPointer <Pimpl>;
  16959. ScopedPointer <Pimpl> pimpl;
  16960. CriticalSection lock;
  16961. String name;
  16962. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  16963. };
  16964. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16965. /*** End of inlined file: juce_InterProcessLock.h ***/
  16966. #endif
  16967. #ifndef __JUCE_PROCESS_JUCEHEADER__
  16968. /*** Start of inlined file: juce_Process.h ***/
  16969. #ifndef __JUCE_PROCESS_JUCEHEADER__
  16970. #define __JUCE_PROCESS_JUCEHEADER__
  16971. /** Represents the current executable's process.
  16972. This contains methods for controlling the current application at the
  16973. process-level.
  16974. @see Thread, JUCEApplication
  16975. */
  16976. class JUCE_API Process
  16977. {
  16978. public:
  16979. enum ProcessPriority
  16980. {
  16981. LowPriority = 0,
  16982. NormalPriority = 1,
  16983. HighPriority = 2,
  16984. RealtimePriority = 3
  16985. };
  16986. /** Changes the current process's priority.
  16987. @param priority the process priority, where
  16988. 0=low, 1=normal, 2=high, 3=realtime
  16989. */
  16990. static void setPriority (const ProcessPriority priority);
  16991. /** Kills the current process immediately.
  16992. This is an emergency process terminator that kills the application
  16993. immediately - it's intended only for use only when something goes
  16994. horribly wrong.
  16995. @see JUCEApplication::quit
  16996. */
  16997. static void terminate();
  16998. /** Returns true if this application process is the one that the user is
  16999. currently using.
  17000. */
  17001. static bool isForegroundProcess();
  17002. /** Raises the current process's privilege level.
  17003. Does nothing if this isn't supported by the current OS, or if process
  17004. privilege level is fixed.
  17005. */
  17006. static void raisePrivilege();
  17007. /** Lowers the current process's privilege level.
  17008. Does nothing if this isn't supported by the current OS, or if process
  17009. privilege level is fixed.
  17010. */
  17011. static void lowerPrivilege();
  17012. /** Returns true if this process is being hosted by a debugger.
  17013. */
  17014. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  17015. private:
  17016. Process();
  17017. JUCE_DECLARE_NON_COPYABLE (Process);
  17018. };
  17019. #endif // __JUCE_PROCESS_JUCEHEADER__
  17020. /*** End of inlined file: juce_Process.h ***/
  17021. #endif
  17022. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17023. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  17024. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  17025. #define __JUCE_READWRITELOCK_JUCEHEADER__
  17026. /*** Start of inlined file: juce_SpinLock.h ***/
  17027. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17028. #define __JUCE_SPINLOCK_JUCEHEADER__
  17029. /**
  17030. A simple spin-lock class that can be used as a simple, low-overhead mutex for
  17031. uncontended situations.
  17032. Note that unlike a CriticalSection, this type of lock is not re-entrant, and may
  17033. be less efficient when used it a highly contended situation, but it's very small and
  17034. requires almost no initialisation.
  17035. It's most appropriate for simple situations where you're only going to hold the
  17036. lock for a very brief time.
  17037. @see CriticalSection
  17038. */
  17039. class JUCE_API SpinLock
  17040. {
  17041. public:
  17042. inline SpinLock() throw() {}
  17043. inline ~SpinLock() throw() {}
  17044. /** Acquires the lock.
  17045. This will block until the lock has been successfully acquired by this thread.
  17046. Note that a SpinLock is NOT re-entrant, and is not smart enough to know whether the
  17047. caller thread already has the lock - so if a thread tries to acquire a lock that it
  17048. already holds, this method will never return!
  17049. It's strongly recommended that you never call this method directly - instead use the
  17050. ScopedLockType class to manage the locking using an RAII pattern instead.
  17051. */
  17052. void enter() const throw();
  17053. /** Attempts to acquire the lock, returning true if this was successful. */
  17054. bool tryEnter() const throw();
  17055. /** Releases the lock. */
  17056. inline void exit() const throw()
  17057. {
  17058. jassert (lock.value == 1); // Agh! Releasing a lock that isn't currently held!
  17059. lock = 0;
  17060. }
  17061. /** Provides the type of scoped lock to use for locking a SpinLock. */
  17062. typedef GenericScopedLock <SpinLock> ScopedLockType;
  17063. /** Provides the type of scoped unlocker to use with a SpinLock. */
  17064. typedef GenericScopedUnlock <SpinLock> ScopedUnlockType;
  17065. private:
  17066. mutable Atomic<int> lock;
  17067. JUCE_DECLARE_NON_COPYABLE (SpinLock);
  17068. };
  17069. #endif // __JUCE_SPINLOCK_JUCEHEADER__
  17070. /*** End of inlined file: juce_SpinLock.h ***/
  17071. /*** Start of inlined file: juce_WaitableEvent.h ***/
  17072. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17073. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  17074. /**
  17075. Allows threads to wait for events triggered by other threads.
  17076. A thread can call wait() on a WaitableObject, and this will suspend the
  17077. calling thread until another thread wakes it up by calling the signal()
  17078. method.
  17079. */
  17080. class JUCE_API WaitableEvent
  17081. {
  17082. public:
  17083. /** Creates a WaitableEvent object.
  17084. @param manualReset If this is false, the event will be reset automatically when the wait()
  17085. method is called. If manualReset is true, then once the event is signalled,
  17086. the only way to reset it will be by calling the reset() method.
  17087. */
  17088. WaitableEvent (bool manualReset = false) throw();
  17089. /** Destructor.
  17090. If other threads are waiting on this object when it gets deleted, this
  17091. can cause nasty errors, so be careful!
  17092. */
  17093. ~WaitableEvent() throw();
  17094. /** Suspends the calling thread until the event has been signalled.
  17095. This will wait until the object's signal() method is called by another thread,
  17096. or until the timeout expires.
  17097. After the event has been signalled, this method will return true and if manualReset
  17098. was set to false in the WaitableEvent's constructor, then the event will be reset.
  17099. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  17100. value will cause it to wait forever.
  17101. @returns true if the object has been signalled, false if the timeout expires first.
  17102. @see signal, reset
  17103. */
  17104. bool wait (int timeOutMilliseconds = -1) const throw();
  17105. /** Wakes up any threads that are currently waiting on this object.
  17106. If signal() is called when nothing is waiting, the next thread to call wait()
  17107. will return immediately and reset the signal.
  17108. @see wait, reset
  17109. */
  17110. void signal() const throw();
  17111. /** Resets the event to an unsignalled state.
  17112. If it's not already signalled, this does nothing.
  17113. */
  17114. void reset() const throw();
  17115. private:
  17116. void* internal;
  17117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  17118. };
  17119. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  17120. /*** End of inlined file: juce_WaitableEvent.h ***/
  17121. /*** Start of inlined file: juce_Thread.h ***/
  17122. #ifndef __JUCE_THREAD_JUCEHEADER__
  17123. #define __JUCE_THREAD_JUCEHEADER__
  17124. /**
  17125. Encapsulates a thread.
  17126. Subclasses derive from Thread and implement the run() method, in which they
  17127. do their business. The thread can then be started with the startThread() method
  17128. and controlled with various other methods.
  17129. This class also contains some thread-related static methods, such
  17130. as sleep(), yield(), getCurrentThreadId() etc.
  17131. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  17132. MessageManagerLock
  17133. */
  17134. class JUCE_API Thread
  17135. {
  17136. public:
  17137. /**
  17138. Creates a thread.
  17139. When first created, the thread is not running. Use the startThread()
  17140. method to start it.
  17141. */
  17142. explicit Thread (const String& threadName);
  17143. /** Destructor.
  17144. Deleting a Thread object that is running will only give the thread a
  17145. brief opportunity to stop itself cleanly, so it's recommended that you
  17146. should always call stopThread() with a decent timeout before deleting,
  17147. to avoid the thread being forcibly killed (which is a Bad Thing).
  17148. */
  17149. virtual ~Thread();
  17150. /** Must be implemented to perform the thread's actual code.
  17151. Remember that the thread must regularly check the threadShouldExit()
  17152. method whilst running, and if this returns true it should return from
  17153. the run() method as soon as possible to avoid being forcibly killed.
  17154. @see threadShouldExit, startThread
  17155. */
  17156. virtual void run() = 0;
  17157. // Thread control functions..
  17158. /** Starts the thread running.
  17159. This will start the thread's run() method.
  17160. (if it's already started, startThread() won't do anything).
  17161. @see stopThread
  17162. */
  17163. void startThread();
  17164. /** Starts the thread with a given priority.
  17165. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  17166. If the thread is already running, its priority will be changed.
  17167. @see startThread, setPriority
  17168. */
  17169. void startThread (int priority);
  17170. /** Attempts to stop the thread running.
  17171. This method will cause the threadShouldExit() method to return true
  17172. and call notify() in case the thread is currently waiting.
  17173. Hopefully the thread will then respond to this by exiting cleanly, and
  17174. the stopThread method will wait for a given time-period for this to
  17175. happen.
  17176. If the thread is stuck and fails to respond after the time-out, it gets
  17177. forcibly killed, which is a very bad thing to happen, as it could still
  17178. be holding locks, etc. which are needed by other parts of your program.
  17179. @param timeOutMilliseconds The number of milliseconds to wait for the
  17180. thread to finish before killing it by force. A negative
  17181. value in here will wait forever.
  17182. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  17183. */
  17184. void stopThread (int timeOutMilliseconds);
  17185. /** Returns true if the thread is currently active */
  17186. bool isThreadRunning() const;
  17187. /** Sets a flag to tell the thread it should stop.
  17188. Calling this means that the threadShouldExit() method will then return true.
  17189. The thread should be regularly checking this to see whether it should exit.
  17190. If your thread makes use of wait(), you might want to call notify() after calling
  17191. this method, to interrupt any waits that might be in progress, and allow it
  17192. to reach a point where it can exit.
  17193. @see threadShouldExit
  17194. @see waitForThreadToExit
  17195. */
  17196. void signalThreadShouldExit();
  17197. /** Checks whether the thread has been told to stop running.
  17198. Threads need to check this regularly, and if it returns true, they should
  17199. return from their run() method at the first possible opportunity.
  17200. @see signalThreadShouldExit
  17201. */
  17202. inline bool threadShouldExit() const { return threadShouldExit_; }
  17203. /** Waits for the thread to stop.
  17204. This will waits until isThreadRunning() is false or until a timeout expires.
  17205. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  17206. is less than zero, it will wait forever.
  17207. @returns true if the thread exits, or false if the timeout expires first.
  17208. */
  17209. bool waitForThreadToExit (int timeOutMilliseconds) const;
  17210. /** Changes the thread's priority.
  17211. May return false if for some reason the priority can't be changed.
  17212. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  17213. of 5 is normal.
  17214. */
  17215. bool setPriority (int priority);
  17216. /** Changes the priority of the caller thread.
  17217. Similar to setPriority(), but this static method acts on the caller thread.
  17218. May return false if for some reason the priority can't be changed.
  17219. @see setPriority
  17220. */
  17221. static bool setCurrentThreadPriority (int priority);
  17222. /** Sets the affinity mask for the thread.
  17223. This will only have an effect next time the thread is started - i.e. if the
  17224. thread is already running when called, it'll have no effect.
  17225. @see setCurrentThreadAffinityMask
  17226. */
  17227. void setAffinityMask (uint32 affinityMask);
  17228. /** Changes the affinity mask for the caller thread.
  17229. This will change the affinity mask for the thread that calls this static method.
  17230. @see setAffinityMask
  17231. */
  17232. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  17233. // this can be called from any thread that needs to pause..
  17234. static void JUCE_CALLTYPE sleep (int milliseconds);
  17235. /** Yields the calling thread's current time-slot. */
  17236. static void JUCE_CALLTYPE yield();
  17237. /** Makes the thread wait for a notification.
  17238. This puts the thread to sleep until either the timeout period expires, or
  17239. another thread calls the notify() method to wake it up.
  17240. A negative time-out value means that the method will wait indefinitely.
  17241. @returns true if the event has been signalled, false if the timeout expires.
  17242. */
  17243. bool wait (int timeOutMilliseconds) const;
  17244. /** Wakes up the thread.
  17245. If the thread has called the wait() method, this will wake it up.
  17246. @see wait
  17247. */
  17248. void notify() const;
  17249. /** A value type used for thread IDs.
  17250. @see getCurrentThreadId(), getThreadId()
  17251. */
  17252. typedef void* ThreadID;
  17253. /** Returns an id that identifies the caller thread.
  17254. To find the ID of a particular thread object, use getThreadId().
  17255. @returns a unique identifier that identifies the calling thread.
  17256. @see getThreadId
  17257. */
  17258. static ThreadID getCurrentThreadId();
  17259. /** Finds the thread object that is currently running.
  17260. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  17261. object associated with them, so this will return 0.
  17262. */
  17263. static Thread* getCurrentThread();
  17264. /** Returns the ID of this thread.
  17265. That means the ID of this thread object - not of the thread that's calling the method.
  17266. This can change when the thread is started and stopped, and will be invalid if the
  17267. thread's not actually running.
  17268. @see getCurrentThreadId
  17269. */
  17270. ThreadID getThreadId() const throw() { return threadId_; }
  17271. /** Returns the name of the thread.
  17272. This is the name that gets set in the constructor.
  17273. */
  17274. const String getThreadName() const { return threadName_; }
  17275. /** Returns the number of currently-running threads.
  17276. @returns the number of Thread objects known to be currently running.
  17277. @see stopAllThreads
  17278. */
  17279. static int getNumRunningThreads();
  17280. /** Tries to stop all currently-running threads.
  17281. This will attempt to stop all the threads known to be running at the moment.
  17282. */
  17283. static void stopAllThreads (int timeoutInMillisecs);
  17284. private:
  17285. const String threadName_;
  17286. void* volatile threadHandle_;
  17287. ThreadID threadId_;
  17288. CriticalSection startStopLock;
  17289. WaitableEvent startSuspensionEvent_, defaultEvent_;
  17290. int threadPriority_;
  17291. uint32 affinityMask_;
  17292. bool volatile threadShouldExit_;
  17293. #ifndef DOXYGEN
  17294. friend class MessageManager;
  17295. friend void JUCE_API juce_threadEntryPoint (void*);
  17296. #endif
  17297. void launchThread();
  17298. void closeThreadHandle();
  17299. void killThread();
  17300. void threadEntryPoint();
  17301. static void setCurrentThreadName (const String& name);
  17302. static bool setThreadPriority (void* handle, int priority);
  17303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  17304. };
  17305. #endif // __JUCE_THREAD_JUCEHEADER__
  17306. /*** End of inlined file: juce_Thread.h ***/
  17307. /**
  17308. A critical section that allows multiple simultaneous readers.
  17309. Features of this type of lock are:
  17310. - Multiple readers can hold the lock at the same time, but only one writer
  17311. can hold it at once.
  17312. - Writers trying to gain the lock will be blocked until all readers and writers
  17313. have released it
  17314. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  17315. blocked until the writer has obtained and released it
  17316. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  17317. there are no other readers
  17318. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  17319. - Recursive locking is supported.
  17320. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  17321. */
  17322. class JUCE_API ReadWriteLock
  17323. {
  17324. public:
  17325. /**
  17326. Creates a ReadWriteLock object.
  17327. */
  17328. ReadWriteLock() throw();
  17329. /** Destructor.
  17330. If the object is deleted whilst locked, any subsequent behaviour
  17331. is unpredictable.
  17332. */
  17333. ~ReadWriteLock() throw();
  17334. /** Locks this object for reading.
  17335. Multiple threads can simulaneously lock the object for reading, but if another
  17336. thread has it locked for writing, then this will block until it releases the
  17337. lock.
  17338. @see exitRead, ScopedReadLock
  17339. */
  17340. void enterRead() const throw();
  17341. /** Releases the read-lock.
  17342. If the caller thread hasn't got the lock, this can have unpredictable results.
  17343. If the enterRead() method has been called multiple times by the thread, each
  17344. call must be matched by a call to exitRead() before other threads will be allowed
  17345. to take over the lock.
  17346. @see enterRead, ScopedReadLock
  17347. */
  17348. void exitRead() const throw();
  17349. /** Locks this object for writing.
  17350. This will block until any other threads that have it locked for reading or
  17351. writing have released their lock.
  17352. @see exitWrite, ScopedWriteLock
  17353. */
  17354. void enterWrite() const throw();
  17355. /** Tries to lock this object for writing.
  17356. This is like enterWrite(), but doesn't block - it returns true if it manages
  17357. to obtain the lock.
  17358. @see enterWrite
  17359. */
  17360. bool tryEnterWrite() const throw();
  17361. /** Releases the write-lock.
  17362. If the caller thread hasn't got the lock, this can have unpredictable results.
  17363. If the enterWrite() method has been called multiple times by the thread, each
  17364. call must be matched by a call to exit() before other threads will be allowed
  17365. to take over the lock.
  17366. @see enterWrite, ScopedWriteLock
  17367. */
  17368. void exitWrite() const throw();
  17369. private:
  17370. SpinLock accessLock;
  17371. WaitableEvent waitEvent;
  17372. mutable int numWaitingWriters, numWriters;
  17373. mutable Thread::ThreadID writerThreadId;
  17374. mutable Array <Thread::ThreadID> readerThreads;
  17375. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  17376. };
  17377. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  17378. /*** End of inlined file: juce_ReadWriteLock.h ***/
  17379. #endif
  17380. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  17381. #endif
  17382. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17383. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  17384. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17385. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17386. /**
  17387. Automatically locks and unlocks a ReadWriteLock object.
  17388. Use one of these as a local variable to control access to a ReadWriteLock.
  17389. e.g. @code
  17390. ReadWriteLock myLock;
  17391. for (;;)
  17392. {
  17393. const ScopedReadLock myScopedLock (myLock);
  17394. // myLock is now locked
  17395. ...do some stuff...
  17396. // myLock gets unlocked here.
  17397. }
  17398. @endcode
  17399. @see ReadWriteLock, ScopedWriteLock
  17400. */
  17401. class JUCE_API ScopedReadLock
  17402. {
  17403. public:
  17404. /** Creates a ScopedReadLock.
  17405. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  17406. when the ScopedReadLock object is deleted, the ReadWriteLock will
  17407. be unlocked.
  17408. Make sure this object is created and deleted by the same thread,
  17409. otherwise there are no guarantees what will happen! Best just to use it
  17410. as a local stack object, rather than creating one with the new() operator.
  17411. */
  17412. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  17413. /** Destructor.
  17414. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  17415. Make sure this object is created and deleted by the same thread,
  17416. otherwise there are no guarantees what will happen!
  17417. */
  17418. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  17419. private:
  17420. const ReadWriteLock& lock_;
  17421. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  17422. };
  17423. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  17424. /*** End of inlined file: juce_ScopedReadLock.h ***/
  17425. #endif
  17426. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17427. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  17428. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17429. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17430. /**
  17431. Automatically locks and unlocks a ReadWriteLock object.
  17432. Use one of these as a local variable to control access to a ReadWriteLock.
  17433. e.g. @code
  17434. ReadWriteLock myLock;
  17435. for (;;)
  17436. {
  17437. const ScopedWriteLock myScopedLock (myLock);
  17438. // myLock is now locked
  17439. ...do some stuff...
  17440. // myLock gets unlocked here.
  17441. }
  17442. @endcode
  17443. @see ReadWriteLock, ScopedReadLock
  17444. */
  17445. class JUCE_API ScopedWriteLock
  17446. {
  17447. public:
  17448. /** Creates a ScopedWriteLock.
  17449. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  17450. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  17451. be unlocked.
  17452. Make sure this object is created and deleted by the same thread,
  17453. otherwise there are no guarantees what will happen! Best just to use it
  17454. as a local stack object, rather than creating one with the new() operator.
  17455. */
  17456. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  17457. /** Destructor.
  17458. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  17459. Make sure this object is created and deleted by the same thread,
  17460. otherwise there are no guarantees what will happen!
  17461. */
  17462. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  17463. private:
  17464. const ReadWriteLock& lock_;
  17465. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  17466. };
  17467. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17468. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  17469. #endif
  17470. #ifndef __JUCE_SPINLOCK_JUCEHEADER__
  17471. #endif
  17472. #ifndef __JUCE_THREAD_JUCEHEADER__
  17473. #endif
  17474. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17475. /*** Start of inlined file: juce_ThreadPool.h ***/
  17476. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17477. #define __JUCE_THREADPOOL_JUCEHEADER__
  17478. class ThreadPool;
  17479. class ThreadPoolThread;
  17480. /**
  17481. A task that is executed by a ThreadPool object.
  17482. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  17483. its threads.
  17484. The runJob() method needs to be implemented to do the task, and if the code that
  17485. does the work takes a significant time to run, it must keep checking the shouldExit()
  17486. method to see if something is trying to interrupt the job. If shouldExit() returns
  17487. true, the runJob() method must return immediately.
  17488. @see ThreadPool, Thread
  17489. */
  17490. class JUCE_API ThreadPoolJob
  17491. {
  17492. public:
  17493. /** Creates a thread pool job object.
  17494. After creating your job, add it to a thread pool with ThreadPool::addJob().
  17495. */
  17496. explicit ThreadPoolJob (const String& name);
  17497. /** Destructor. */
  17498. virtual ~ThreadPoolJob();
  17499. /** Returns the name of this job.
  17500. @see setJobName
  17501. */
  17502. const String getJobName() const;
  17503. /** Changes the job's name.
  17504. @see getJobName
  17505. */
  17506. void setJobName (const String& newName);
  17507. /** These are the values that can be returned by the runJob() method.
  17508. */
  17509. enum JobStatus
  17510. {
  17511. jobHasFinished = 0, /**< indicates that the job has finished and can be
  17512. removed from the pool. */
  17513. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  17514. should be automatically deleted by the pool. */
  17515. jobNeedsRunningAgain /**< indicates that the job would like to be called
  17516. again when a thread is free. */
  17517. };
  17518. /** Peforms the actual work that this job needs to do.
  17519. Your subclass must implement this method, in which is does its work.
  17520. If the code in this method takes a significant time to run, it must repeatedly check
  17521. the shouldExit() method to see if something is trying to interrupt the job.
  17522. If shouldExit() ever returns true, the runJob() method must return immediately.
  17523. If this method returns jobHasFinished, then the job will be removed from the pool
  17524. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  17525. pool and will get a chance to run again as soon as a thread is free.
  17526. @see shouldExit()
  17527. */
  17528. virtual JobStatus runJob() = 0;
  17529. /** Returns true if this job is currently running its runJob() method. */
  17530. bool isRunning() const { return isActive; }
  17531. /** Returns true if something is trying to interrupt this job and make it stop.
  17532. Your runJob() method must call this whenever it gets a chance, and if it ever
  17533. returns true, the runJob() method must return immediately.
  17534. @see signalJobShouldExit()
  17535. */
  17536. bool shouldExit() const { return shouldStop; }
  17537. /** Calling this will cause the shouldExit() method to return true, and the job
  17538. should (if it's been implemented correctly) stop as soon as possible.
  17539. @see shouldExit()
  17540. */
  17541. void signalJobShouldExit();
  17542. private:
  17543. friend class ThreadPool;
  17544. friend class ThreadPoolThread;
  17545. String jobName;
  17546. ThreadPool* pool;
  17547. bool shouldStop, isActive, shouldBeDeleted;
  17548. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  17549. };
  17550. /**
  17551. A set of threads that will run a list of jobs.
  17552. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  17553. will be called by the next pooled thread that becomes free.
  17554. @see ThreadPoolJob, Thread
  17555. */
  17556. class JUCE_API ThreadPool
  17557. {
  17558. public:
  17559. /** Creates a thread pool.
  17560. Once you've created a pool, you can give it some things to do with the addJob()
  17561. method.
  17562. @param numberOfThreads the maximum number of actual threads to run.
  17563. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  17564. until there are some jobs to run. If false, then
  17565. all the threads will be fired-up immediately so that
  17566. they're ready for action
  17567. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  17568. inactive for this length of time, they will automatically
  17569. be stopped until more jobs come along and they're needed
  17570. */
  17571. ThreadPool (int numberOfThreads,
  17572. bool startThreadsOnlyWhenNeeded = true,
  17573. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  17574. /** Destructor.
  17575. This will attempt to remove all the jobs before deleting, but if you want to
  17576. specify a timeout, you should call removeAllJobs() explicitly before deleting
  17577. the pool.
  17578. */
  17579. ~ThreadPool();
  17580. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  17581. for some kind of operation.
  17582. @see ThreadPool::removeAllJobs
  17583. */
  17584. class JUCE_API JobSelector
  17585. {
  17586. public:
  17587. virtual ~JobSelector() {}
  17588. /** Should return true if the specified thread matches your criteria for whatever
  17589. operation that this object is being used for.
  17590. Any implementation of this method must be extremely fast and thread-safe!
  17591. */
  17592. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  17593. };
  17594. /** Adds a job to the queue.
  17595. Once a job has been added, then the next time a thread is free, it will run
  17596. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  17597. runJob() method, the pool will either remove the job from the pool or add it to
  17598. the back of the queue to be run again.
  17599. */
  17600. void addJob (ThreadPoolJob* job);
  17601. /** Tries to remove a job from the pool.
  17602. If the job isn't yet running, this will simply remove it. If it is running, it
  17603. will wait for it to finish.
  17604. If the timeout period expires before the job finishes running, then the job will be
  17605. left in the pool and this will return false. It returns true if the job is sucessfully
  17606. stopped and removed.
  17607. @param job the job to remove
  17608. @param interruptIfRunning if true, then if the job is currently busy, its
  17609. ThreadPoolJob::signalJobShouldExit() method will be called to try
  17610. to interrupt it. If false, then if the job will be allowed to run
  17611. until it stops normally (or the timeout expires)
  17612. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  17613. before giving up and returning false
  17614. */
  17615. bool removeJob (ThreadPoolJob* job,
  17616. bool interruptIfRunning,
  17617. int timeOutMilliseconds);
  17618. /** Tries to remove all jobs from the pool.
  17619. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  17620. methods called to try to interrupt them
  17621. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  17622. before giving up and returning false
  17623. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  17624. they will simply be removed from the pool. Jobs that are already running when
  17625. this method is called can choose whether they should be deleted by
  17626. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  17627. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  17628. jobs should be removed. If it is zero, all jobs are removed
  17629. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  17630. expires while waiting for one or more jobs to stop
  17631. */
  17632. bool removeAllJobs (bool interruptRunningJobs,
  17633. int timeOutMilliseconds,
  17634. bool deleteInactiveJobs = false,
  17635. JobSelector* selectedJobsToRemove = 0);
  17636. /** Returns the number of jobs currently running or queued.
  17637. */
  17638. int getNumJobs() const;
  17639. /** Returns one of the jobs in the queue.
  17640. Note that this can be a very volatile list as jobs might be continuously getting shifted
  17641. around in the list, and this method may return 0 if the index is currently out-of-range.
  17642. */
  17643. ThreadPoolJob* getJob (int index) const;
  17644. /** Returns true if the given job is currently queued or running.
  17645. @see isJobRunning()
  17646. */
  17647. bool contains (const ThreadPoolJob* job) const;
  17648. /** Returns true if the given job is currently being run by a thread.
  17649. */
  17650. bool isJobRunning (const ThreadPoolJob* job) const;
  17651. /** Waits until a job has finished running and has been removed from the pool.
  17652. This will wait until the job is no longer in the pool - i.e. until its
  17653. runJob() method returns ThreadPoolJob::jobHasFinished.
  17654. If the timeout period expires before the job finishes, this will return false;
  17655. it returns true if the job has finished successfully.
  17656. */
  17657. bool waitForJobToFinish (const ThreadPoolJob* job,
  17658. int timeOutMilliseconds) const;
  17659. /** Returns a list of the names of all the jobs currently running or queued.
  17660. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  17661. */
  17662. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  17663. /** Changes the priority of all the threads.
  17664. This will call Thread::setPriority() for each thread in the pool.
  17665. May return false if for some reason the priority can't be changed.
  17666. */
  17667. bool setThreadPriorities (int newPriority);
  17668. private:
  17669. const int threadStopTimeout;
  17670. int priority;
  17671. class ThreadPoolThread;
  17672. friend class OwnedArray <ThreadPoolThread>;
  17673. OwnedArray <ThreadPoolThread> threads;
  17674. Array <ThreadPoolJob*> jobs;
  17675. CriticalSection lock;
  17676. uint32 lastJobEndTime;
  17677. WaitableEvent jobFinishedSignal;
  17678. friend class ThreadPoolThread;
  17679. bool runNextJob();
  17680. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  17681. };
  17682. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  17683. /*** End of inlined file: juce_ThreadPool.h ***/
  17684. #endif
  17685. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17686. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  17687. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17688. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17689. class TimeSliceThread;
  17690. /**
  17691. Used by the TimeSliceThread class.
  17692. To register your class with a TimeSliceThread, derive from this class and
  17693. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  17694. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  17695. deleting your client!
  17696. @see TimeSliceThread
  17697. */
  17698. class JUCE_API TimeSliceClient
  17699. {
  17700. public:
  17701. /** Destructor. */
  17702. virtual ~TimeSliceClient() {}
  17703. /** Called back by a TimeSliceThread.
  17704. When you register this class with it, a TimeSliceThread will repeatedly call
  17705. this method.
  17706. The implementation of this method should use its time-slice to do something that's
  17707. quick - never block for longer than absolutely necessary.
  17708. @returns Your method should return the number of milliseconds which it would like to wait before being called
  17709. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  17710. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  17711. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  17712. thread - the actual time before the next callback may be more or less than specified.
  17713. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  17714. */
  17715. virtual int useTimeSlice() = 0;
  17716. private:
  17717. friend class TimeSliceThread;
  17718. Time nextCallTime;
  17719. };
  17720. /**
  17721. A thread that keeps a list of clients, and calls each one in turn, giving them
  17722. all a chance to run some sort of short task.
  17723. @see TimeSliceClient, Thread
  17724. */
  17725. class JUCE_API TimeSliceThread : public Thread
  17726. {
  17727. public:
  17728. /**
  17729. Creates a TimeSliceThread.
  17730. When first created, the thread is not running. Use the startThread()
  17731. method to start it.
  17732. */
  17733. explicit TimeSliceThread (const String& threadName);
  17734. /** Destructor.
  17735. Deleting a Thread object that is running will only give the thread a
  17736. brief opportunity to stop itself cleanly, so it's recommended that you
  17737. should always call stopThread() with a decent timeout before deleting,
  17738. to avoid the thread being forcibly killed (which is a Bad Thing).
  17739. */
  17740. ~TimeSliceThread();
  17741. /** Adds a client to the list.
  17742. The client's callbacks will start after the number of milliseconds specified
  17743. by millisecondsBeforeStarting (and this may happen before this method has returned).
  17744. */
  17745. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  17746. /** Removes a client from the list.
  17747. This method will make sure that all callbacks to the client have completely
  17748. finished before the method returns.
  17749. */
  17750. void removeTimeSliceClient (TimeSliceClient* client);
  17751. /** Returns the number of registered clients. */
  17752. int getNumClients() const;
  17753. /** Returns one of the registered clients. */
  17754. TimeSliceClient* getClient (int index) const;
  17755. /** @internal */
  17756. void run();
  17757. private:
  17758. CriticalSection callbackLock, listLock;
  17759. Array <TimeSliceClient*> clients;
  17760. TimeSliceClient* clientBeingCalled;
  17761. TimeSliceClient* getNextClient (int index) const;
  17762. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  17763. };
  17764. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17765. /*** End of inlined file: juce_TimeSliceThread.h ***/
  17766. #endif
  17767. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17768. #endif
  17769. #endif
  17770. /*** End of inlined file: juce_core_includes.h ***/
  17771. // if you're compiling a command-line app, you might want to just include the core headers,
  17772. // so you can set this macro before including juce.h
  17773. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  17774. /*** Start of inlined file: juce_app_includes.h ***/
  17775. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17776. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17777. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17778. /*** Start of inlined file: juce_Application.h ***/
  17779. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17780. #define __JUCE_APPLICATION_JUCEHEADER__
  17781. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  17782. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17783. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17784. /*** Start of inlined file: juce_Component.h ***/
  17785. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  17786. #define __JUCE_COMPONENT_JUCEHEADER__
  17787. /*** Start of inlined file: juce_MouseCursor.h ***/
  17788. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  17789. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  17790. class Image;
  17791. class ComponentPeer;
  17792. class Component;
  17793. /**
  17794. Represents a mouse cursor image.
  17795. This object can either be used to represent one of the standard mouse
  17796. cursor shapes, or a custom one generated from an image.
  17797. */
  17798. class JUCE_API MouseCursor
  17799. {
  17800. public:
  17801. /** The set of available standard mouse cursors. */
  17802. enum StandardCursorType
  17803. {
  17804. NoCursor = 0, /**< An invisible cursor. */
  17805. NormalCursor, /**< The stardard arrow cursor. */
  17806. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  17807. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  17808. CrosshairCursor, /**< A pair of crosshairs. */
  17809. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  17810. that you're dragging a copy of something. */
  17811. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  17812. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  17813. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  17814. UpDownResizeCursor, /**< an arrow pointing up and down. */
  17815. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  17816. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  17817. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  17818. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  17819. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  17820. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  17821. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  17822. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  17823. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  17824. };
  17825. /** Creates the standard arrow cursor. */
  17826. MouseCursor();
  17827. /** Creates one of the standard mouse cursor */
  17828. MouseCursor (StandardCursorType type);
  17829. /** Creates a custom cursor from an image.
  17830. @param image the image to use for the cursor - if this is bigger than the
  17831. system can manage, it might get scaled down first, and might
  17832. also have to be turned to black-and-white if it can't do colour
  17833. cursors.
  17834. @param hotSpotX the x position of the cursor's hotspot within the image
  17835. @param hotSpotY the y position of the cursor's hotspot within the image
  17836. */
  17837. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  17838. /** Creates a copy of another cursor object. */
  17839. MouseCursor (const MouseCursor& other);
  17840. /** Copies this cursor from another object. */
  17841. MouseCursor& operator= (const MouseCursor& other);
  17842. /** Destructor. */
  17843. ~MouseCursor();
  17844. /** Checks whether two mouse cursors are the same.
  17845. For custom cursors, two cursors created from the same image won't be
  17846. recognised as the same, only MouseCursor objects that have been
  17847. copied from the same object.
  17848. */
  17849. bool operator== (const MouseCursor& other) const throw();
  17850. /** Checks whether two mouse cursors are the same.
  17851. For custom cursors, two cursors created from the same image won't be
  17852. recognised as the same, only MouseCursor objects that have been
  17853. copied from the same object.
  17854. */
  17855. bool operator!= (const MouseCursor& other) const throw();
  17856. /** Makes the system show its default 'busy' cursor.
  17857. This will turn the system cursor to an hourglass or spinning beachball
  17858. until the next time the mouse is moved, or hideWaitCursor() is called.
  17859. This is handy if the message loop is about to block for a couple of
  17860. seconds while busy and you want to give the user feedback about this.
  17861. @see MessageManager::setTimeBeforeShowingWaitCursor
  17862. */
  17863. static void showWaitCursor();
  17864. /** If showWaitCursor has been called, this will return the mouse to its
  17865. normal state.
  17866. This will look at what component is under the mouse, and update the
  17867. cursor to be the correct one for that component.
  17868. @see showWaitCursor
  17869. */
  17870. static void hideWaitCursor();
  17871. private:
  17872. class SharedCursorHandle;
  17873. friend class SharedCursorHandle;
  17874. SharedCursorHandle* cursorHandle;
  17875. friend class MouseInputSourceInternal;
  17876. void showInWindow (ComponentPeer* window) const;
  17877. void showInAllWindows() const;
  17878. void* getHandle() const throw();
  17879. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  17880. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  17881. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  17882. JUCE_LEAK_DETECTOR (MouseCursor);
  17883. };
  17884. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  17885. /*** End of inlined file: juce_MouseCursor.h ***/
  17886. /*** Start of inlined file: juce_MouseListener.h ***/
  17887. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  17888. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  17889. class MouseEvent;
  17890. /**
  17891. A MouseListener can be registered with a component to receive callbacks
  17892. about mouse events that happen to that component.
  17893. @see Component::addMouseListener, Component::removeMouseListener
  17894. */
  17895. class JUCE_API MouseListener
  17896. {
  17897. public:
  17898. /** Destructor. */
  17899. virtual ~MouseListener() {}
  17900. /** Called when the mouse moves inside a component.
  17901. If the mouse button isn't pressed and the mouse moves over a component,
  17902. this will be called to let the component react to this.
  17903. A component will always get a mouseEnter callback before a mouseMove.
  17904. @param e details about the position and status of the mouse event, including
  17905. the source component in which it occurred
  17906. @see mouseEnter, mouseExit, mouseDrag, contains
  17907. */
  17908. virtual void mouseMove (const MouseEvent& e);
  17909. /** Called when the mouse first enters a component.
  17910. If the mouse button isn't pressed and the mouse moves into a component,
  17911. this will be called to let the component react to this.
  17912. When the mouse button is pressed and held down while being moved in
  17913. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  17914. mouseDrag messages are sent to the component that the mouse was originally
  17915. clicked on, until the button is released.
  17916. @param e details about the position and status of the mouse event, including
  17917. the source component in which it occurred
  17918. @see mouseExit, mouseDrag, mouseMove, contains
  17919. */
  17920. virtual void mouseEnter (const MouseEvent& e);
  17921. /** Called when the mouse moves out of a component.
  17922. This will be called when the mouse moves off the edge of this
  17923. component.
  17924. If the mouse button was pressed, and it was then dragged off the
  17925. edge of the component and released, then this callback will happen
  17926. when the button is released, after the mouseUp callback.
  17927. @param e details about the position and status of the mouse event, including
  17928. the source component in which it occurred
  17929. @see mouseEnter, mouseDrag, mouseMove, contains
  17930. */
  17931. virtual void mouseExit (const MouseEvent& e);
  17932. /** Called when a mouse button is pressed.
  17933. The MouseEvent object passed in contains lots of methods for finding out
  17934. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17935. were held down at the time.
  17936. Once a button is held down, the mouseDrag method will be called when the
  17937. mouse moves, until the button is released.
  17938. @param e details about the position and status of the mouse event, including
  17939. the source component in which it occurred
  17940. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  17941. */
  17942. virtual void mouseDown (const MouseEvent& e);
  17943. /** Called when the mouse is moved while a button is held down.
  17944. When a mouse button is pressed inside a component, that component
  17945. receives mouseDrag callbacks each time the mouse moves, even if the
  17946. mouse strays outside the component's bounds.
  17947. @param e details about the position and status of the mouse event, including
  17948. the source component in which it occurred
  17949. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  17950. */
  17951. virtual void mouseDrag (const MouseEvent& e);
  17952. /** Called when a mouse button is released.
  17953. A mouseUp callback is sent to the component in which a button was pressed
  17954. even if the mouse is actually over a different component when the
  17955. button is released.
  17956. The MouseEvent object passed in contains lots of methods for finding out
  17957. which buttons were down just before they were released.
  17958. @param e details about the position and status of the mouse event, including
  17959. the source component in which it occurred
  17960. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  17961. */
  17962. virtual void mouseUp (const MouseEvent& e);
  17963. /** Called when a mouse button has been double-clicked on a component.
  17964. The MouseEvent object passed in contains lots of methods for finding out
  17965. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17966. were held down at the time.
  17967. @param e details about the position and status of the mouse event, including
  17968. the source component in which it occurred
  17969. @see mouseDown, mouseUp
  17970. */
  17971. virtual void mouseDoubleClick (const MouseEvent& e);
  17972. /** Called when the mouse-wheel is moved.
  17973. This callback is sent to the component that the mouse is over when the
  17974. wheel is moved.
  17975. If not overridden, the component will forward this message to its parent, so
  17976. that parent components can collect mouse-wheel messages that happen to
  17977. child components which aren't interested in them.
  17978. @param e details about the position and status of the mouse event, including
  17979. the source component in which it occurred
  17980. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  17981. value means the wheel has been pushed to the right, negative means it
  17982. was pushed to the left
  17983. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  17984. value means the wheel has been pushed upwards, negative means it
  17985. was pushed downwards
  17986. */
  17987. virtual void mouseWheelMove (const MouseEvent& e,
  17988. float wheelIncrementX,
  17989. float wheelIncrementY);
  17990. };
  17991. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  17992. /*** End of inlined file: juce_MouseListener.h ***/
  17993. /*** Start of inlined file: juce_MouseEvent.h ***/
  17994. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  17995. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  17996. class Component;
  17997. class MouseInputSource;
  17998. /*** Start of inlined file: juce_ModifierKeys.h ***/
  17999. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  18000. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  18001. /**
  18002. Represents the state of the mouse buttons and modifier keys.
  18003. This is used both by mouse events and by KeyPress objects to describe
  18004. the state of keys such as shift, control, alt, etc.
  18005. @see KeyPress, MouseEvent::mods
  18006. */
  18007. class JUCE_API ModifierKeys
  18008. {
  18009. public:
  18010. /** Creates a ModifierKeys object from a raw set of flags.
  18011. @param flags to represent the keys that are down
  18012. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  18013. rightButtonModifier, commandModifier, popupMenuClickModifier
  18014. */
  18015. ModifierKeys (int flags = 0) throw();
  18016. /** Creates a copy of another object. */
  18017. ModifierKeys (const ModifierKeys& other) throw();
  18018. /** Copies this object from another one. */
  18019. ModifierKeys& operator= (const ModifierKeys& other) throw();
  18020. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  18021. This is a platform-agnostic way of checking for the operating system's
  18022. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  18023. Windows/Linux, it's actually checking for the CTRL key.
  18024. */
  18025. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  18026. /** Checks whether the user is trying to launch a pop-up menu.
  18027. This checks for platform-specific modifiers that might indicate that the user
  18028. is following the operating system's normal method of showing a pop-up menu.
  18029. So on Windows/Linux, this method is really testing for a right-click.
  18030. On the Mac, it tests for either the CTRL key being down, or a right-click.
  18031. */
  18032. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  18033. /** Checks whether the flag is set for the left mouse-button. */
  18034. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  18035. /** Checks whether the flag is set for the right mouse-button.
  18036. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  18037. this is platform-independent (and makes your code more explanatory too).
  18038. */
  18039. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  18040. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  18041. /** Tests for any of the mouse-button flags. */
  18042. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  18043. /** Tests for any of the modifier key flags. */
  18044. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  18045. /** Checks whether the shift key's flag is set. */
  18046. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  18047. /** Checks whether the CTRL key's flag is set.
  18048. Remember that it's better to use the platform-agnostic routines to test for command-key and
  18049. popup-menu modifiers.
  18050. @see isCommandDown, isPopupMenu
  18051. */
  18052. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  18053. /** Checks whether the shift key's flag is set. */
  18054. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  18055. /** Flags that represent the different keys. */
  18056. enum Flags
  18057. {
  18058. /** Shift key flag. */
  18059. shiftModifier = 1,
  18060. /** CTRL key flag. */
  18061. ctrlModifier = 2,
  18062. /** ALT key flag. */
  18063. altModifier = 4,
  18064. /** Left mouse button flag. */
  18065. leftButtonModifier = 16,
  18066. /** Right mouse button flag. */
  18067. rightButtonModifier = 32,
  18068. /** Middle mouse button flag. */
  18069. middleButtonModifier = 64,
  18070. #if JUCE_MAC
  18071. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18072. commandModifier = 8,
  18073. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18074. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18075. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  18076. #else
  18077. /** Command key flag - on windows this is the same as the CTRL key flag. */
  18078. commandModifier = ctrlModifier,
  18079. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  18080. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  18081. popupMenuClickModifier = rightButtonModifier,
  18082. #endif
  18083. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  18084. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  18085. /** Represents a combination of all the mouse buttons at once. */
  18086. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  18087. };
  18088. /** Returns a copy of only the mouse-button flags */
  18089. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  18090. /** Returns a copy of only the non-mouse flags */
  18091. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  18092. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  18093. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  18094. /** Returns the raw flags for direct testing. */
  18095. inline int getRawFlags() const throw() { return flags; }
  18096. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  18097. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  18098. /** Tests a combination of flags and returns true if any of them are set. */
  18099. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  18100. /** Returns the total number of mouse buttons that are down. */
  18101. int getNumMouseButtonsDown() const throw();
  18102. /** Creates a ModifierKeys object to represent the last-known state of the
  18103. keyboard and mouse buttons.
  18104. @see getCurrentModifiersRealtime
  18105. */
  18106. static const ModifierKeys getCurrentModifiers() throw();
  18107. /** Creates a ModifierKeys object to represent the current state of the
  18108. keyboard and mouse buttons.
  18109. This isn't often needed and isn't recommended, but will actively check all the
  18110. mouse and key states rather than just returning their last-known state like
  18111. getCurrentModifiers() does.
  18112. This is only needed in special circumstances for up-to-date modifier information
  18113. at times when the app's event loop isn't running normally.
  18114. Another reason to avoid this method is that it's not stateless, and calling it may
  18115. update the value returned by getCurrentModifiers(), which could cause subtle changes
  18116. in the behaviour of some components.
  18117. */
  18118. static const ModifierKeys getCurrentModifiersRealtime() throw();
  18119. private:
  18120. int flags;
  18121. static ModifierKeys currentModifiers;
  18122. friend class ComponentPeer;
  18123. friend class MouseInputSource;
  18124. friend class MouseInputSourceInternal;
  18125. static void updateCurrentModifiers() throw();
  18126. };
  18127. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  18128. /*** End of inlined file: juce_ModifierKeys.h ***/
  18129. /*** Start of inlined file: juce_Point.h ***/
  18130. #ifndef __JUCE_POINT_JUCEHEADER__
  18131. #define __JUCE_POINT_JUCEHEADER__
  18132. /*** Start of inlined file: juce_AffineTransform.h ***/
  18133. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18134. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18135. /**
  18136. Represents a 2D affine-transformation matrix.
  18137. An affine transformation is a transformation such as a rotation, scale, shear,
  18138. resize or translation.
  18139. These are used for various 2D transformation tasks, e.g. with Path objects.
  18140. @see Path, Point, Line
  18141. */
  18142. class JUCE_API AffineTransform
  18143. {
  18144. public:
  18145. /** Creates an identity transform. */
  18146. AffineTransform() throw();
  18147. /** Creates a copy of another transform. */
  18148. AffineTransform (const AffineTransform& other) throw();
  18149. /** Creates a transform from a set of raw matrix values.
  18150. The resulting matrix is:
  18151. (mat00 mat01 mat02)
  18152. (mat10 mat11 mat12)
  18153. ( 0 0 1 )
  18154. */
  18155. AffineTransform (float mat00, float mat01, float mat02,
  18156. float mat10, float mat11, float mat12) throw();
  18157. /** Copies from another AffineTransform object */
  18158. AffineTransform& operator= (const AffineTransform& other) throw();
  18159. /** Compares two transforms. */
  18160. bool operator== (const AffineTransform& other) const throw();
  18161. /** Compares two transforms. */
  18162. bool operator!= (const AffineTransform& other) const throw();
  18163. /** A ready-to-use identity transform, which you can use to append other
  18164. transformations to.
  18165. e.g. @code
  18166. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  18167. .scaled (2.0f);
  18168. @endcode
  18169. */
  18170. static const AffineTransform identity;
  18171. /** Transforms a 2D co-ordinate using this matrix. */
  18172. template <typename ValueType>
  18173. void transformPoint (ValueType& x, ValueType& y) const throw()
  18174. {
  18175. const ValueType oldX = x;
  18176. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  18177. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  18178. }
  18179. /** Transforms two 2D co-ordinates using this matrix.
  18180. This is just a shortcut for calling transformPoint() on each of these pairs of
  18181. coordinates in turn. (And putting all the calculations into one function hopefully
  18182. also gives the compiler a bit more scope for pipelining it).
  18183. */
  18184. template <typename ValueType>
  18185. void transformPoints (ValueType& x1, ValueType& y1,
  18186. ValueType& x2, ValueType& y2) const throw()
  18187. {
  18188. const ValueType oldX1 = x1, oldX2 = x2;
  18189. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18190. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18191. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18192. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18193. }
  18194. /** Transforms three 2D co-ordinates using this matrix.
  18195. This is just a shortcut for calling transformPoint() on each of these pairs of
  18196. coordinates in turn. (And putting all the calculations into one function hopefully
  18197. also gives the compiler a bit more scope for pipelining it).
  18198. */
  18199. template <typename ValueType>
  18200. void transformPoints (ValueType& x1, ValueType& y1,
  18201. ValueType& x2, ValueType& y2,
  18202. ValueType& x3, ValueType& y3) const throw()
  18203. {
  18204. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  18205. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  18206. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  18207. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  18208. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  18209. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  18210. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  18211. }
  18212. /** Returns a new transform which is the same as this one followed by a translation. */
  18213. const AffineTransform translated (float deltaX,
  18214. float deltaY) const throw();
  18215. /** Returns a new transform which is a translation. */
  18216. static const AffineTransform translation (float deltaX,
  18217. float deltaY) throw();
  18218. /** Returns a transform which is the same as this one followed by a rotation.
  18219. The rotation is specified by a number of radians to rotate clockwise, centred around
  18220. the origin (0, 0).
  18221. */
  18222. const AffineTransform rotated (float angleInRadians) const throw();
  18223. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  18224. The rotation is specified by a number of radians to rotate clockwise, centred around
  18225. the co-ordinates passed in.
  18226. */
  18227. const AffineTransform rotated (float angleInRadians,
  18228. float pivotX,
  18229. float pivotY) const throw();
  18230. /** Returns a new transform which is a rotation about (0, 0). */
  18231. static const AffineTransform rotation (float angleInRadians) throw();
  18232. /** Returns a new transform which is a rotation about a given point. */
  18233. static const AffineTransform rotation (float angleInRadians,
  18234. float pivotX,
  18235. float pivotY) throw();
  18236. /** Returns a transform which is the same as this one followed by a re-scaling.
  18237. The scaling is centred around the origin (0, 0).
  18238. */
  18239. const AffineTransform scaled (float factorX,
  18240. float factorY) const throw();
  18241. /** Returns a transform which is the same as this one followed by a re-scaling.
  18242. The scaling is centred around the origin provided.
  18243. */
  18244. const AffineTransform scaled (float factorX, float factorY,
  18245. float pivotX, float pivotY) const throw();
  18246. /** Returns a new transform which is a re-scale about the origin. */
  18247. static const AffineTransform scale (float factorX,
  18248. float factorY) throw();
  18249. /** Returns a new transform which is a re-scale centred around the point provided. */
  18250. static const AffineTransform scale (float factorX, float factorY,
  18251. float pivotX, float pivotY) throw();
  18252. /** Returns a transform which is the same as this one followed by a shear.
  18253. The shear is centred around the origin (0, 0).
  18254. */
  18255. const AffineTransform sheared (float shearX, float shearY) const throw();
  18256. /** Returns a shear transform, centred around the origin (0, 0). */
  18257. static const AffineTransform shear (float shearX, float shearY) throw();
  18258. /** Returns a matrix which is the inverse operation of this one.
  18259. Some matrices don't have an inverse - in this case, the method will just return
  18260. an identity transform.
  18261. */
  18262. const AffineTransform inverted() const throw();
  18263. /** Returns the transform that will map three known points onto three coordinates
  18264. that are supplied.
  18265. This returns the transform that will transform (0, 0) into (x00, y00),
  18266. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  18267. */
  18268. static const AffineTransform fromTargetPoints (float x00, float y00,
  18269. float x10, float y10,
  18270. float x01, float y01) throw();
  18271. /** Returns the transform that will map three specified points onto three target points.
  18272. */
  18273. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  18274. float sourceX2, float sourceY2, float targetX2, float targetY2,
  18275. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  18276. /** Returns the result of concatenating another transformation after this one. */
  18277. const AffineTransform followedBy (const AffineTransform& other) const throw();
  18278. /** Returns true if this transform has no effect on points. */
  18279. bool isIdentity() const throw();
  18280. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  18281. bool isSingularity() const throw();
  18282. /** Returns true if the transform only translates, and doesn't scale or rotate the
  18283. points. */
  18284. bool isOnlyTranslation() const throw();
  18285. /** If this transform is only a translation, this returns the X offset.
  18286. @see isOnlyTranslation
  18287. */
  18288. float getTranslationX() const throw() { return mat02; }
  18289. /** If this transform is only a translation, this returns the X offset.
  18290. @see isOnlyTranslation
  18291. */
  18292. float getTranslationY() const throw() { return mat12; }
  18293. /** Returns the approximate scale factor by which lengths will be transformed.
  18294. Obviously a length may be scaled by entirely different amounts depending on its
  18295. direction, so this is only appropriate as a rough guide.
  18296. */
  18297. float getScaleFactor() const throw();
  18298. /* The transform matrix is:
  18299. (mat00 mat01 mat02)
  18300. (mat10 mat11 mat12)
  18301. ( 0 0 1 )
  18302. */
  18303. float mat00, mat01, mat02;
  18304. float mat10, mat11, mat12;
  18305. private:
  18306. JUCE_LEAK_DETECTOR (AffineTransform);
  18307. };
  18308. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  18309. /*** End of inlined file: juce_AffineTransform.h ***/
  18310. /**
  18311. A pair of (x, y) co-ordinates.
  18312. The ValueType template should be a primitive type such as int, float, double,
  18313. rather than a class.
  18314. @see Line, Path, AffineTransform
  18315. */
  18316. template <typename ValueType>
  18317. class Point
  18318. {
  18319. public:
  18320. /** Creates a point with co-ordinates (0, 0). */
  18321. Point() throw() : x(), y() {}
  18322. /** Creates a copy of another point. */
  18323. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  18324. /** Creates a point from an (x, y) position. */
  18325. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  18326. /** Destructor. */
  18327. ~Point() throw() {}
  18328. /** Copies this point from another one. */
  18329. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  18330. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  18331. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  18332. /** Returns true if the point is (0, 0). */
  18333. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  18334. /** Returns the point's x co-ordinate. */
  18335. inline ValueType getX() const throw() { return x; }
  18336. /** Returns the point's y co-ordinate. */
  18337. inline ValueType getY() const throw() { return y; }
  18338. /** Sets the point's x co-ordinate. */
  18339. inline void setX (const ValueType newX) throw() { x = newX; }
  18340. /** Sets the point's y co-ordinate. */
  18341. inline void setY (const ValueType newY) throw() { y = newY; }
  18342. /** Returns a point which has the same Y position as this one, but a new X. */
  18343. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  18344. /** Returns a point which has the same X position as this one, but a new Y. */
  18345. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  18346. /** Changes the point's x and y co-ordinates. */
  18347. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  18348. /** Adds a pair of co-ordinates to this value. */
  18349. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  18350. /** Returns a point with a given offset from this one. */
  18351. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  18352. /** Adds two points together. */
  18353. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  18354. /** Adds another point's co-ordinates to this one. */
  18355. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  18356. /** Subtracts one points from another. */
  18357. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  18358. /** Subtracts another point's co-ordinates to this one. */
  18359. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  18360. /** Returns a point whose coordinates are multiplied by a given value. */
  18361. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  18362. /** Multiplies the point's co-ordinates by a value. */
  18363. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  18364. /** Returns a point whose coordinates are divided by a given value. */
  18365. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  18366. /** Divides the point's co-ordinates by a value. */
  18367. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  18368. /** Returns the inverse of this point. */
  18369. const Point operator-() const throw() { return Point (-x, -y); }
  18370. /** Returns the straight-line distance between this point and another one. */
  18371. ValueType getDistanceFromOrigin() const throw() { return juce_hypot (x, y); }
  18372. /** Returns the straight-line distance between this point and another one. */
  18373. ValueType getDistanceFrom (const Point& other) const throw() { return juce_hypot (x - other.x, y - other.y); }
  18374. /** Returns the angle from this point to another one.
  18375. The return value is the number of radians clockwise from the 3 o'clock direction,
  18376. where this point is the centre and the other point is on the circumference.
  18377. */
  18378. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  18379. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  18380. @param radius the radius of the circle.
  18381. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18382. */
  18383. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  18384. y - radius * std::cos (angle)); }
  18385. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  18386. @param radiusX the horizontal radius of the circle.
  18387. @param radiusY the vertical radius of the circle.
  18388. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  18389. */
  18390. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  18391. y - radiusY * std::cos (angle)); }
  18392. /** Uses a transform to change the point's co-ordinates.
  18393. This will only compile if ValueType = float!
  18394. @see AffineTransform::transformPoint
  18395. */
  18396. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  18397. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  18398. const Point transformedBy (const AffineTransform& transform) const throw() { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  18399. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  18400. /** Casts this point to a Point<int> object. */
  18401. const Point<int> toInt() const throw() { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  18402. /** Casts this point to a Point<float> object. */
  18403. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  18404. /** Casts this point to a Point<double> object. */
  18405. const Point<double> toDouble() const throw() { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  18406. /** Returns the point as a string in the form "x, y". */
  18407. const String toString() const { return String (x) + ", " + String (y); }
  18408. private:
  18409. ValueType x, y;
  18410. };
  18411. #endif // __JUCE_POINT_JUCEHEADER__
  18412. /*** End of inlined file: juce_Point.h ***/
  18413. /**
  18414. Contains position and status information about a mouse event.
  18415. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  18416. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  18417. */
  18418. class JUCE_API MouseEvent
  18419. {
  18420. public:
  18421. /** Creates a MouseEvent.
  18422. Normally an application will never need to use this.
  18423. @param source the source that's invoking the event
  18424. @param position the position of the mouse, relative to the component that is passed-in
  18425. @param modifiers the key modifiers at the time of the event
  18426. @param eventComponent the component that the mouse event applies to
  18427. @param originator the component that originally received the event
  18428. @param eventTime the time the event happened
  18429. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  18430. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18431. the same as the current mouse-x position.
  18432. @param mouseDownTime the time at which the corresponding mouse-down event happened
  18433. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  18434. the same as the current mouse-event time.
  18435. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  18436. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  18437. */
  18438. MouseEvent (MouseInputSource& source,
  18439. const Point<int>& position,
  18440. const ModifierKeys& modifiers,
  18441. Component* eventComponent,
  18442. Component* originator,
  18443. const Time& eventTime,
  18444. const Point<int> mouseDownPos,
  18445. const Time& mouseDownTime,
  18446. int numberOfClicks,
  18447. bool mouseWasDragged) throw();
  18448. /** Destructor. */
  18449. ~MouseEvent() throw();
  18450. /** The x-position of the mouse when the event occurred.
  18451. This value is relative to the top-left of the component to which the
  18452. event applies (as indicated by the MouseEvent::eventComponent field).
  18453. */
  18454. const int x;
  18455. /** The y-position of the mouse when the event occurred.
  18456. This value is relative to the top-left of the component to which the
  18457. event applies (as indicated by the MouseEvent::eventComponent field).
  18458. */
  18459. const int y;
  18460. /** The key modifiers associated with the event.
  18461. This will let you find out which mouse buttons were down, as well as which
  18462. modifier keys were held down.
  18463. When used for mouse-up events, this will indicate the state of the mouse buttons
  18464. just before they were released, so that you can tell which button they let go of.
  18465. */
  18466. const ModifierKeys mods;
  18467. /** The component that this event applies to.
  18468. This is usually the component that the mouse was over at the time, but for mouse-drag
  18469. events the mouse could actually be over a different component and the events are
  18470. still sent to the component that the button was originally pressed on.
  18471. The x and y member variables are relative to this component's position.
  18472. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18473. component, this pointer will be updated, but originalComponent remains unchanged.
  18474. @see originalComponent
  18475. */
  18476. Component* const eventComponent;
  18477. /** The component that the event first occurred on.
  18478. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18479. component, this value remains unchanged to indicate the first component that received it.
  18480. @see eventComponent
  18481. */
  18482. Component* const originalComponent;
  18483. /** The time that this mouse-event occurred.
  18484. */
  18485. const Time eventTime;
  18486. /** The source device that generated this event.
  18487. */
  18488. MouseInputSource& source;
  18489. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  18490. The co-ordinate is relative to the component specified in MouseEvent::component.
  18491. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18492. */
  18493. int getMouseDownX() const throw();
  18494. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  18495. The co-ordinate is relative to the component specified in MouseEvent::component.
  18496. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18497. */
  18498. int getMouseDownY() const throw();
  18499. /** Returns the co-ordinates of the last place that a mouse was pressed.
  18500. The co-ordinates are relative to the component specified in MouseEvent::component.
  18501. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18502. */
  18503. const Point<int> getMouseDownPosition() const throw();
  18504. /** Returns the straight-line distance between where the mouse is now and where it
  18505. was the last time the button was pressed.
  18506. This is quite handy for things like deciding whether the user has moved far enough
  18507. for it to be considered a drag operation.
  18508. @see getDistanceFromDragStartX
  18509. */
  18510. int getDistanceFromDragStart() const throw();
  18511. /** Returns the difference between the mouse's current x postion and where it was
  18512. when the button was last pressed.
  18513. @see getDistanceFromDragStart
  18514. */
  18515. int getDistanceFromDragStartX() const throw();
  18516. /** Returns the difference between the mouse's current y postion and where it was
  18517. when the button was last pressed.
  18518. @see getDistanceFromDragStart
  18519. */
  18520. int getDistanceFromDragStartY() const throw();
  18521. /** Returns the difference between the mouse's current postion and where it was
  18522. when the button was last pressed.
  18523. @see getDistanceFromDragStart
  18524. */
  18525. const Point<int> getOffsetFromDragStart() const throw();
  18526. /** Returns true if the mouse has just been clicked.
  18527. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  18528. the user has dragged the mouse more than a few pixels from the place where the
  18529. mouse-down occurred.
  18530. Once they have dragged it far enough for this method to return false, it will continue
  18531. to return false until the mouse-up, even if they move the mouse back to the same
  18532. position where they originally pressed it. This means that it's very handy for
  18533. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  18534. callback to ignore any small movements they might make while clicking.
  18535. @returns true if the mouse wasn't dragged by more than a few pixels between
  18536. the last time the button was pressed and released.
  18537. */
  18538. bool mouseWasClicked() const throw();
  18539. /** For a click event, the number of times the mouse was clicked in succession.
  18540. So for example a double-click event will return 2, a triple-click 3, etc.
  18541. */
  18542. int getNumberOfClicks() const throw() { return numberOfClicks; }
  18543. /** Returns the time that the mouse button has been held down for.
  18544. If called from a mouseDrag or mouseUp callback, this will return the
  18545. number of milliseconds since the corresponding mouseDown event occurred.
  18546. If called in other contexts, e.g. a mouseMove, then the returned value
  18547. may be 0 or an undefined value.
  18548. */
  18549. int getLengthOfMousePress() const throw();
  18550. /** The position of the mouse when the event occurred.
  18551. This position is relative to the top-left of the component to which the
  18552. event applies (as indicated by the MouseEvent::eventComponent field).
  18553. */
  18554. const Point<int> getPosition() const throw();
  18555. /** Returns the mouse x position of this event, in global screen co-ordinates.
  18556. The co-ordinates are relative to the top-left of the main monitor.
  18557. @see getScreenPosition
  18558. */
  18559. int getScreenX() const;
  18560. /** Returns the mouse y position of this event, in global screen co-ordinates.
  18561. The co-ordinates are relative to the top-left of the main monitor.
  18562. @see getScreenPosition
  18563. */
  18564. int getScreenY() const;
  18565. /** Returns the mouse position of this event, in global screen co-ordinates.
  18566. The co-ordinates are relative to the top-left of the main monitor.
  18567. @see getMouseDownScreenPosition
  18568. */
  18569. const Point<int> getScreenPosition() const;
  18570. /** Returns the x co-ordinate at which the mouse button was last pressed.
  18571. The co-ordinates are relative to the top-left of the main monitor.
  18572. @see getMouseDownScreenPosition
  18573. */
  18574. int getMouseDownScreenX() const;
  18575. /** Returns the y co-ordinate at which the mouse button was last pressed.
  18576. The co-ordinates are relative to the top-left of the main monitor.
  18577. @see getMouseDownScreenPosition
  18578. */
  18579. int getMouseDownScreenY() const;
  18580. /** Returns the co-ordinates at which the mouse button was last pressed.
  18581. The co-ordinates are relative to the top-left of the main monitor.
  18582. @see getScreenPosition
  18583. */
  18584. const Point<int> getMouseDownScreenPosition() const;
  18585. /** Creates a version of this event that is relative to a different component.
  18586. The x and y positions of the event that is returned will have been
  18587. adjusted to be relative to the new component.
  18588. */
  18589. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  18590. /** Creates a copy of this event with a different position.
  18591. All other members of the event object are the same, but the x and y are
  18592. replaced with these new values.
  18593. */
  18594. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  18595. /** Changes the application-wide setting for the double-click time limit.
  18596. This is the maximum length of time between mouse-clicks for it to be
  18597. considered a double-click. It's used by the Component class.
  18598. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  18599. */
  18600. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  18601. /** Returns the application-wide setting for the double-click time limit.
  18602. This is the maximum length of time between mouse-clicks for it to be
  18603. considered a double-click. It's used by the Component class.
  18604. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  18605. */
  18606. static int getDoubleClickTimeout() throw();
  18607. private:
  18608. const Point<int> mouseDownPos;
  18609. const Time mouseDownTime;
  18610. const int numberOfClicks;
  18611. const bool wasMovedSinceMouseDown;
  18612. static int doubleClickTimeOutMs;
  18613. MouseEvent& operator= (const MouseEvent&);
  18614. };
  18615. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  18616. /*** End of inlined file: juce_MouseEvent.h ***/
  18617. /*** Start of inlined file: juce_ComponentListener.h ***/
  18618. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18619. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18620. class Component;
  18621. /**
  18622. Gets informed about changes to a component's hierarchy or position.
  18623. To monitor a component for changes, register a subclass of ComponentListener
  18624. with the component using Component::addComponentListener().
  18625. Be sure to deregister listeners before you delete them!
  18626. @see Component::addComponentListener, Component::removeComponentListener
  18627. */
  18628. class JUCE_API ComponentListener
  18629. {
  18630. public:
  18631. /** Destructor. */
  18632. virtual ~ComponentListener() {}
  18633. /** Called when the component's position or size changes.
  18634. @param component the component that was moved or resized
  18635. @param wasMoved true if the component's top-left corner has just moved
  18636. @param wasResized true if the component's width or height has just changed
  18637. @see Component::setBounds, Component::resized, Component::moved
  18638. */
  18639. virtual void componentMovedOrResized (Component& component,
  18640. bool wasMoved,
  18641. bool wasResized);
  18642. /** Called when the component is brought to the top of the z-order.
  18643. @param component the component that was moved
  18644. @see Component::toFront, Component::broughtToFront
  18645. */
  18646. virtual void componentBroughtToFront (Component& component);
  18647. /** Called when the component is made visible or invisible.
  18648. @param component the component that changed
  18649. @see Component::setVisible
  18650. */
  18651. virtual void componentVisibilityChanged (Component& component);
  18652. /** Called when the component has children added or removed.
  18653. @param component the component whose children were changed
  18654. @see Component::childrenChanged, Component::addChildComponent,
  18655. Component::removeChildComponent
  18656. */
  18657. virtual void componentChildrenChanged (Component& component);
  18658. /** Called to indicate that the component's parents have changed.
  18659. When a component is added or removed from its parent, all of its children
  18660. will produce this notification (recursively - so all children of its
  18661. children will also be called as well).
  18662. @param component the component that this listener is registered with
  18663. @see Component::parentHierarchyChanged
  18664. */
  18665. virtual void componentParentHierarchyChanged (Component& component);
  18666. /** Called when the component's name is changed.
  18667. @see Component::setName, Component::getName
  18668. */
  18669. virtual void componentNameChanged (Component& component);
  18670. /** Called when the component is in the process of being deleted.
  18671. This callback is made from inside the destructor, so be very, very cautious
  18672. about what you do in here.
  18673. In particular, bear in mind that it's the Component base class's destructor that calls
  18674. this - so if the object that's being deleted is a subclass of Component, then the
  18675. subclass layers of the object will already have been destructed when it gets to this
  18676. point!
  18677. */
  18678. virtual void componentBeingDeleted (Component& component);
  18679. };
  18680. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18681. /*** End of inlined file: juce_ComponentListener.h ***/
  18682. /*** Start of inlined file: juce_KeyListener.h ***/
  18683. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  18684. #define __JUCE_KEYLISTENER_JUCEHEADER__
  18685. /*** Start of inlined file: juce_KeyPress.h ***/
  18686. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  18687. #define __JUCE_KEYPRESS_JUCEHEADER__
  18688. /**
  18689. Represents a key press, including any modifier keys that are needed.
  18690. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  18691. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  18692. */
  18693. class JUCE_API KeyPress
  18694. {
  18695. public:
  18696. /** Creates an (invalid) KeyPress.
  18697. @see isValid
  18698. */
  18699. KeyPress() throw();
  18700. /** Creates a KeyPress for a key and some modifiers.
  18701. e.g.
  18702. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  18703. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  18704. @param keyCode a code that represents the key - this value must be
  18705. one of special constants listed in this class, or an
  18706. 8-bit character code such as a letter (case is ignored),
  18707. digit or a simple key like "," or ".". Note that this
  18708. isn't the same as the textCharacter parameter, so for example
  18709. a keyCode of 'a' and a shift-key modifier should have a
  18710. textCharacter value of 'A'.
  18711. @param modifiers the modifiers to associate with the keystroke
  18712. @param textCharacter the character that would be printed if someone typed
  18713. this keypress into a text editor. This value may be
  18714. null if the keypress is a non-printing character
  18715. @see getKeyCode, isKeyCode, getModifiers
  18716. */
  18717. KeyPress (int keyCode,
  18718. const ModifierKeys& modifiers,
  18719. juce_wchar textCharacter) throw();
  18720. /** Creates a keypress with a keyCode but no modifiers or text character.
  18721. */
  18722. KeyPress (int keyCode) throw();
  18723. /** Creates a copy of another KeyPress. */
  18724. KeyPress (const KeyPress& other) throw();
  18725. /** Copies this KeyPress from another one. */
  18726. KeyPress& operator= (const KeyPress& other) throw();
  18727. /** Compares two KeyPress objects. */
  18728. bool operator== (const KeyPress& other) const throw();
  18729. /** Compares two KeyPress objects. */
  18730. bool operator!= (const KeyPress& other) const throw();
  18731. /** Returns true if this is a valid KeyPress.
  18732. A null keypress can be created by the default constructor, in case it's
  18733. needed.
  18734. */
  18735. bool isValid() const throw() { return keyCode != 0; }
  18736. /** Returns the key code itself.
  18737. This will either be one of the special constants defined in this class,
  18738. or an 8-bit character code.
  18739. */
  18740. int getKeyCode() const throw() { return keyCode; }
  18741. /** Returns the key modifiers.
  18742. @see ModifierKeys
  18743. */
  18744. const ModifierKeys getModifiers() const throw() { return mods; }
  18745. /** Returns the character that is associated with this keypress.
  18746. This is the character that you'd expect to see printed if you press this
  18747. keypress in a text editor or similar component.
  18748. */
  18749. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  18750. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  18751. the modifiers.
  18752. The values for key codes can either be one of the special constants defined in
  18753. this class, or an 8-bit character code.
  18754. @see getKeyCode
  18755. */
  18756. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  18757. /** Converts a textual key description to a KeyPress.
  18758. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  18759. This isn't designed to cope with any kind of input, but should be given the
  18760. strings that are created by the getTextDescription() method.
  18761. If the string can't be parsed, the object returned will be invalid.
  18762. @see getTextDescription
  18763. */
  18764. static const KeyPress createFromDescription (const String& textVersion);
  18765. /** Creates a textual description of the key combination.
  18766. e.g. "CTRL + C" or "DELETE".
  18767. To store a keypress in a file, use this method, along with createFromDescription()
  18768. to retrieve it later.
  18769. */
  18770. const String getTextDescription() const;
  18771. /** Creates a textual description of the key combination, using unicode icon symbols if possible.
  18772. On OSX, this uses the Apple symbols for command, option, shift, etc, instead of the textual
  18773. modifier key descriptions that are returned by getTextDescription()
  18774. */
  18775. const String getTextDescriptionWithIcons() const;
  18776. /** Checks whether the user is currently holding down the keys that make up this
  18777. KeyPress.
  18778. Note that this will return false if any extra modifier keys are
  18779. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  18780. then it will be false.
  18781. */
  18782. bool isCurrentlyDown() const;
  18783. /** Checks whether a particular key is held down, irrespective of modifiers.
  18784. The values for key codes can either be one of the special constants defined in
  18785. this class, or an 8-bit character code.
  18786. */
  18787. static bool isKeyCurrentlyDown (int keyCode);
  18788. // Key codes
  18789. //
  18790. // Note that the actual values of these are platform-specific and may change
  18791. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  18792. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  18793. //
  18794. static const int spaceKey; /**< key-code for the space bar */
  18795. static const int escapeKey; /**< key-code for the escape key */
  18796. static const int returnKey; /**< key-code for the return key*/
  18797. static const int tabKey; /**< key-code for the tab key*/
  18798. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  18799. static const int backspaceKey; /**< key-code for the backspace key */
  18800. static const int insertKey; /**< key-code for the insert key */
  18801. static const int upKey; /**< key-code for the cursor-up key */
  18802. static const int downKey; /**< key-code for the cursor-down key */
  18803. static const int leftKey; /**< key-code for the cursor-left key */
  18804. static const int rightKey; /**< key-code for the cursor-right key */
  18805. static const int pageUpKey; /**< key-code for the page-up key */
  18806. static const int pageDownKey; /**< key-code for the page-down key */
  18807. static const int homeKey; /**< key-code for the home key */
  18808. static const int endKey; /**< key-code for the end key */
  18809. static const int F1Key; /**< key-code for the F1 key */
  18810. static const int F2Key; /**< key-code for the F2 key */
  18811. static const int F3Key; /**< key-code for the F3 key */
  18812. static const int F4Key; /**< key-code for the F4 key */
  18813. static const int F5Key; /**< key-code for the F5 key */
  18814. static const int F6Key; /**< key-code for the F6 key */
  18815. static const int F7Key; /**< key-code for the F7 key */
  18816. static const int F8Key; /**< key-code for the F8 key */
  18817. static const int F9Key; /**< key-code for the F9 key */
  18818. static const int F10Key; /**< key-code for the F10 key */
  18819. static const int F11Key; /**< key-code for the F11 key */
  18820. static const int F12Key; /**< key-code for the F12 key */
  18821. static const int F13Key; /**< key-code for the F13 key */
  18822. static const int F14Key; /**< key-code for the F14 key */
  18823. static const int F15Key; /**< key-code for the F15 key */
  18824. static const int F16Key; /**< key-code for the F16 key */
  18825. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  18826. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  18827. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  18828. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  18829. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  18830. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  18831. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  18832. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  18833. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  18834. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  18835. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  18836. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  18837. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  18838. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  18839. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  18840. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  18841. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  18842. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  18843. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  18844. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  18845. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  18846. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  18847. private:
  18848. int keyCode;
  18849. ModifierKeys mods;
  18850. juce_wchar textCharacter;
  18851. JUCE_LEAK_DETECTOR (KeyPress);
  18852. };
  18853. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  18854. /*** End of inlined file: juce_KeyPress.h ***/
  18855. class Component;
  18856. /**
  18857. Receives callbacks when keys are pressed.
  18858. You can add a key listener to a component to be informed when that component
  18859. gets key events. See the Component::addListener method for more details.
  18860. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  18861. */
  18862. class JUCE_API KeyListener
  18863. {
  18864. public:
  18865. /** Destructor. */
  18866. virtual ~KeyListener() {}
  18867. /** Called to indicate that a key has been pressed.
  18868. If your implementation returns true, then the key event is considered to have
  18869. been consumed, and will not be passed on to any other components. If it returns
  18870. false, then the key will be passed to other components that might want to use it.
  18871. @param key the keystroke, including modifier keys
  18872. @param originatingComponent the component that received the key event
  18873. @see keyStateChanged, Component::keyPressed
  18874. */
  18875. virtual bool keyPressed (const KeyPress& key,
  18876. Component* originatingComponent) = 0;
  18877. /** Called when any key is pressed or released.
  18878. When this is called, classes that might be interested in
  18879. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  18880. check whether their key has changed.
  18881. If your implementation returns true, then the key event is considered to have
  18882. been consumed, and will not be passed on to any other components. If it returns
  18883. false, then the key will be passed to other components that might want to use it.
  18884. @param originatingComponent the component that received the key event
  18885. @param isKeyDown true if a key is being pressed, false if one is being released
  18886. @see KeyPress, Component::keyStateChanged
  18887. */
  18888. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  18889. };
  18890. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  18891. /*** End of inlined file: juce_KeyListener.h ***/
  18892. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  18893. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18894. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18895. class Component;
  18896. /**
  18897. Controls the order in which focus moves between components.
  18898. The default algorithm used by this class to work out the order of traversal
  18899. is as follows:
  18900. - if two components both have an explicit focus order specified, then the
  18901. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  18902. method).
  18903. - any component with an explicit focus order greater than 0 comes before ones
  18904. that don't have an order specified.
  18905. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  18906. order.
  18907. If you need traversal in a more customised way, you can create a subclass
  18908. of KeyboardFocusTraverser that uses your own algorithm, and use
  18909. Component::createFocusTraverser() to create it.
  18910. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  18911. */
  18912. class JUCE_API KeyboardFocusTraverser
  18913. {
  18914. public:
  18915. KeyboardFocusTraverser();
  18916. /** Destructor. */
  18917. virtual ~KeyboardFocusTraverser();
  18918. /** Returns the component that should be given focus after the specified one
  18919. when moving "forwards".
  18920. The default implementation will return the next component which is to the
  18921. right of or below this one.
  18922. This may return 0 if there's no suitable candidate.
  18923. */
  18924. virtual Component* getNextComponent (Component* current);
  18925. /** Returns the component that should be given focus after the specified one
  18926. when moving "backwards".
  18927. The default implementation will return the next component which is to the
  18928. left of or above this one.
  18929. This may return 0 if there's no suitable candidate.
  18930. */
  18931. virtual Component* getPreviousComponent (Component* current);
  18932. /** Returns the component that should receive focus be default within the given
  18933. parent component.
  18934. The default implementation will just return the foremost child component that
  18935. wants focus.
  18936. This may return 0 if there's no suitable candidate.
  18937. */
  18938. virtual Component* getDefaultComponent (Component* parentComponent);
  18939. };
  18940. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18941. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  18942. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  18943. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18944. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18945. /*** Start of inlined file: juce_Graphics.h ***/
  18946. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  18947. #define __JUCE_GRAPHICS_JUCEHEADER__
  18948. /*** Start of inlined file: juce_Font.h ***/
  18949. #ifndef __JUCE_FONT_JUCEHEADER__
  18950. #define __JUCE_FONT_JUCEHEADER__
  18951. /*** Start of inlined file: juce_Typeface.h ***/
  18952. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  18953. #define __JUCE_TYPEFACE_JUCEHEADER__
  18954. /*** Start of inlined file: juce_Path.h ***/
  18955. #ifndef __JUCE_PATH_JUCEHEADER__
  18956. #define __JUCE_PATH_JUCEHEADER__
  18957. /*** Start of inlined file: juce_Line.h ***/
  18958. #ifndef __JUCE_LINE_JUCEHEADER__
  18959. #define __JUCE_LINE_JUCEHEADER__
  18960. /**
  18961. Represents a line.
  18962. This class contains a bunch of useful methods for various geometric
  18963. tasks.
  18964. The ValueType template parameter should be a primitive type - float or double
  18965. are what it's designed for. Integer types will work in a basic way, but some methods
  18966. that perform mathematical operations may not compile, or they may not produce
  18967. sensible results.
  18968. @see Point, Rectangle, Path, Graphics::drawLine
  18969. */
  18970. template <typename ValueType>
  18971. class Line
  18972. {
  18973. public:
  18974. /** Creates a line, using (0, 0) as its start and end points. */
  18975. Line() throw() {}
  18976. /** Creates a copy of another line. */
  18977. Line (const Line& other) throw()
  18978. : start (other.start),
  18979. end (other.end)
  18980. {
  18981. }
  18982. /** Creates a line based on the co-ordinates of its start and end points. */
  18983. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  18984. : start (startX, startY),
  18985. end (endX, endY)
  18986. {
  18987. }
  18988. /** Creates a line from its start and end points. */
  18989. Line (const Point<ValueType>& startPoint,
  18990. const Point<ValueType>& endPoint) throw()
  18991. : start (startPoint),
  18992. end (endPoint)
  18993. {
  18994. }
  18995. /** Copies a line from another one. */
  18996. Line& operator= (const Line& other) throw()
  18997. {
  18998. start = other.start;
  18999. end = other.end;
  19000. return *this;
  19001. }
  19002. /** Destructor. */
  19003. ~Line() throw() {}
  19004. /** Returns the x co-ordinate of the line's start point. */
  19005. inline ValueType getStartX() const throw() { return start.getX(); }
  19006. /** Returns the y co-ordinate of the line's start point. */
  19007. inline ValueType getStartY() const throw() { return start.getY(); }
  19008. /** Returns the x co-ordinate of the line's end point. */
  19009. inline ValueType getEndX() const throw() { return end.getX(); }
  19010. /** Returns the y co-ordinate of the line's end point. */
  19011. inline ValueType getEndY() const throw() { return end.getY(); }
  19012. /** Returns the line's start point. */
  19013. inline const Point<ValueType>& getStart() const throw() { return start; }
  19014. /** Returns the line's end point. */
  19015. inline const Point<ValueType>& getEnd() const throw() { return end; }
  19016. /** Changes this line's start point */
  19017. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  19018. /** Changes this line's end point */
  19019. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  19020. /** Changes this line's start point */
  19021. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  19022. /** Changes this line's end point */
  19023. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  19024. /** Returns a line that is the same as this one, but with the start and end reversed, */
  19025. const Line reversed() const throw() { return Line (end, start); }
  19026. /** Applies an affine transform to the line's start and end points. */
  19027. void applyTransform (const AffineTransform& transform) throw()
  19028. {
  19029. start.applyTransform (transform);
  19030. end.applyTransform (transform);
  19031. }
  19032. /** Returns the length of the line. */
  19033. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  19034. /** Returns true if the line's start and end x co-ordinates are the same. */
  19035. bool isVertical() const throw() { return start.getX() == end.getX(); }
  19036. /** Returns true if the line's start and end y co-ordinates are the same. */
  19037. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  19038. /** Returns the line's angle.
  19039. This value is the number of radians clockwise from the 3 o'clock direction,
  19040. where the line's start point is considered to be at the centre.
  19041. */
  19042. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  19043. /** Compares two lines. */
  19044. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  19045. /** Compares two lines. */
  19046. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  19047. /** Finds the intersection between two lines.
  19048. @param line the other line
  19049. @param intersection the position of the point where the lines meet (or
  19050. where they would meet if they were infinitely long)
  19051. the intersection (if the lines intersect). If the lines
  19052. are parallel, this will just be set to the position
  19053. of one of the line's endpoints.
  19054. @returns true if the line segments intersect; false if they dont. Even if they
  19055. don't intersect, the intersection co-ordinates returned will still
  19056. be valid
  19057. */
  19058. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  19059. {
  19060. return findIntersection (start, end, line.start, line.end, intersection);
  19061. }
  19062. /** Finds the intersection between two lines.
  19063. @param line the line to intersect with
  19064. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  19065. */
  19066. const Point<ValueType> getIntersection (const Line& line) const throw()
  19067. {
  19068. Point<ValueType> p;
  19069. findIntersection (start, end, line.start, line.end, p);
  19070. return p;
  19071. }
  19072. /** Returns the location of the point which is a given distance along this line.
  19073. @param distanceFromStart the distance to move along the line from its
  19074. start point. This value can be negative or longer
  19075. than the line itself
  19076. @see getPointAlongLineProportionally
  19077. */
  19078. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  19079. {
  19080. return start + (end - start) * (distanceFromStart / getLength());
  19081. }
  19082. /** Returns a point which is a certain distance along and to the side of this line.
  19083. This effectively moves a given distance along the line, then another distance
  19084. perpendicularly to this, and returns the resulting position.
  19085. @param distanceFromStart the distance to move along the line from its
  19086. start point. This value can be negative or longer
  19087. than the line itself
  19088. @param perpendicularDistance how far to move sideways from the line. If you're
  19089. looking along the line from its start towards its
  19090. end, then a positive value here will move to the
  19091. right, negative value move to the left.
  19092. */
  19093. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  19094. ValueType perpendicularDistance) const throw()
  19095. {
  19096. const Point<ValueType> delta (end - start);
  19097. const double length = juce_hypot ((double) delta.getX(),
  19098. (double) delta.getY());
  19099. if (length <= 0)
  19100. return start;
  19101. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  19102. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  19103. }
  19104. /** Returns the location of the point which is a given distance along this line
  19105. proportional to the line's length.
  19106. @param proportionOfLength the distance to move along the line from its
  19107. start point, in multiples of the line's length.
  19108. So a value of 0.0 will return the line's start point
  19109. and a value of 1.0 will return its end point. (This value
  19110. can be negative or greater than 1.0).
  19111. @see getPointAlongLine
  19112. */
  19113. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  19114. {
  19115. return start + (end - start) * proportionOfLength;
  19116. }
  19117. /** Returns the smallest distance between this line segment and a given point.
  19118. So if the point is close to the line, this will return the perpendicular
  19119. distance from the line; if the point is a long way beyond one of the line's
  19120. end-point's, it'll return the straight-line distance to the nearest end-point.
  19121. pointOnLine receives the position of the point that is found.
  19122. @returns the point's distance from the line
  19123. @see getPositionAlongLineOfNearestPoint
  19124. */
  19125. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  19126. Point<ValueType>& pointOnLine) const throw()
  19127. {
  19128. const Point<ValueType> delta (end - start);
  19129. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  19130. if (length > 0)
  19131. {
  19132. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  19133. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  19134. if (prop >= 0 && prop <= 1.0)
  19135. {
  19136. pointOnLine = start + delta * (ValueType) prop;
  19137. return targetPoint.getDistanceFrom (pointOnLine);
  19138. }
  19139. }
  19140. const float fromStart = targetPoint.getDistanceFrom (start);
  19141. const float fromEnd = targetPoint.getDistanceFrom (end);
  19142. if (fromStart < fromEnd)
  19143. {
  19144. pointOnLine = start;
  19145. return fromStart;
  19146. }
  19147. else
  19148. {
  19149. pointOnLine = end;
  19150. return fromEnd;
  19151. }
  19152. }
  19153. /** Finds the point on this line which is nearest to a given point, and
  19154. returns its position as a proportional position along the line.
  19155. @returns a value 0 to 1.0 which is the distance along this line from the
  19156. line's start to the point which is nearest to the point passed-in. To
  19157. turn this number into a position, use getPointAlongLineProportionally().
  19158. @see getDistanceFromPoint, getPointAlongLineProportionally
  19159. */
  19160. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  19161. {
  19162. const Point<ValueType> delta (end - start);
  19163. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  19164. return length <= 0 ? 0
  19165. : jlimit ((ValueType) 0, (ValueType) 1,
  19166. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  19167. + (point.getY() - start.getY()) * delta.getY()) / length));
  19168. }
  19169. /** Finds the point on this line which is nearest to a given point.
  19170. @see getDistanceFromPoint, findNearestProportionalPositionTo
  19171. */
  19172. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  19173. {
  19174. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  19175. }
  19176. /** Returns true if the given point lies above this line.
  19177. The return value is true if the point's y coordinate is less than the y
  19178. coordinate of this line at the given x (assuming the line extends infinitely
  19179. in both directions).
  19180. */
  19181. bool isPointAbove (const Point<ValueType>& point) const throw()
  19182. {
  19183. return start.getX() != end.getX()
  19184. && point.getY() < ((end.getY() - start.getY())
  19185. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  19186. }
  19187. /** Returns a shortened copy of this line.
  19188. This will chop off part of the start of this line by a certain amount, (leaving the
  19189. end-point the same), and return the new line.
  19190. */
  19191. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  19192. {
  19193. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  19194. }
  19195. /** Returns a shortened copy of this line.
  19196. This will chop off part of the end of this line by a certain amount, (leaving the
  19197. start-point the same), and return the new line.
  19198. */
  19199. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  19200. {
  19201. const ValueType length = getLength();
  19202. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  19203. }
  19204. private:
  19205. Point<ValueType> start, end;
  19206. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  19207. const Point<ValueType>& p3, const Point<ValueType>& p4,
  19208. Point<ValueType>& intersection) throw()
  19209. {
  19210. if (p2 == p3)
  19211. {
  19212. intersection = p2;
  19213. return true;
  19214. }
  19215. const Point<ValueType> d1 (p2 - p1);
  19216. const Point<ValueType> d2 (p4 - p3);
  19217. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  19218. if (divisor == 0)
  19219. {
  19220. if (! (d1.isOrigin() || d2.isOrigin()))
  19221. {
  19222. if (d1.getY() == 0 && d2.getY() != 0)
  19223. {
  19224. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  19225. intersection = p1.withX (p3.getX() + along * d2.getX());
  19226. return along >= 0 && along <= (ValueType) 1;
  19227. }
  19228. else if (d2.getY() == 0 && d1.getY() != 0)
  19229. {
  19230. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  19231. intersection = p3.withX (p1.getX() + along * d1.getX());
  19232. return along >= 0 && along <= (ValueType) 1;
  19233. }
  19234. else if (d1.getX() == 0 && d2.getX() != 0)
  19235. {
  19236. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  19237. intersection = p1.withY (p3.getY() + along * d2.getY());
  19238. return along >= 0 && along <= (ValueType) 1;
  19239. }
  19240. else if (d2.getX() == 0 && d1.getX() != 0)
  19241. {
  19242. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  19243. intersection = p3.withY (p1.getY() + along * d1.getY());
  19244. return along >= 0 && along <= (ValueType) 1;
  19245. }
  19246. }
  19247. intersection = (p2 + p3) / (ValueType) 2;
  19248. return false;
  19249. }
  19250. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  19251. intersection = p1 + d1 * along1;
  19252. if (along1 < 0 || along1 > (ValueType) 1)
  19253. return false;
  19254. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  19255. return along2 >= 0 && along2 <= (ValueType) 1;
  19256. }
  19257. };
  19258. #endif // __JUCE_LINE_JUCEHEADER__
  19259. /*** End of inlined file: juce_Line.h ***/
  19260. /*** Start of inlined file: juce_Rectangle.h ***/
  19261. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  19262. #define __JUCE_RECTANGLE_JUCEHEADER__
  19263. class RectangleList;
  19264. /**
  19265. Manages a rectangle and allows geometric operations to be performed on it.
  19266. @see RectangleList, Path, Line, Point
  19267. */
  19268. template <typename ValueType>
  19269. class Rectangle
  19270. {
  19271. public:
  19272. /** Creates a rectangle of zero size.
  19273. The default co-ordinates will be (0, 0, 0, 0).
  19274. */
  19275. Rectangle() throw()
  19276. : x(), y(), w(), h()
  19277. {
  19278. }
  19279. /** Creates a copy of another rectangle. */
  19280. Rectangle (const Rectangle& other) throw()
  19281. : x (other.x), y (other.y),
  19282. w (other.w), h (other.h)
  19283. {
  19284. }
  19285. /** Creates a rectangle with a given position and size. */
  19286. Rectangle (const ValueType initialX, const ValueType initialY,
  19287. const ValueType width, const ValueType height) throw()
  19288. : x (initialX), y (initialY),
  19289. w (width), h (height)
  19290. {
  19291. }
  19292. /** Creates a rectangle with a given size, and a position of (0, 0). */
  19293. Rectangle (const ValueType width, const ValueType height) throw()
  19294. : x(), y(), w (width), h (height)
  19295. {
  19296. }
  19297. /** Creates a Rectangle from the positions of two opposite corners. */
  19298. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  19299. : x (jmin (corner1.getX(), corner2.getX())),
  19300. y (jmin (corner1.getY(), corner2.getY())),
  19301. w (corner1.getX() - corner2.getX()),
  19302. h (corner1.getY() - corner2.getY())
  19303. {
  19304. if (w < ValueType()) w = -w;
  19305. if (h < ValueType()) h = -h;
  19306. }
  19307. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  19308. The right and bottom values must be larger than the left and top ones, or the resulting
  19309. rectangle will have a negative size.
  19310. */
  19311. static const Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  19312. const ValueType right, const ValueType bottom) throw()
  19313. {
  19314. return Rectangle (left, top, right - left, bottom - top);
  19315. }
  19316. Rectangle& operator= (const Rectangle& other) throw()
  19317. {
  19318. x = other.x; y = other.y;
  19319. w = other.w; h = other.h;
  19320. return *this;
  19321. }
  19322. /** Destructor. */
  19323. ~Rectangle() throw() {}
  19324. /** Returns true if the rectangle's width and height are both zero or less */
  19325. bool isEmpty() const throw() { return w <= ValueType() || h <= ValueType(); }
  19326. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  19327. inline ValueType getX() const throw() { return x; }
  19328. /** Returns the y co-ordinate of the rectangle's top edge. */
  19329. inline ValueType getY() const throw() { return y; }
  19330. /** Returns the width of the rectangle. */
  19331. inline ValueType getWidth() const throw() { return w; }
  19332. /** Returns the height of the rectangle. */
  19333. inline ValueType getHeight() const throw() { return h; }
  19334. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  19335. inline ValueType getRight() const throw() { return x + w; }
  19336. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  19337. inline ValueType getBottom() const throw() { return y + h; }
  19338. /** Returns the x co-ordinate of the rectangle's centre. */
  19339. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  19340. /** Returns the y co-ordinate of the rectangle's centre. */
  19341. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  19342. /** Returns the centre point of the rectangle. */
  19343. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  19344. /** Returns the aspect ratio of the rectangle's width / height.
  19345. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  19346. it returns height / width. */
  19347. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  19348. /** Returns the rectangle's top-left position as a Point. */
  19349. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  19350. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19351. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  19352. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  19353. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  19354. /** Returns a rectangle with the same size as this one, but a new position. */
  19355. const Rectangle withPosition (const ValueType newX, const ValueType newY) const throw() { return Rectangle (newX, newY, w, h); }
  19356. /** Returns a rectangle with the same size as this one, but a new position. */
  19357. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  19358. /** Returns the rectangle's top-left position as a Point. */
  19359. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  19360. /** Returns the rectangle's top-right position as a Point. */
  19361. const Point<ValueType> getTopRight() const throw() { return Point<ValueType> (x + w, y); }
  19362. /** Returns the rectangle's bottom-left position as a Point. */
  19363. const Point<ValueType> getBottomLeft() const throw() { return Point<ValueType> (x, y + h); }
  19364. /** Returns the rectangle's bottom-right position as a Point. */
  19365. const Point<ValueType> getBottomRight() const throw() { return Point<ValueType> (x + w, y + h); }
  19366. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  19367. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  19368. /** Returns a rectangle with the same position as this one, but a new size. */
  19369. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  19370. /** Changes all the rectangle's co-ordinates. */
  19371. void setBounds (const ValueType newX, const ValueType newY,
  19372. const ValueType newWidth, const ValueType newHeight) throw()
  19373. {
  19374. x = newX; y = newY; w = newWidth; h = newHeight;
  19375. }
  19376. /** Changes the rectangle's X coordinate */
  19377. void setX (const ValueType newX) throw() { x = newX; }
  19378. /** Changes the rectangle's Y coordinate */
  19379. void setY (const ValueType newY) throw() { y = newY; }
  19380. /** Changes the rectangle's width */
  19381. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  19382. /** Changes the rectangle's height */
  19383. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  19384. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  19385. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  19386. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  19387. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  19388. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  19389. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  19390. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  19391. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  19392. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  19393. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  19394. @see withLeft
  19395. */
  19396. void setLeft (const ValueType newLeft) throw()
  19397. {
  19398. w = jmax (ValueType(), x + w - newLeft);
  19399. x = newLeft;
  19400. }
  19401. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  19402. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  19403. @see setLeft
  19404. */
  19405. const Rectangle withLeft (const ValueType newLeft) const throw() { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  19406. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  19407. If the y is moved to be below the current bottom edge, the height will be set to zero.
  19408. @see withTop
  19409. */
  19410. void setTop (const ValueType newTop) throw()
  19411. {
  19412. h = jmax (ValueType(), y + h - newTop);
  19413. y = newTop;
  19414. }
  19415. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  19416. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19417. @see setTop
  19418. */
  19419. const Rectangle withTop (const ValueType newTop) const throw() { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  19420. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  19421. If the new right is below the current X value, the X will be pushed down to match it.
  19422. @see getRight, withRight
  19423. */
  19424. void setRight (const ValueType newRight) throw()
  19425. {
  19426. x = jmin (x, newRight);
  19427. w = newRight - x;
  19428. }
  19429. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  19430. If the new right edge is below the current left-hand edge, the width will be set to zero.
  19431. @see setRight
  19432. */
  19433. const Rectangle withRight (const ValueType newRight) const throw() { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  19434. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  19435. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  19436. @see getBottom, withBottom
  19437. */
  19438. void setBottom (const ValueType newBottom) throw()
  19439. {
  19440. y = jmin (y, newBottom);
  19441. h = newBottom - y;
  19442. }
  19443. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  19444. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  19445. @see setBottom
  19446. */
  19447. const Rectangle withBottom (const ValueType newBottom) const throw() { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  19448. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  19449. void translate (const ValueType deltaX,
  19450. const ValueType deltaY) throw()
  19451. {
  19452. x += deltaX;
  19453. y += deltaY;
  19454. }
  19455. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19456. const Rectangle translated (const ValueType deltaX,
  19457. const ValueType deltaY) const throw()
  19458. {
  19459. return Rectangle (x + deltaX, y + deltaY, w, h);
  19460. }
  19461. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19462. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  19463. {
  19464. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  19465. }
  19466. /** Moves this rectangle by a given amount. */
  19467. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  19468. {
  19469. x += deltaPosition.getX(); y += deltaPosition.getY();
  19470. return *this;
  19471. }
  19472. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19473. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  19474. {
  19475. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  19476. }
  19477. /** Moves this rectangle by a given amount. */
  19478. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  19479. {
  19480. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  19481. return *this;
  19482. }
  19483. /** Expands the rectangle by a given amount.
  19484. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19485. @see expanded, reduce, reduced
  19486. */
  19487. void expand (const ValueType deltaX,
  19488. const ValueType deltaY) throw()
  19489. {
  19490. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19491. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19492. setBounds (x - deltaX, y - deltaY, nw, nh);
  19493. }
  19494. /** Returns a rectangle that is larger than this one by a given amount.
  19495. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19496. @see expand, reduce, reduced
  19497. */
  19498. const Rectangle expanded (const ValueType deltaX,
  19499. const ValueType deltaY) const throw()
  19500. {
  19501. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19502. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19503. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  19504. }
  19505. /** Shrinks the rectangle by a given amount.
  19506. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19507. @see reduced, expand, expanded
  19508. */
  19509. void reduce (const ValueType deltaX,
  19510. const ValueType deltaY) throw()
  19511. {
  19512. expand (-deltaX, -deltaY);
  19513. }
  19514. /** Returns a rectangle that is smaller than this one by a given amount.
  19515. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19516. @see reduce, expand, expanded
  19517. */
  19518. const Rectangle reduced (const ValueType deltaX,
  19519. const ValueType deltaY) const throw()
  19520. {
  19521. return expanded (-deltaX, -deltaY);
  19522. }
  19523. /** Removes a strip from the top of this rectangle, reducing this rectangle
  19524. by the specified amount and returning the section that was removed.
  19525. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19526. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  19527. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19528. that value.
  19529. */
  19530. const Rectangle removeFromTop (const ValueType amountToRemove) throw()
  19531. {
  19532. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  19533. y += r.h; h -= r.h;
  19534. return r;
  19535. }
  19536. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  19537. by the specified amount and returning the section that was removed.
  19538. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19539. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  19540. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19541. that value.
  19542. */
  19543. const Rectangle removeFromLeft (const ValueType amountToRemove) throw()
  19544. {
  19545. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  19546. x += r.w; w -= r.w;
  19547. return r;
  19548. }
  19549. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  19550. by the specified amount and returning the section that was removed.
  19551. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19552. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  19553. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19554. that value.
  19555. */
  19556. const Rectangle removeFromRight (ValueType amountToRemove) throw()
  19557. {
  19558. amountToRemove = jmin (amountToRemove, w);
  19559. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  19560. w -= amountToRemove;
  19561. return r;
  19562. }
  19563. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  19564. by the specified amount and returning the section that was removed.
  19565. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19566. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  19567. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19568. that value.
  19569. */
  19570. const Rectangle removeFromBottom (ValueType amountToRemove) throw()
  19571. {
  19572. amountToRemove = jmin (amountToRemove, h);
  19573. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  19574. h -= amountToRemove;
  19575. return r;
  19576. }
  19577. /** Returns true if the two rectangles are identical. */
  19578. bool operator== (const Rectangle& other) const throw()
  19579. {
  19580. return x == other.x && y == other.y
  19581. && w == other.w && h == other.h;
  19582. }
  19583. /** Returns true if the two rectangles are not identical. */
  19584. bool operator!= (const Rectangle& other) const throw()
  19585. {
  19586. return x != other.x || y != other.y
  19587. || w != other.w || h != other.h;
  19588. }
  19589. /** Returns true if this co-ordinate is inside the rectangle. */
  19590. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  19591. {
  19592. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  19593. }
  19594. /** Returns true if this co-ordinate is inside the rectangle. */
  19595. bool contains (const Point<ValueType>& point) const throw()
  19596. {
  19597. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  19598. }
  19599. /** Returns true if this other rectangle is completely inside this one. */
  19600. bool contains (const Rectangle& other) const throw()
  19601. {
  19602. return x <= other.x && y <= other.y
  19603. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  19604. }
  19605. /** Returns the nearest point to the specified point that lies within this rectangle. */
  19606. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  19607. {
  19608. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  19609. jlimit (y, y + h, point.getY()));
  19610. }
  19611. /** Returns true if any part of another rectangle overlaps this one. */
  19612. bool intersects (const Rectangle& other) const throw()
  19613. {
  19614. return x + w > other.x
  19615. && y + h > other.y
  19616. && x < other.x + other.w
  19617. && y < other.y + other.h
  19618. && w > ValueType() && h > ValueType();
  19619. }
  19620. /** Returns the region that is the overlap between this and another rectangle.
  19621. If the two rectangles don't overlap, the rectangle returned will be empty.
  19622. */
  19623. const Rectangle getIntersection (const Rectangle& other) const throw()
  19624. {
  19625. const ValueType nx = jmax (x, other.x);
  19626. const ValueType ny = jmax (y, other.y);
  19627. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  19628. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  19629. if (nw >= ValueType() && nh >= ValueType())
  19630. return Rectangle (nx, ny, nw, nh);
  19631. return Rectangle();
  19632. }
  19633. /** Clips a rectangle so that it lies only within this one.
  19634. This is a non-static version of intersectRectangles().
  19635. Returns false if the two regions didn't overlap.
  19636. */
  19637. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  19638. {
  19639. const int maxX = jmax (otherX, x);
  19640. otherW = jmin (otherX + otherW, x + w) - maxX;
  19641. if (otherW > ValueType())
  19642. {
  19643. const int maxY = jmax (otherY, y);
  19644. otherH = jmin (otherY + otherH, y + h) - maxY;
  19645. if (otherH > ValueType())
  19646. {
  19647. otherX = maxX; otherY = maxY;
  19648. return true;
  19649. }
  19650. }
  19651. return false;
  19652. }
  19653. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  19654. If either this or the other rectangle are empty, they will not be counted as
  19655. part of the resulting region.
  19656. */
  19657. const Rectangle getUnion (const Rectangle& other) const throw()
  19658. {
  19659. if (other.isEmpty()) return *this;
  19660. if (isEmpty()) return other;
  19661. const ValueType newX = jmin (x, other.x);
  19662. const ValueType newY = jmin (y, other.y);
  19663. return Rectangle (newX, newY,
  19664. jmax (x + w, other.x + other.w) - newX,
  19665. jmax (y + h, other.y + other.h) - newY);
  19666. }
  19667. /** If this rectangle merged with another one results in a simple rectangle, this
  19668. will set this rectangle to the result, and return true.
  19669. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19670. or if they form a complex region.
  19671. */
  19672. bool enlargeIfAdjacent (const Rectangle& other) throw()
  19673. {
  19674. if (x == other.x && getRight() == other.getRight()
  19675. && (other.getBottom() >= y && other.y <= getBottom()))
  19676. {
  19677. const ValueType newY = jmin (y, other.y);
  19678. h = jmax (getBottom(), other.getBottom()) - newY;
  19679. y = newY;
  19680. return true;
  19681. }
  19682. else if (y == other.y && getBottom() == other.getBottom()
  19683. && (other.getRight() >= x && other.x <= getRight()))
  19684. {
  19685. const ValueType newX = jmin (x, other.x);
  19686. w = jmax (getRight(), other.getRight()) - newX;
  19687. x = newX;
  19688. return true;
  19689. }
  19690. return false;
  19691. }
  19692. /** If after removing another rectangle from this one the result is a simple rectangle,
  19693. this will set this object's bounds to be the result, and return true.
  19694. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19695. or if removing the other one would form a complex region.
  19696. */
  19697. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  19698. {
  19699. int inside = 0;
  19700. const int otherR = other.getRight();
  19701. if (x >= other.x && x < otherR) inside = 1;
  19702. const int otherB = other.getBottom();
  19703. if (y >= other.y && y < otherB) inside |= 2;
  19704. const int r = x + w;
  19705. if (r >= other.x && r < otherR) inside |= 4;
  19706. const int b = y + h;
  19707. if (b >= other.y && b < otherB) inside |= 8;
  19708. switch (inside)
  19709. {
  19710. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  19711. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  19712. case 2 + 4 + 8: w = other.x - x; return true;
  19713. case 1 + 4 + 8: h = other.y - y; return true;
  19714. }
  19715. return false;
  19716. }
  19717. /** Returns the smallest rectangle that can contain the shape created by applying
  19718. a transform to this rectangle.
  19719. This should only be used on floating point rectangles.
  19720. */
  19721. const Rectangle transformed (const AffineTransform& transform) const throw()
  19722. {
  19723. float x1 = x, y1 = y;
  19724. float x2 = x + w, y2 = y;
  19725. float x3 = x, y3 = y + h;
  19726. float x4 = x2, y4 = y3;
  19727. transform.transformPoints (x1, y1, x2, y2);
  19728. transform.transformPoints (x3, y3, x4, y4);
  19729. const float rx = jmin (x1, x2, x3, x4);
  19730. const float ry = jmin (y1, y2, y3, y4);
  19731. return Rectangle (rx, ry,
  19732. jmax (x1, x2, x3, x4) - rx,
  19733. jmax (y1, y2, y3, y4) - ry);
  19734. }
  19735. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  19736. This is only relevent for floating-point rectangles, of course.
  19737. @see toFloat()
  19738. */
  19739. const Rectangle<int> getSmallestIntegerContainer() const throw()
  19740. {
  19741. const int x1 = (int) std::floor (static_cast<float> (x));
  19742. const int y1 = (int) std::floor (static_cast<float> (y));
  19743. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  19744. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  19745. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  19746. }
  19747. /** Returns the smallest Rectangle that can contain a set of points. */
  19748. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  19749. {
  19750. if (numPoints == 0)
  19751. return Rectangle();
  19752. ValueType minX (points[0].getX());
  19753. ValueType maxX (minX);
  19754. ValueType minY (points[0].getY());
  19755. ValueType maxY (minY);
  19756. for (int i = 1; i < numPoints; ++i)
  19757. {
  19758. minX = jmin (minX, points[i].getX());
  19759. maxX = jmax (maxX, points[i].getX());
  19760. minY = jmin (minY, points[i].getY());
  19761. maxY = jmax (maxY, points[i].getY());
  19762. }
  19763. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  19764. }
  19765. /** Casts this rectangle to a Rectangle<float>.
  19766. Obviously this is mainly useful for rectangles that use integer types.
  19767. @see getSmallestIntegerContainer
  19768. */
  19769. const Rectangle<float> toFloat() const throw()
  19770. {
  19771. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  19772. static_cast<float> (w), static_cast<float> (h));
  19773. }
  19774. /** Static utility to intersect two sets of rectangular co-ordinates.
  19775. Returns false if the two regions didn't overlap.
  19776. @see intersectRectangle
  19777. */
  19778. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  19779. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  19780. {
  19781. const ValueType x = jmax (x1, x2);
  19782. w1 = jmin (x1 + w1, x2 + w2) - x;
  19783. if (w1 > ValueType())
  19784. {
  19785. const ValueType y = jmax (y1, y2);
  19786. h1 = jmin (y1 + h1, y2 + h2) - y;
  19787. if (h1 > ValueType())
  19788. {
  19789. x1 = x; y1 = y;
  19790. return true;
  19791. }
  19792. }
  19793. return false;
  19794. }
  19795. /** Creates a string describing this rectangle.
  19796. The string will be of the form "x y width height", e.g. "100 100 400 200".
  19797. Coupled with the fromString() method, this is very handy for things like
  19798. storing rectangles (particularly component positions) in XML attributes.
  19799. @see fromString
  19800. */
  19801. const String toString() const
  19802. {
  19803. String s;
  19804. s.preallocateBytes (32);
  19805. s << x << ' ' << y << ' ' << w << ' ' << h;
  19806. return s;
  19807. }
  19808. /** Parses a string containing a rectangle's details.
  19809. The string should contain 4 integer tokens, in the form "x y width height". They
  19810. can be comma or whitespace separated.
  19811. This method is intended to go with the toString() method, to form an easy way
  19812. of saving/loading rectangles as strings.
  19813. @see toString
  19814. */
  19815. static const Rectangle fromString (const String& stringVersion)
  19816. {
  19817. StringArray toks;
  19818. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  19819. return Rectangle (toks[0].trim().getIntValue(),
  19820. toks[1].trim().getIntValue(),
  19821. toks[2].trim().getIntValue(),
  19822. toks[3].trim().getIntValue());
  19823. }
  19824. private:
  19825. friend class RectangleList;
  19826. ValueType x, y, w, h;
  19827. };
  19828. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  19829. /*** End of inlined file: juce_Rectangle.h ***/
  19830. /*** Start of inlined file: juce_Justification.h ***/
  19831. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  19832. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  19833. /**
  19834. Represents a type of justification to be used when positioning graphical items.
  19835. e.g. it indicates whether something should be placed top-left, top-right,
  19836. centred, etc.
  19837. It is used in various places wherever this kind of information is needed.
  19838. */
  19839. class JUCE_API Justification
  19840. {
  19841. public:
  19842. /** Creates a Justification object using a combination of flags. */
  19843. inline Justification (int flags_) throw() : flags (flags_) {}
  19844. /** Creates a copy of another Justification object. */
  19845. Justification (const Justification& other) throw();
  19846. /** Copies another Justification object. */
  19847. Justification& operator= (const Justification& other) throw();
  19848. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  19849. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  19850. /** Returns the raw flags that are set for this Justification object. */
  19851. inline int getFlags() const throw() { return flags; }
  19852. /** Tests a set of flags for this object.
  19853. @returns true if any of the flags passed in are set on this object.
  19854. */
  19855. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  19856. /** Returns just the flags from this object that deal with vertical layout. */
  19857. int getOnlyVerticalFlags() const throw();
  19858. /** Returns just the flags from this object that deal with horizontal layout. */
  19859. int getOnlyHorizontalFlags() const throw();
  19860. /** Adjusts the position of a rectangle to fit it into a space.
  19861. The (x, y) position of the rectangle will be updated to position it inside the
  19862. given space according to the justification flags.
  19863. */
  19864. template <typename ValueType>
  19865. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  19866. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const throw()
  19867. {
  19868. x = spaceX;
  19869. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  19870. else if ((flags & right) != 0) x += spaceW - w;
  19871. y = spaceY;
  19872. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  19873. else if ((flags & bottom) != 0) y += spaceH - h;
  19874. }
  19875. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  19876. */
  19877. template <typename ValueType>
  19878. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  19879. const Rectangle<ValueType>& targetSpace) const throw()
  19880. {
  19881. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  19882. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  19883. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  19884. return areaToAdjust.withPosition (x, y);
  19885. }
  19886. /** Flag values that can be combined and used in the constructor. */
  19887. enum
  19888. {
  19889. /** Indicates that the item should be aligned against the left edge of the available space. */
  19890. left = 1,
  19891. /** Indicates that the item should be aligned against the right edge of the available space. */
  19892. right = 2,
  19893. /** Indicates that the item should be placed in the centre between the left and right
  19894. sides of the available space. */
  19895. horizontallyCentred = 4,
  19896. /** Indicates that the item should be aligned against the top edge of the available space. */
  19897. top = 8,
  19898. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  19899. bottom = 16,
  19900. /** Indicates that the item should be placed in the centre between the top and bottom
  19901. sides of the available space. */
  19902. verticallyCentred = 32,
  19903. /** Indicates that lines of text should be spread out to fill the maximum width
  19904. available, so that both margins are aligned vertically.
  19905. */
  19906. horizontallyJustified = 64,
  19907. /** Indicates that the item should be centred vertically and horizontally.
  19908. This is equivalent to (horizontallyCentred | verticallyCentred)
  19909. */
  19910. centred = 36,
  19911. /** Indicates that the item should be centred vertically but placed on the left hand side.
  19912. This is equivalent to (left | verticallyCentred)
  19913. */
  19914. centredLeft = 33,
  19915. /** Indicates that the item should be centred vertically but placed on the right hand side.
  19916. This is equivalent to (right | verticallyCentred)
  19917. */
  19918. centredRight = 34,
  19919. /** Indicates that the item should be centred horizontally and placed at the top.
  19920. This is equivalent to (horizontallyCentred | top)
  19921. */
  19922. centredTop = 12,
  19923. /** Indicates that the item should be centred horizontally and placed at the bottom.
  19924. This is equivalent to (horizontallyCentred | bottom)
  19925. */
  19926. centredBottom = 20,
  19927. /** Indicates that the item should be placed in the top-left corner.
  19928. This is equivalent to (left | top)
  19929. */
  19930. topLeft = 9,
  19931. /** Indicates that the item should be placed in the top-right corner.
  19932. This is equivalent to (right | top)
  19933. */
  19934. topRight = 10,
  19935. /** Indicates that the item should be placed in the bottom-left corner.
  19936. This is equivalent to (left | bottom)
  19937. */
  19938. bottomLeft = 17,
  19939. /** Indicates that the item should be placed in the bottom-left corner.
  19940. This is equivalent to (right | bottom)
  19941. */
  19942. bottomRight = 18
  19943. };
  19944. private:
  19945. int flags;
  19946. };
  19947. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  19948. /*** End of inlined file: juce_Justification.h ***/
  19949. class Image;
  19950. /**
  19951. A path is a sequence of lines and curves that may either form a closed shape
  19952. or be open-ended.
  19953. To use a path, you can create an empty one, then add lines and curves to it
  19954. to create shapes, then it can be rendered by a Graphics context or used
  19955. for geometric operations.
  19956. e.g. @code
  19957. Path myPath;
  19958. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  19959. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  19960. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  19961. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  19962. // add an ellipse as well, which will form a second sub-path within the path..
  19963. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  19964. // double the width of the whole thing..
  19965. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  19966. // and draw it to a graphics context with a 5-pixel thick outline.
  19967. g.strokePath (myPath, PathStrokeType (5.0f));
  19968. @endcode
  19969. A path object can actually contain multiple sub-paths, which may themselves
  19970. be open or closed.
  19971. @see PathFlatteningIterator, PathStrokeType, Graphics
  19972. */
  19973. class JUCE_API Path
  19974. {
  19975. public:
  19976. /** Creates an empty path. */
  19977. Path();
  19978. /** Creates a copy of another path. */
  19979. Path (const Path& other);
  19980. /** Destructor. */
  19981. ~Path();
  19982. /** Copies this path from another one. */
  19983. Path& operator= (const Path& other);
  19984. bool operator== (const Path& other) const throw();
  19985. bool operator!= (const Path& other) const throw();
  19986. /** Returns true if the path doesn't contain any lines or curves. */
  19987. bool isEmpty() const throw();
  19988. /** Returns the smallest rectangle that contains all points within the path.
  19989. */
  19990. const Rectangle<float> getBounds() const throw();
  19991. /** Returns the smallest rectangle that contains all points within the path
  19992. after it's been transformed with the given tranasform matrix.
  19993. */
  19994. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  19995. /** Checks whether a point lies within the path.
  19996. This is only relevent for closed paths (see closeSubPath()), and
  19997. may produce false results if used on a path which has open sub-paths.
  19998. The path's winding rule is taken into account by this method.
  19999. The tolerance parameter is the maximum error allowed when flattening the path,
  20000. so this method could return a false positive when your point is up to this distance
  20001. outside the path's boundary.
  20002. @see closeSubPath, setUsingNonZeroWinding
  20003. */
  20004. bool contains (float x, float y,
  20005. float tolerance = 1.0f) const;
  20006. /** Checks whether a point lies within the path.
  20007. This is only relevent for closed paths (see closeSubPath()), and
  20008. may produce false results if used on a path which has open sub-paths.
  20009. The path's winding rule is taken into account by this method.
  20010. The tolerance parameter is the maximum error allowed when flattening the path,
  20011. so this method could return a false positive when your point is up to this distance
  20012. outside the path's boundary.
  20013. @see closeSubPath, setUsingNonZeroWinding
  20014. */
  20015. bool contains (const Point<float>& point,
  20016. float tolerance = 1.0f) const;
  20017. /** Checks whether a line crosses the path.
  20018. This will return positive if the line crosses any of the paths constituent
  20019. lines or curves. It doesn't take into account whether the line is inside
  20020. or outside the path, or whether the path is open or closed.
  20021. The tolerance parameter is the maximum error allowed when flattening the path,
  20022. so this method could return a false positive when your point is up to this distance
  20023. outside the path's boundary.
  20024. */
  20025. bool intersectsLine (const Line<float>& line,
  20026. float tolerance = 1.0f);
  20027. /** Cuts off parts of a line to keep the parts that are either inside or
  20028. outside this path.
  20029. Note that this isn't smart enough to cope with situations where the
  20030. line would need to be cut into multiple pieces to correctly clip against
  20031. a re-entrant shape.
  20032. @param line the line to clip
  20033. @param keepSectionOutsidePath if true, it's the section outside the path
  20034. that will be kept; if false its the section inside
  20035. the path
  20036. */
  20037. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  20038. /** Returns the length of the path.
  20039. @see getPointAlongPath
  20040. */
  20041. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  20042. /** Returns a point that is the specified distance along the path.
  20043. If the distance is greater than the total length of the path, this will return the
  20044. end point.
  20045. @see getLength
  20046. */
  20047. const Point<float> getPointAlongPath (float distanceFromStart,
  20048. const AffineTransform& transform = AffineTransform::identity) const;
  20049. /** Finds the point along the path which is nearest to a given position.
  20050. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  20051. of the path.
  20052. */
  20053. float getNearestPoint (const Point<float>& targetPoint,
  20054. Point<float>& pointOnPath,
  20055. const AffineTransform& transform = AffineTransform::identity) const;
  20056. /** Removes all lines and curves, resetting the path completely. */
  20057. void clear() throw();
  20058. /** Begins a new subpath with a given starting position.
  20059. This will move the path's current position to the co-ordinates passed in and
  20060. make it ready to draw lines or curves starting from this position.
  20061. After adding whatever lines and curves are needed, you can either
  20062. close the current sub-path using closeSubPath() or call startNewSubPath()
  20063. to move to a new sub-path, leaving the old one open-ended.
  20064. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20065. */
  20066. void startNewSubPath (float startX, float startY);
  20067. /** Begins a new subpath with a given starting position.
  20068. This will move the path's current position to the co-ordinates passed in and
  20069. make it ready to draw lines or curves starting from this position.
  20070. After adding whatever lines and curves are needed, you can either
  20071. close the current sub-path using closeSubPath() or call startNewSubPath()
  20072. to move to a new sub-path, leaving the old one open-ended.
  20073. @see lineTo, quadraticTo, cubicTo, closeSubPath
  20074. */
  20075. void startNewSubPath (const Point<float>& start);
  20076. /** Closes a the current sub-path with a line back to its start-point.
  20077. When creating a closed shape such as a triangle, don't use 3 lineTo()
  20078. calls - instead use two lineTo() calls, followed by a closeSubPath()
  20079. to join the final point back to the start.
  20080. This ensures that closes shapes are recognised as such, and this is
  20081. important for tasks like drawing strokes, which needs to know whether to
  20082. draw end-caps or not.
  20083. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  20084. */
  20085. void closeSubPath();
  20086. /** Adds a line from the shape's last position to a new end-point.
  20087. This will connect the end-point of the last line or curve that was added
  20088. to a new point, using a straight line.
  20089. See the class description for an example of how to add lines and curves to a path.
  20090. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20091. */
  20092. void lineTo (float endX, float endY);
  20093. /** Adds a line from the shape's last position to a new end-point.
  20094. This will connect the end-point of the last line or curve that was added
  20095. to a new point, using a straight line.
  20096. See the class description for an example of how to add lines and curves to a path.
  20097. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  20098. */
  20099. void lineTo (const Point<float>& end);
  20100. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20101. This will connect the end-point of the last line or curve that was added
  20102. to a new point, using a quadratic spline with one control-point.
  20103. See the class description for an example of how to add lines and curves to a path.
  20104. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20105. */
  20106. void quadraticTo (float controlPointX,
  20107. float controlPointY,
  20108. float endPointX,
  20109. float endPointY);
  20110. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  20111. This will connect the end-point of the last line or curve that was added
  20112. to a new point, using a quadratic spline with one control-point.
  20113. See the class description for an example of how to add lines and curves to a path.
  20114. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  20115. */
  20116. void quadraticTo (const Point<float>& controlPoint,
  20117. const Point<float>& endPoint);
  20118. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20119. This will connect the end-point of the last line or curve that was added
  20120. to a new point, using a cubic spline with two control-points.
  20121. See the class description for an example of how to add lines and curves to a path.
  20122. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20123. */
  20124. void cubicTo (float controlPoint1X,
  20125. float controlPoint1Y,
  20126. float controlPoint2X,
  20127. float controlPoint2Y,
  20128. float endPointX,
  20129. float endPointY);
  20130. /** Adds a cubic bezier curve from the shape's last position to a new position.
  20131. This will connect the end-point of the last line or curve that was added
  20132. to a new point, using a cubic spline with two control-points.
  20133. See the class description for an example of how to add lines and curves to a path.
  20134. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  20135. */
  20136. void cubicTo (const Point<float>& controlPoint1,
  20137. const Point<float>& controlPoint2,
  20138. const Point<float>& endPoint);
  20139. /** Returns the last point that was added to the path by one of the drawing methods.
  20140. */
  20141. const Point<float> getCurrentPosition() const;
  20142. /** Adds a rectangle to the path.
  20143. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20144. @see addRoundedRectangle, addTriangle
  20145. */
  20146. void addRectangle (float x, float y, float width, float height);
  20147. /** Adds a rectangle to the path.
  20148. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20149. @see addRoundedRectangle, addTriangle
  20150. */
  20151. template <typename ValueType>
  20152. void addRectangle (const Rectangle<ValueType>& rectangle)
  20153. {
  20154. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20155. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  20156. }
  20157. /** Adds a rectangle with rounded corners to the path.
  20158. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20159. @see addRectangle, addTriangle
  20160. */
  20161. void addRoundedRectangle (float x, float y, float width, float height,
  20162. float cornerSize);
  20163. /** Adds a rectangle with rounded corners to the path.
  20164. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20165. @see addRectangle, addTriangle
  20166. */
  20167. void addRoundedRectangle (float x, float y, float width, float height,
  20168. float cornerSizeX,
  20169. float cornerSizeY);
  20170. /** Adds a rectangle with rounded corners to the path.
  20171. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20172. @see addRectangle, addTriangle
  20173. */
  20174. template <typename ValueType>
  20175. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  20176. {
  20177. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  20178. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  20179. cornerSizeX, cornerSizeY);
  20180. }
  20181. /** Adds a rectangle with rounded corners to the path.
  20182. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  20183. @see addRectangle, addTriangle
  20184. */
  20185. template <typename ValueType>
  20186. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  20187. {
  20188. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  20189. }
  20190. /** Adds a triangle to the path.
  20191. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  20192. Note that whether the vertices are specified in clockwise or anticlockwise
  20193. order will affect how the triangle is filled when it overlaps other
  20194. shapes (the winding order setting will affect this of course).
  20195. */
  20196. void addTriangle (float x1, float y1,
  20197. float x2, float y2,
  20198. float x3, float y3);
  20199. /** Adds a quadrilateral to the path.
  20200. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  20201. Note that whether the vertices are specified in clockwise or anticlockwise
  20202. order will affect how the quad is filled when it overlaps other
  20203. shapes (the winding order setting will affect this of course).
  20204. */
  20205. void addQuadrilateral (float x1, float y1,
  20206. float x2, float y2,
  20207. float x3, float y3,
  20208. float x4, float y4);
  20209. /** Adds an ellipse to the path.
  20210. The shape is added as a new sub-path. (Any currently open paths will be left open).
  20211. @see addArc
  20212. */
  20213. void addEllipse (float x, float y, float width, float height);
  20214. /** Adds an elliptical arc to the current path.
  20215. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20216. or anti-clockwise according to whether the end angle is greater than the start. This means
  20217. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20218. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20219. @param y the top edge of the rectangle in which the elliptical outline fits
  20220. @param width the width of the rectangle in which the elliptical outline fits
  20221. @param height the height of the rectangle in which the elliptical outline fits
  20222. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20223. top-centre of the ellipse)
  20224. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20225. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20226. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20227. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20228. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20229. it will be added to the current sub-path, continuing from the current postition
  20230. @see addCentredArc, arcTo, addPieSegment, addEllipse
  20231. */
  20232. void addArc (float x, float y, float width, float height,
  20233. float fromRadians,
  20234. float toRadians,
  20235. bool startAsNewSubPath = false);
  20236. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  20237. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20238. or anti-clockwise according to whether the end angle is greater than the start. This means
  20239. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20240. @param centreX the centre x of the ellipse
  20241. @param centreY the centre y of the ellipse
  20242. @param radiusX the horizontal radius of the ellipse
  20243. @param radiusY the vertical radius of the ellipse
  20244. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  20245. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20246. top-centre of the ellipse)
  20247. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20248. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  20249. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  20250. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  20251. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  20252. it will be added to the current sub-path, continuing from the current postition
  20253. @see addArc, arcTo
  20254. */
  20255. void addCentredArc (float centreX, float centreY,
  20256. float radiusX, float radiusY,
  20257. float rotationOfEllipse,
  20258. float fromRadians,
  20259. float toRadians,
  20260. bool startAsNewSubPath = false);
  20261. /** Adds a "pie-chart" shape to the path.
  20262. The shape is added as a new sub-path. (Any currently open paths will be
  20263. left open).
  20264. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  20265. or anti-clockwise according to whether the end angle is greater than the start. This means
  20266. that sometimes you may need to use values greater than 2*Pi for the end angle.
  20267. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  20268. @param y the top edge of the rectangle in which the elliptical outline fits
  20269. @param width the width of the rectangle in which the elliptical outline fits
  20270. @param height the height of the rectangle in which the elliptical outline fits
  20271. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  20272. top-centre of the ellipse)
  20273. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  20274. top-centre of the ellipse)
  20275. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  20276. ellipse at its centre, where this value indicates the inner ellipse's size with
  20277. respect to the outer one.
  20278. @see addArc
  20279. */
  20280. void addPieSegment (float x, float y,
  20281. float width, float height,
  20282. float fromRadians,
  20283. float toRadians,
  20284. float innerCircleProportionalSize);
  20285. /** Adds a line with a specified thickness.
  20286. The line is added as a new closed sub-path. (Any currently open paths will be
  20287. left open).
  20288. @see addArrow
  20289. */
  20290. void addLineSegment (const Line<float>& line, float lineThickness);
  20291. /** Adds a line with an arrowhead on the end.
  20292. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  20293. @see PathStrokeType::createStrokeWithArrowheads
  20294. */
  20295. void addArrow (const Line<float>& line,
  20296. float lineThickness,
  20297. float arrowheadWidth,
  20298. float arrowheadLength);
  20299. /** Adds a polygon shape to the path.
  20300. @see addStar
  20301. */
  20302. void addPolygon (const Point<float>& centre,
  20303. int numberOfSides,
  20304. float radius,
  20305. float startAngle = 0.0f);
  20306. /** Adds a star shape to the path.
  20307. @see addPolygon
  20308. */
  20309. void addStar (const Point<float>& centre,
  20310. int numberOfPoints,
  20311. float innerRadius,
  20312. float outerRadius,
  20313. float startAngle = 0.0f);
  20314. /** Adds a speech-bubble shape to the path.
  20315. @param bodyX the left of the main body area of the bubble
  20316. @param bodyY the top of the main body area of the bubble
  20317. @param bodyW the width of the main body area of the bubble
  20318. @param bodyH the height of the main body area of the bubble
  20319. @param cornerSize the amount by which to round off the corners of the main body rectangle
  20320. @param arrowTipX the x position that the tip of the arrow should connect to
  20321. @param arrowTipY the y position that the tip of the arrow should connect to
  20322. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  20323. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  20324. arrow's base should be - this is a proportional distance between 0 and 1.0
  20325. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  20326. */
  20327. void addBubble (float bodyX, float bodyY,
  20328. float bodyW, float bodyH,
  20329. float cornerSize,
  20330. float arrowTipX,
  20331. float arrowTipY,
  20332. int whichSide,
  20333. float arrowPositionAlongEdgeProportional,
  20334. float arrowWidth);
  20335. /** Adds another path to this one.
  20336. The new path is added as a new sub-path. (Any currently open paths in this
  20337. path will be left open).
  20338. @param pathToAppend the path to add
  20339. */
  20340. void addPath (const Path& pathToAppend);
  20341. /** Adds another path to this one, transforming it on the way in.
  20342. The new path is added as a new sub-path, its points being transformed by the given
  20343. matrix before being added.
  20344. @param pathToAppend the path to add
  20345. @param transformToApply an optional transform to apply to the incoming vertices
  20346. */
  20347. void addPath (const Path& pathToAppend,
  20348. const AffineTransform& transformToApply);
  20349. /** Swaps the contents of this path with another one.
  20350. The internal data of the two paths is swapped over, so this is much faster than
  20351. copying it to a temp variable and back.
  20352. */
  20353. void swapWithPath (Path& other) throw();
  20354. /** Applies a 2D transform to all the vertices in the path.
  20355. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  20356. */
  20357. void applyTransform (const AffineTransform& transform) throw();
  20358. /** Rescales this path to make it fit neatly into a given space.
  20359. This is effectively a quick way of calling
  20360. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  20361. @param x the x position of the rectangle to fit the path inside
  20362. @param y the y position of the rectangle to fit the path inside
  20363. @param width the width of the rectangle to fit the path inside
  20364. @param height the height of the rectangle to fit the path inside
  20365. @param preserveProportions if true, it will fit the path into the space without altering its
  20366. horizontal/vertical scale ratio; if false, it will distort the
  20367. path to fill the specified ratio both horizontally and vertically
  20368. @see applyTransform, getTransformToScaleToFit
  20369. */
  20370. void scaleToFit (float x, float y, float width, float height,
  20371. bool preserveProportions) throw();
  20372. /** Returns a transform that can be used to rescale the path to fit into a given space.
  20373. @param x the x position of the rectangle to fit the path inside
  20374. @param y the y position of the rectangle to fit the path inside
  20375. @param width the width of the rectangle to fit the path inside
  20376. @param height the height of the rectangle to fit the path inside
  20377. @param preserveProportions if true, it will fit the path into the space without altering its
  20378. horizontal/vertical scale ratio; if false, it will distort the
  20379. path to fill the specified ratio both horizontally and vertically
  20380. @param justificationType if the proportions are preseved, the resultant path may be smaller
  20381. than the available rectangle, so this describes how it should be
  20382. positioned within the space.
  20383. @returns an appropriate transformation
  20384. @see applyTransform, scaleToFit
  20385. */
  20386. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  20387. bool preserveProportions,
  20388. const Justification& justificationType = Justification::centred) const;
  20389. /** Creates a version of this path where all sharp corners have been replaced by curves.
  20390. Wherever two lines meet at an angle, this will replace the corner with a curve
  20391. of the given radius.
  20392. */
  20393. const Path createPathWithRoundedCorners (float cornerRadius) const;
  20394. /** Changes the winding-rule to be used when filling the path.
  20395. If set to true (which is the default), then the path uses a non-zero-winding rule
  20396. to determine which points are inside the path. If set to false, it uses an
  20397. alternate-winding rule.
  20398. The winding-rule comes into play when areas of the shape overlap other
  20399. areas, and determines whether the overlapping regions are considered to be
  20400. inside or outside.
  20401. Changing this value just sets a flag - it doesn't affect the contents of the
  20402. path.
  20403. @see isUsingNonZeroWinding
  20404. */
  20405. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  20406. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  20407. The default for a new path is true.
  20408. @see setUsingNonZeroWinding
  20409. */
  20410. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  20411. /** Iterates the lines and curves that a path contains.
  20412. @see Path, PathFlatteningIterator
  20413. */
  20414. class JUCE_API Iterator
  20415. {
  20416. public:
  20417. Iterator (const Path& path);
  20418. ~Iterator();
  20419. /** Moves onto the next element in the path.
  20420. If this returns false, there are no more elements. If it returns true,
  20421. the elementType variable will be set to the type of the current element,
  20422. and some of the x and y variables will be filled in with values.
  20423. */
  20424. bool next();
  20425. enum PathElementType
  20426. {
  20427. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  20428. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  20429. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  20430. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  20431. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  20432. };
  20433. PathElementType elementType;
  20434. float x1, y1, x2, y2, x3, y3;
  20435. private:
  20436. const Path& path;
  20437. size_t index;
  20438. JUCE_DECLARE_NON_COPYABLE (Iterator);
  20439. };
  20440. /** Loads a stored path from a data stream.
  20441. The data in the stream must have been written using writePathToStream().
  20442. Note that this will append the stored path to whatever is currently in
  20443. this path, so you might need to call clear() beforehand.
  20444. @see loadPathFromData, writePathToStream
  20445. */
  20446. void loadPathFromStream (InputStream& source);
  20447. /** Loads a stored path from a block of data.
  20448. This is similar to loadPathFromStream(), but just reads from a block
  20449. of data. Useful if you're including stored shapes in your code as a
  20450. block of static data.
  20451. @see loadPathFromStream, writePathToStream
  20452. */
  20453. void loadPathFromData (const void* data, int numberOfBytes);
  20454. /** Stores the path by writing it out to a stream.
  20455. After writing out a path, you can reload it using loadPathFromStream().
  20456. @see loadPathFromStream, loadPathFromData
  20457. */
  20458. void writePathToStream (OutputStream& destination) const;
  20459. /** Creates a string containing a textual representation of this path.
  20460. @see restoreFromString
  20461. */
  20462. const String toString() const;
  20463. /** Restores this path from a string that was created with the toString() method.
  20464. @see toString()
  20465. */
  20466. void restoreFromString (const String& stringVersion);
  20467. private:
  20468. friend class PathFlatteningIterator;
  20469. friend class Path::Iterator;
  20470. ArrayAllocationBase <float, DummyCriticalSection> data;
  20471. size_t numElements;
  20472. float pathXMin, pathXMax, pathYMin, pathYMax;
  20473. bool useNonZeroWinding;
  20474. static const float lineMarker;
  20475. static const float moveMarker;
  20476. static const float quadMarker;
  20477. static const float cubicMarker;
  20478. static const float closeSubPathMarker;
  20479. JUCE_LEAK_DETECTOR (Path);
  20480. };
  20481. #endif // __JUCE_PATH_JUCEHEADER__
  20482. /*** End of inlined file: juce_Path.h ***/
  20483. class Font;
  20484. class EdgeTable;
  20485. /** A typeface represents a size-independent font.
  20486. This base class is abstract, but calling createSystemTypefaceFor() will return
  20487. a platform-specific subclass that can be used.
  20488. The CustomTypeface subclass allow you to build your own typeface, and to
  20489. load and save it in the Juce typeface format.
  20490. Normally you should never need to deal directly with Typeface objects - the Font
  20491. class does everything you typically need for rendering text.
  20492. @see CustomTypeface, Font
  20493. */
  20494. class JUCE_API Typeface : public ReferenceCountedObject
  20495. {
  20496. public:
  20497. /** A handy typedef for a pointer to a typeface. */
  20498. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  20499. /** Returns the name of the typeface.
  20500. @see Font::getTypefaceName
  20501. */
  20502. const String getName() const throw() { return name; }
  20503. /** Creates a new system typeface. */
  20504. static const Ptr createSystemTypefaceFor (const Font& font);
  20505. /** Destructor. */
  20506. virtual ~Typeface();
  20507. /** Returns true if this typeface can be used to render the specified font.
  20508. When called, the font will already have been checked to make sure that its name and
  20509. style flags match the typeface.
  20510. */
  20511. virtual bool isSuitableForFont (const Font&) const { return true; }
  20512. /** Returns the ascent of the font, as a proportion of its height.
  20513. The height is considered to always be normalised as 1.0, so this will be a
  20514. value less that 1.0, indicating the proportion of the font that lies above
  20515. its baseline.
  20516. */
  20517. virtual float getAscent() const = 0;
  20518. /** Returns the descent of the font, as a proportion of its height.
  20519. The height is considered to always be normalised as 1.0, so this will be a
  20520. value less that 1.0, indicating the proportion of the font that lies below
  20521. its baseline.
  20522. */
  20523. virtual float getDescent() const = 0;
  20524. /** Measures the width of a line of text.
  20525. The distance returned is based on the font having an normalised height of 1.0.
  20526. You should never need to call this directly! Use Font::getStringWidth() instead!
  20527. */
  20528. virtual float getStringWidth (const String& text) = 0;
  20529. /** Converts a line of text into its glyph numbers and their positions.
  20530. The distances returned are based on the font having an normalised height of 1.0.
  20531. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  20532. */
  20533. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  20534. /** Returns the outline for a glyph.
  20535. The path returned will be normalised to a font height of 1.0.
  20536. */
  20537. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  20538. /** Returns a new EdgeTable that contains the path for the givem glyph, with the specified transform applied. */
  20539. virtual EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  20540. /** Returns true if the typeface uses hinting. */
  20541. virtual bool isHinted() const { return false; }
  20542. /** Changes the number of fonts that are cached in memory. */
  20543. static void setTypefaceCacheSize (int numFontsToCache);
  20544. protected:
  20545. String name;
  20546. bool isFallbackFont;
  20547. explicit Typeface (const String& name) throw();
  20548. static const Ptr getFallbackTypeface();
  20549. private:
  20550. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  20551. };
  20552. /** A typeface that can be populated with custom glyphs.
  20553. You can create a CustomTypeface if you need one that contains your own glyphs,
  20554. or if you need to load a typeface from a Juce-formatted binary stream.
  20555. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  20556. to copy glyphs into this face.
  20557. @see Typeface, Font
  20558. */
  20559. class JUCE_API CustomTypeface : public Typeface
  20560. {
  20561. public:
  20562. /** Creates a new, empty typeface. */
  20563. CustomTypeface();
  20564. /** Loads a typeface from a previously saved stream.
  20565. The stream must have been created by writeToStream().
  20566. @see writeToStream
  20567. */
  20568. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  20569. /** Destructor. */
  20570. ~CustomTypeface();
  20571. /** Resets this typeface, deleting all its glyphs and settings. */
  20572. void clear();
  20573. /** Sets the vital statistics for the typeface.
  20574. @param name the typeface's name
  20575. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  20576. the value that will be returned by Typeface::getAscent(). The
  20577. descent is assumed to be (1.0 - ascent)
  20578. @param isBold should be true if the typeface is bold
  20579. @param isItalic should be true if the typeface is italic
  20580. @param defaultCharacter the character to be used as a replacement if there's
  20581. no glyph available for the character that's being drawn
  20582. */
  20583. void setCharacteristics (const String& name, float ascent,
  20584. bool isBold, bool isItalic,
  20585. juce_wchar defaultCharacter) throw();
  20586. /** Adds a glyph to the typeface.
  20587. The path that is passed in is normalised so that the font height is 1.0, and its
  20588. origin is the anchor point of the character on its baseline.
  20589. The width is the nominal width of the character, and any extra kerning values that
  20590. are specified will be added to this width.
  20591. */
  20592. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  20593. /** Specifies an extra kerning amount to be used between a pair of characters.
  20594. The amount will be added to the nominal width of the first character when laying out a string.
  20595. */
  20596. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  20597. /** Adds a range of glyphs from another typeface.
  20598. This will attempt to pull in the paths and kerning information from another typeface and
  20599. add it to this one.
  20600. */
  20601. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  20602. /** Saves this typeface as a Juce-formatted font file.
  20603. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  20604. constructor.
  20605. */
  20606. bool writeToStream (OutputStream& outputStream);
  20607. // The following methods implement the basic Typeface behaviour.
  20608. float getAscent() const;
  20609. float getDescent() const;
  20610. float getStringWidth (const String& text);
  20611. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  20612. bool getOutlineForGlyph (int glyphNumber, Path& path);
  20613. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  20614. int getGlyphForCharacter (juce_wchar character);
  20615. protected:
  20616. juce_wchar defaultCharacter;
  20617. float ascent;
  20618. bool isBold, isItalic;
  20619. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  20620. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  20621. particular character and there's no corresponding glyph, they'll call this
  20622. method so that a subclass can try to add that glyph, returning true if it
  20623. manages to do so.
  20624. */
  20625. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  20626. private:
  20627. class GlyphInfo;
  20628. friend class OwnedArray<GlyphInfo>;
  20629. OwnedArray <GlyphInfo> glyphs;
  20630. short lookupTable [128];
  20631. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  20632. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  20633. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  20634. };
  20635. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  20636. /*** End of inlined file: juce_Typeface.h ***/
  20637. class LowLevelGraphicsContext;
  20638. /**
  20639. Represents a particular font, including its size, style, etc.
  20640. Apart from the typeface to be used, a Font object also dictates whether
  20641. the font is bold, italic, underlined, how big it is, and its kerning and
  20642. horizontal scale factor.
  20643. @see Typeface
  20644. */
  20645. class JUCE_API Font
  20646. {
  20647. public:
  20648. /** A combination of these values is used by the constructor to specify the
  20649. style of font to use.
  20650. */
  20651. enum FontStyleFlags
  20652. {
  20653. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  20654. bold = 1, /**< boldens the font. @see setStyleFlags */
  20655. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  20656. underlined = 4 /**< underlines the font. @see setStyleFlags */
  20657. };
  20658. /** Creates a sans-serif font in a given size.
  20659. @param fontHeight the height in pixels (can be fractional)
  20660. @param styleFlags the style to use - this can be a combination of the
  20661. Font::bold, Font::italic and Font::underlined, or
  20662. just Font::plain for the normal style.
  20663. @see FontStyleFlags, getDefaultSansSerifFontName
  20664. */
  20665. Font (float fontHeight, int styleFlags = plain);
  20666. /** Creates a font with a given typeface and parameters.
  20667. @param typefaceName the name of the typeface to use
  20668. @param fontHeight the height in pixels (can be fractional)
  20669. @param styleFlags the style to use - this can be a combination of the
  20670. Font::bold, Font::italic and Font::underlined, or
  20671. just Font::plain for the normal style.
  20672. @see FontStyleFlags, getDefaultSansSerifFontName
  20673. */
  20674. Font (const String& typefaceName, float fontHeight, int styleFlags);
  20675. /** Creates a copy of another Font object. */
  20676. Font (const Font& other) throw();
  20677. /** Creates a font for a typeface. */
  20678. Font (const Typeface::Ptr& typeface);
  20679. /** Creates a basic sans-serif font at a default height.
  20680. You should use one of the other constructors for creating a font that you're planning
  20681. on drawing with - this constructor is here to help initialise objects before changing
  20682. the font's settings later.
  20683. */
  20684. Font();
  20685. /** Copies this font from another one. */
  20686. Font& operator= (const Font& other) throw();
  20687. bool operator== (const Font& other) const throw();
  20688. bool operator!= (const Font& other) const throw();
  20689. /** Destructor. */
  20690. ~Font() throw();
  20691. /** Changes the name of the typeface family.
  20692. e.g. "Arial", "Courier", etc.
  20693. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20694. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20695. but are generic names that are used to represent the various default fonts.
  20696. If you need to know the exact typeface name being used, you can call
  20697. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20698. If a suitable font isn't found on the machine, it'll just use a default instead.
  20699. */
  20700. void setTypefaceName (const String& faceName);
  20701. /** Returns the name of the typeface family that this font uses.
  20702. e.g. "Arial", "Courier", etc.
  20703. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20704. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20705. but are generic names that are used to represent the various default fonts.
  20706. If you need to know the exact typeface name being used, you can call
  20707. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20708. */
  20709. const String& getTypefaceName() const throw() { return font->typefaceName; }
  20710. /** Returns a typeface name that represents the default sans-serif font.
  20711. This is also the typeface that will be used when a font is created without
  20712. specifying any typeface details.
  20713. Note that this method just returns a generic placeholder string that means "the default
  20714. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  20715. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20716. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  20717. */
  20718. static const String getDefaultSansSerifFontName();
  20719. /** Returns a typeface name that represents the default sans-serif font.
  20720. Note that this method just returns a generic placeholder string that means "the default
  20721. serif font" - it's not the actual name of this font. To get the actual name, use
  20722. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20723. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  20724. */
  20725. static const String getDefaultSerifFontName();
  20726. /** Returns a typeface name that represents the default sans-serif font.
  20727. Note that this method just returns a generic placeholder string that means "the default
  20728. monospaced font" - it's not the actual name of this font. To get the actual name, use
  20729. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20730. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  20731. */
  20732. static const String getDefaultMonospacedFontName();
  20733. /** Returns the typeface names of the default fonts on the current platform. */
  20734. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  20735. /** Returns the total height of this font.
  20736. This is the maximum height, from the top of the ascent to the bottom of the
  20737. descenders.
  20738. @see setHeight, setHeightWithoutChangingWidth, getAscent
  20739. */
  20740. float getHeight() const throw() { return font->height; }
  20741. /** Changes the font's height.
  20742. @see getHeight, setHeightWithoutChangingWidth
  20743. */
  20744. void setHeight (float newHeight);
  20745. /** Changes the font's height without changing its width.
  20746. This alters the horizontal scale to compensate for the change in height.
  20747. */
  20748. void setHeightWithoutChangingWidth (float newHeight);
  20749. /** Returns the height of the font above its baseline.
  20750. This is the maximum height from the baseline to the top.
  20751. @see getHeight, getDescent
  20752. */
  20753. float getAscent() const;
  20754. /** Returns the amount that the font descends below its baseline.
  20755. This is calculated as (getHeight() - getAscent()).
  20756. @see getAscent, getHeight
  20757. */
  20758. float getDescent() const;
  20759. /** Returns the font's style flags.
  20760. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  20761. enum, to describe whether the font is bold, italic, etc.
  20762. @see FontStyleFlags
  20763. */
  20764. int getStyleFlags() const throw() { return font->styleFlags; }
  20765. /** Changes the font's style.
  20766. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  20767. enum, to set the font's properties
  20768. @see FontStyleFlags
  20769. */
  20770. void setStyleFlags (int newFlags);
  20771. /** Makes the font bold or non-bold. */
  20772. void setBold (bool shouldBeBold);
  20773. /** Returns a copy of this font with the bold attribute set. */
  20774. const Font boldened() const;
  20775. /** Returns true if the font is bold. */
  20776. bool isBold() const throw();
  20777. /** Makes the font italic or non-italic. */
  20778. void setItalic (bool shouldBeItalic);
  20779. /** Returns a copy of this font with the italic attribute set. */
  20780. const Font italicised() const;
  20781. /** Returns true if the font is italic. */
  20782. bool isItalic() const throw();
  20783. /** Makes the font underlined or non-underlined. */
  20784. void setUnderline (bool shouldBeUnderlined);
  20785. /** Returns true if the font is underlined. */
  20786. bool isUnderlined() const throw();
  20787. /** Changes the font's horizontal scale factor.
  20788. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  20789. narrower, greater than 1.0 will be stretched out.
  20790. */
  20791. void setHorizontalScale (float scaleFactor);
  20792. /** Returns the font's horizontal scale.
  20793. A value of 1.0 is the normal scale, less than this will be narrower, greater
  20794. than 1.0 will be stretched out.
  20795. @see setHorizontalScale
  20796. */
  20797. float getHorizontalScale() const throw() { return font->horizontalScale; }
  20798. /** Changes the font's kerning.
  20799. @param extraKerning a multiple of the font's height that will be added
  20800. to space between the characters. So a value of zero is
  20801. normal spacing, positive values spread the letters out,
  20802. negative values make them closer together.
  20803. */
  20804. void setExtraKerningFactor (float extraKerning);
  20805. /** Returns the font's kerning.
  20806. This is the extra space added between adjacent characters, as a proportion
  20807. of the font's height.
  20808. A value of zero is normal spacing, positive values will spread the letters
  20809. out more, and negative values make them closer together.
  20810. */
  20811. float getExtraKerningFactor() const throw() { return font->kerning; }
  20812. /** Changes all the font's characteristics with one call. */
  20813. void setSizeAndStyle (float newHeight,
  20814. int newStyleFlags,
  20815. float newHorizontalScale,
  20816. float newKerningAmount);
  20817. /** Returns the total width of a string as it would be drawn using this font.
  20818. For a more accurate floating-point result, use getStringWidthFloat().
  20819. */
  20820. int getStringWidth (const String& text) const;
  20821. /** Returns the total width of a string as it would be drawn using this font.
  20822. @see getStringWidth
  20823. */
  20824. float getStringWidthFloat (const String& text) const;
  20825. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  20826. An extra x offset is added at the end of the run, to indicate where the right hand
  20827. edge of the last character is.
  20828. */
  20829. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  20830. /** Returns the typeface used by this font.
  20831. Note that the object returned may go out of scope if this font is deleted
  20832. or has its style changed.
  20833. */
  20834. Typeface* getTypeface() const;
  20835. /** Creates an array of Font objects to represent all the fonts on the system.
  20836. If you just need the names of the typefaces, you can also use
  20837. findAllTypefaceNames() instead.
  20838. @param results the array to which new Font objects will be added.
  20839. */
  20840. static void findFonts (Array<Font>& results);
  20841. /** Returns a list of all the available typeface names.
  20842. The names returned can be passed into setTypefaceName().
  20843. You can use this instead of findFonts() if you only need their names, and not
  20844. font objects.
  20845. */
  20846. static const StringArray findAllTypefaceNames();
  20847. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  20848. in the requested typeface.
  20849. */
  20850. static const String getFallbackFontName();
  20851. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  20852. available in whatever font you're trying to use.
  20853. */
  20854. static void setFallbackFontName (const String& name);
  20855. /** Creates a string to describe this font.
  20856. The string will contain information to describe the font's typeface, size, and
  20857. style. To recreate the font from this string, use fromString().
  20858. */
  20859. const String toString() const;
  20860. /** Recreates a font from its stringified encoding.
  20861. This method takes a string that was created by toString(), and recreates the
  20862. original font.
  20863. */
  20864. static const Font fromString (const String& fontDescription);
  20865. private:
  20866. friend class FontGlyphAlphaMap;
  20867. friend class TypefaceCache;
  20868. class SharedFontInternal : public ReferenceCountedObject
  20869. {
  20870. public:
  20871. SharedFontInternal (float height, int styleFlags) throw();
  20872. SharedFontInternal (const String& typefaceName, float height, int styleFlags) throw();
  20873. SharedFontInternal (const Typeface::Ptr& typeface) throw();
  20874. SharedFontInternal (const SharedFontInternal& other) throw();
  20875. bool operator== (const SharedFontInternal&) const throw();
  20876. String typefaceName;
  20877. float height, horizontalScale, kerning, ascent;
  20878. int styleFlags;
  20879. Typeface::Ptr typeface;
  20880. };
  20881. ReferenceCountedObjectPtr <SharedFontInternal> font;
  20882. void dupeInternalIfShared();
  20883. JUCE_LEAK_DETECTOR (Font);
  20884. };
  20885. #endif // __JUCE_FONT_JUCEHEADER__
  20886. /*** End of inlined file: juce_Font.h ***/
  20887. /*** Start of inlined file: juce_PathStrokeType.h ***/
  20888. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20889. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20890. /**
  20891. Describes a type of stroke used to render a solid outline along a path.
  20892. A PathStrokeType object can be used directly to create the shape of an outline
  20893. around a path, and is used by Graphics::strokePath to specify the type of
  20894. stroke to draw.
  20895. @see Path, Graphics::strokePath
  20896. */
  20897. class JUCE_API PathStrokeType
  20898. {
  20899. public:
  20900. /** The type of shape to use for the corners between two adjacent line segments. */
  20901. enum JointStyle
  20902. {
  20903. mitered, /**< Indicates that corners should be drawn with sharp joints.
  20904. Note that for angles that curve back on themselves, drawing a
  20905. mitre could require extending the point too far away from the
  20906. path, so a mitre limit is imposed and any corners that exceed it
  20907. are drawn as bevelled instead. */
  20908. curved, /**< Indicates that corners should be drawn as rounded-off. */
  20909. beveled /**< Indicates that corners should be drawn with a line flattening their
  20910. outside edge. */
  20911. };
  20912. /** The type shape to use for the ends of lines. */
  20913. enum EndCapStyle
  20914. {
  20915. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  20916. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  20917. the thickness of the stroke. */
  20918. rounded /**< Ends of lines are rounded-off with a circular shape. */
  20919. };
  20920. /** Creates a stroke type.
  20921. @param strokeThickness the width of the line to use
  20922. @param jointStyle the type of joints to use for corners
  20923. @param endStyle the type of end-caps to use for the ends of open paths.
  20924. */
  20925. PathStrokeType (float strokeThickness,
  20926. JointStyle jointStyle = mitered,
  20927. EndCapStyle endStyle = butt) throw();
  20928. /** Createes a copy of another stroke type. */
  20929. PathStrokeType (const PathStrokeType& other) throw();
  20930. /** Copies another stroke onto this one. */
  20931. PathStrokeType& operator= (const PathStrokeType& other) throw();
  20932. /** Destructor. */
  20933. ~PathStrokeType() throw();
  20934. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  20935. @param destPath the resultant stroked outline shape will be copied into this path.
  20936. Note that it's ok for the source and destination Paths to be
  20937. the same object, so you can easily turn a path into a stroked version
  20938. of itself.
  20939. @param sourcePath the path to use as the source
  20940. @param transform an optional transform to apply to the points from the source path
  20941. as they are being used
  20942. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20943. a higher resolution, which improves the quality if you'll later want
  20944. to enlarge the stroked path. So for example, if you're planning on drawing
  20945. the stroke at 3x the size that you're creating it, you should set this to 3.
  20946. @see createDashedStroke
  20947. */
  20948. void createStrokedPath (Path& destPath,
  20949. const Path& sourcePath,
  20950. const AffineTransform& transform = AffineTransform::identity,
  20951. float extraAccuracy = 1.0f) const;
  20952. /** Applies this stroke type to a path, creating a dashed line.
  20953. This is similar to createStrokedPath, but uses the array passed in to
  20954. break the stroke up into a series of dashes.
  20955. @param destPath the resultant stroked outline shape will be copied into this path.
  20956. Note that it's ok for the source and destination Paths to be
  20957. the same object, so you can easily turn a path into a stroked version
  20958. of itself.
  20959. @param sourcePath the path to use as the source
  20960. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  20961. a line of length 2, then skip a length of 3, then add a line of length 4,
  20962. skip 5, and keep repeating this pattern.
  20963. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  20964. an even number, otherwise the pattern will get out of step as it
  20965. repeats.
  20966. @param transform an optional transform to apply to the points from the source path
  20967. as they are being used
  20968. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20969. a higher resolution, which improves the quality if you'll later want
  20970. to enlarge the stroked path. So for example, if you're planning on drawing
  20971. the stroke at 3x the size that you're creating it, you should set this to 3.
  20972. */
  20973. void createDashedStroke (Path& destPath,
  20974. const Path& sourcePath,
  20975. const float* dashLengths,
  20976. int numDashLengths,
  20977. const AffineTransform& transform = AffineTransform::identity,
  20978. float extraAccuracy = 1.0f) const;
  20979. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  20980. @param destPath the resultant stroked outline shape will be copied into this path.
  20981. Note that it's ok for the source and destination Paths to be
  20982. the same object, so you can easily turn a path into a stroked version
  20983. of itself.
  20984. @param sourcePath the path to use as the source
  20985. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  20986. @param arrowheadStartLength the length of the arrowhead at the start of the path
  20987. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  20988. @param arrowheadEndLength the length of the arrowhead at the end of the path
  20989. @param transform an optional transform to apply to the points from the source path
  20990. as they are being used
  20991. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20992. a higher resolution, which improves the quality if you'll later want
  20993. to enlarge the stroked path. So for example, if you're planning on drawing
  20994. the stroke at 3x the size that you're creating it, you should set this to 3.
  20995. @see createDashedStroke
  20996. */
  20997. void createStrokeWithArrowheads (Path& destPath,
  20998. const Path& sourcePath,
  20999. float arrowheadStartWidth, float arrowheadStartLength,
  21000. float arrowheadEndWidth, float arrowheadEndLength,
  21001. const AffineTransform& transform = AffineTransform::identity,
  21002. float extraAccuracy = 1.0f) const;
  21003. /** Returns the stroke thickness. */
  21004. float getStrokeThickness() const throw() { return thickness; }
  21005. /** Sets the stroke thickness. */
  21006. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  21007. /** Returns the joint style. */
  21008. JointStyle getJointStyle() const throw() { return jointStyle; }
  21009. /** Sets the joint style. */
  21010. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  21011. /** Returns the end-cap style. */
  21012. EndCapStyle getEndStyle() const throw() { return endStyle; }
  21013. /** Sets the end-cap style. */
  21014. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  21015. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21016. bool operator== (const PathStrokeType& other) const throw();
  21017. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  21018. bool operator!= (const PathStrokeType& other) const throw();
  21019. private:
  21020. float thickness;
  21021. JointStyle jointStyle;
  21022. EndCapStyle endStyle;
  21023. JUCE_LEAK_DETECTOR (PathStrokeType);
  21024. };
  21025. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  21026. /*** End of inlined file: juce_PathStrokeType.h ***/
  21027. /*** Start of inlined file: juce_Colours.h ***/
  21028. #ifndef __JUCE_COLOURS_JUCEHEADER__
  21029. #define __JUCE_COLOURS_JUCEHEADER__
  21030. /*** Start of inlined file: juce_Colour.h ***/
  21031. #ifndef __JUCE_COLOUR_JUCEHEADER__
  21032. #define __JUCE_COLOUR_JUCEHEADER__
  21033. /*** Start of inlined file: juce_PixelFormats.h ***/
  21034. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  21035. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  21036. #ifndef DOXYGEN
  21037. #if JUCE_MSVC
  21038. #pragma pack (push, 1)
  21039. #define PACKED
  21040. #elif JUCE_GCC
  21041. #define PACKED __attribute__((packed))
  21042. #else
  21043. #define PACKED
  21044. #endif
  21045. #endif
  21046. class PixelRGB;
  21047. class PixelAlpha;
  21048. /**
  21049. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  21050. operations with it.
  21051. This is used internally by the imaging classes.
  21052. @see PixelRGB
  21053. */
  21054. class JUCE_API PixelARGB
  21055. {
  21056. public:
  21057. /** Creates a pixel without defining its colour. */
  21058. PixelARGB() throw() {}
  21059. ~PixelARGB() throw() {}
  21060. /** Creates a pixel from a 32-bit argb value.
  21061. */
  21062. PixelARGB (const uint32 argb_) throw()
  21063. : argb (argb_)
  21064. {
  21065. }
  21066. forcedinline uint32 getARGB() const throw() { return argb; }
  21067. forcedinline uint32 getUnpremultipliedARGB() const throw() { PixelARGB p (argb); p.unpremultiply(); return p.getARGB(); }
  21068. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  21069. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  21070. forcedinline uint8 getAlpha() const throw() { return components.a; }
  21071. forcedinline uint8 getRed() const throw() { return components.r; }
  21072. forcedinline uint8 getGreen() const throw() { return components.g; }
  21073. forcedinline uint8 getBlue() const throw() { return components.b; }
  21074. /** Blends another pixel onto this one.
  21075. This takes into account the opacity of the pixel being overlaid, and blends
  21076. it accordingly.
  21077. */
  21078. forcedinline void blend (const PixelARGB& src) throw()
  21079. {
  21080. uint32 sargb = src.getARGB();
  21081. const uint32 alpha = 0x100 - (sargb >> 24);
  21082. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21083. sargb += 0xff00ff00 & (getAG() * alpha);
  21084. argb = sargb;
  21085. }
  21086. /** Blends another pixel onto this one.
  21087. This takes into account the opacity of the pixel being overlaid, and blends
  21088. it accordingly.
  21089. */
  21090. forcedinline void blend (const PixelAlpha& src) throw();
  21091. /** Blends another pixel onto this one.
  21092. This takes into account the opacity of the pixel being overlaid, and blends
  21093. it accordingly.
  21094. */
  21095. forcedinline void blend (const PixelRGB& src) throw();
  21096. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21097. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21098. being used, so this can blend semi-transparently from a PixelRGB argument.
  21099. */
  21100. template <class Pixel>
  21101. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  21102. {
  21103. ++extraAlpha;
  21104. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  21105. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  21106. const uint32 alpha = 0x100 - (sargb >> 24);
  21107. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21108. sargb += 0xff00ff00 & (getAG() * alpha);
  21109. argb = sargb;
  21110. }
  21111. /** Blends another pixel with this one, creating a colour that is somewhere
  21112. between the two, as specified by the amount.
  21113. */
  21114. template <class Pixel>
  21115. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  21116. {
  21117. uint32 drb = getRB();
  21118. drb += (((src.getRB() - drb) * amount) >> 8);
  21119. drb &= 0x00ff00ff;
  21120. uint32 dag = getAG();
  21121. dag += (((src.getAG() - dag) * amount) >> 8);
  21122. dag &= 0x00ff00ff;
  21123. dag <<= 8;
  21124. dag |= drb;
  21125. argb = dag;
  21126. }
  21127. /** Copies another pixel colour over this one.
  21128. This doesn't blend it - this colour is simply replaced by the other one.
  21129. */
  21130. template <class Pixel>
  21131. forcedinline void set (const Pixel& src) throw()
  21132. {
  21133. argb = src.getARGB();
  21134. }
  21135. /** Replaces the colour's alpha value with another one. */
  21136. forcedinline void setAlpha (const uint8 newAlpha) throw()
  21137. {
  21138. components.a = newAlpha;
  21139. }
  21140. /** Multiplies the colour's alpha value with another one. */
  21141. forcedinline void multiplyAlpha (int multiplier) throw()
  21142. {
  21143. ++multiplier;
  21144. argb = ((multiplier * getAG()) & 0xff00ff00)
  21145. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  21146. }
  21147. forcedinline void multiplyAlpha (const float multiplier) throw()
  21148. {
  21149. multiplyAlpha ((int) (multiplier * 256.0f));
  21150. }
  21151. /** Sets the pixel's colour from individual components. */
  21152. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  21153. {
  21154. components.b = b;
  21155. components.g = g;
  21156. components.r = r;
  21157. components.a = a;
  21158. }
  21159. /** Premultiplies the pixel's RGB values by its alpha. */
  21160. forcedinline void premultiply() throw()
  21161. {
  21162. const uint32 alpha = components.a;
  21163. if (alpha < 0xff)
  21164. {
  21165. if (alpha == 0)
  21166. {
  21167. components.b = 0;
  21168. components.g = 0;
  21169. components.r = 0;
  21170. }
  21171. else
  21172. {
  21173. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  21174. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  21175. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  21176. }
  21177. }
  21178. }
  21179. /** Unpremultiplies the pixel's RGB values. */
  21180. forcedinline void unpremultiply() throw()
  21181. {
  21182. const uint32 alpha = components.a;
  21183. if (alpha < 0xff)
  21184. {
  21185. if (alpha == 0)
  21186. {
  21187. components.b = 0;
  21188. components.g = 0;
  21189. components.r = 0;
  21190. }
  21191. else
  21192. {
  21193. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  21194. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  21195. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  21196. }
  21197. }
  21198. }
  21199. forcedinline void desaturate() throw()
  21200. {
  21201. if (components.a < 0xff && components.a > 0)
  21202. {
  21203. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  21204. components.r = components.g = components.b
  21205. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  21206. }
  21207. else
  21208. {
  21209. components.r = components.g = components.b
  21210. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  21211. }
  21212. }
  21213. /** The indexes of the different components in the byte layout of this type of colour. */
  21214. #if JUCE_BIG_ENDIAN
  21215. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  21216. #else
  21217. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  21218. #endif
  21219. private:
  21220. union
  21221. {
  21222. uint32 argb;
  21223. struct
  21224. {
  21225. #if JUCE_BIG_ENDIAN
  21226. uint8 a : 8, r : 8, g : 8, b : 8;
  21227. #else
  21228. uint8 b, g, r, a;
  21229. #endif
  21230. } PACKED components;
  21231. };
  21232. }
  21233. #ifndef DOXYGEN
  21234. PACKED
  21235. #endif
  21236. ;
  21237. /**
  21238. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  21239. This is used internally by the imaging classes.
  21240. @see PixelARGB
  21241. */
  21242. class JUCE_API PixelRGB
  21243. {
  21244. public:
  21245. /** Creates a pixel without defining its colour. */
  21246. PixelRGB() throw() {}
  21247. ~PixelRGB() throw() {}
  21248. /** Creates a pixel from a 32-bit argb value.
  21249. (The argb format is that used by PixelARGB)
  21250. */
  21251. PixelRGB (const uint32 argb) throw()
  21252. {
  21253. r = (uint8) (argb >> 16);
  21254. g = (uint8) (argb >> 8);
  21255. b = (uint8) (argb);
  21256. }
  21257. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  21258. forcedinline uint32 getUnpremultipliedARGB() const throw() { return getARGB(); }
  21259. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  21260. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  21261. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  21262. forcedinline uint8 getRed() const throw() { return r; }
  21263. forcedinline uint8 getGreen() const throw() { return g; }
  21264. forcedinline uint8 getBlue() const throw() { return b; }
  21265. /** Blends another pixel onto this one.
  21266. This takes into account the opacity of the pixel being overlaid, and blends
  21267. it accordingly.
  21268. */
  21269. forcedinline void blend (const PixelARGB& src) throw()
  21270. {
  21271. uint32 sargb = src.getARGB();
  21272. const uint32 alpha = 0x100 - (sargb >> 24);
  21273. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21274. sargb += 0x0000ff00 & (g * alpha);
  21275. r = (uint8) (sargb >> 16);
  21276. g = (uint8) (sargb >> 8);
  21277. b = (uint8) sargb;
  21278. }
  21279. forcedinline void blend (const PixelRGB& src) throw()
  21280. {
  21281. set (src);
  21282. }
  21283. forcedinline void blend (const PixelAlpha& src) throw();
  21284. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21285. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21286. being used, so this can blend semi-transparently from a PixelRGB argument.
  21287. */
  21288. template <class Pixel>
  21289. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  21290. {
  21291. ++extraAlpha;
  21292. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  21293. const uint32 sag = extraAlpha * src.getAG();
  21294. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  21295. const uint32 alpha = 0x100 - (sargb >> 24);
  21296. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21297. sargb += 0x0000ff00 & (g * alpha);
  21298. b = (uint8) sargb;
  21299. g = (uint8) (sargb >> 8);
  21300. r = (uint8) (sargb >> 16);
  21301. }
  21302. /** Blends another pixel with this one, creating a colour that is somewhere
  21303. between the two, as specified by the amount.
  21304. */
  21305. template <class Pixel>
  21306. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  21307. {
  21308. uint32 drb = getRB();
  21309. drb += (((src.getRB() - drb) * amount) >> 8);
  21310. uint32 dag = getAG();
  21311. dag += (((src.getAG() - dag) * amount) >> 8);
  21312. b = (uint8) drb;
  21313. g = (uint8) dag;
  21314. r = (uint8) (drb >> 16);
  21315. }
  21316. /** Copies another pixel colour over this one.
  21317. This doesn't blend it - this colour is simply replaced by the other one.
  21318. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  21319. is thrown away.
  21320. */
  21321. template <class Pixel>
  21322. forcedinline void set (const Pixel& src) throw()
  21323. {
  21324. b = src.getBlue();
  21325. g = src.getGreen();
  21326. r = src.getRed();
  21327. }
  21328. /** This method is included for compatibility with the PixelARGB class. */
  21329. forcedinline void setAlpha (const uint8) throw() {}
  21330. /** Multiplies the colour's alpha value with another one. */
  21331. forcedinline void multiplyAlpha (int) throw() {}
  21332. /** Sets the pixel's colour from individual components. */
  21333. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  21334. {
  21335. r = r_;
  21336. g = g_;
  21337. b = b_;
  21338. }
  21339. /** Premultiplies the pixel's RGB values by its alpha. */
  21340. forcedinline void premultiply() throw() {}
  21341. /** Unpremultiplies the pixel's RGB values. */
  21342. forcedinline void unpremultiply() throw() {}
  21343. forcedinline void desaturate() throw()
  21344. {
  21345. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  21346. }
  21347. /** The indexes of the different components in the byte layout of this type of colour. */
  21348. #if JUCE_MAC
  21349. enum { indexR = 0, indexG = 1, indexB = 2 };
  21350. #else
  21351. enum { indexR = 2, indexG = 1, indexB = 0 };
  21352. #endif
  21353. private:
  21354. #if JUCE_MAC
  21355. uint8 r, g, b;
  21356. #else
  21357. uint8 b, g, r;
  21358. #endif
  21359. }
  21360. #ifndef DOXYGEN
  21361. PACKED
  21362. #endif
  21363. ;
  21364. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  21365. {
  21366. set (src);
  21367. }
  21368. /**
  21369. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  21370. This is used internally by the imaging classes.
  21371. @see PixelARGB, PixelRGB
  21372. */
  21373. class JUCE_API PixelAlpha
  21374. {
  21375. public:
  21376. /** Creates a pixel without defining its colour. */
  21377. PixelAlpha() throw() {}
  21378. ~PixelAlpha() throw() {}
  21379. /** Creates a pixel from a 32-bit argb value.
  21380. (The argb format is that used by PixelARGB)
  21381. */
  21382. PixelAlpha (const uint32 argb) throw()
  21383. {
  21384. a = (uint8) (argb >> 24);
  21385. }
  21386. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  21387. forcedinline uint32 getUnpremultipliedARGB() const throw() { return (((uint32) a) << 24) | 0xffffff; }
  21388. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  21389. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  21390. forcedinline uint8 getAlpha() const throw() { return a; }
  21391. forcedinline uint8 getRed() const throw() { return 0; }
  21392. forcedinline uint8 getGreen() const throw() { return 0; }
  21393. forcedinline uint8 getBlue() const throw() { return 0; }
  21394. /** Blends another pixel onto this one.
  21395. This takes into account the opacity of the pixel being overlaid, and blends
  21396. it accordingly.
  21397. */
  21398. template <class Pixel>
  21399. forcedinline void blend (const Pixel& src) throw()
  21400. {
  21401. const int srcA = src.getAlpha();
  21402. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  21403. }
  21404. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  21405. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  21406. being used, so this can blend semi-transparently from a PixelRGB argument.
  21407. */
  21408. template <class Pixel>
  21409. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  21410. {
  21411. ++extraAlpha;
  21412. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  21413. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  21414. }
  21415. /** Blends another pixel with this one, creating a colour that is somewhere
  21416. between the two, as specified by the amount.
  21417. */
  21418. template <class Pixel>
  21419. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  21420. {
  21421. a += ((src,getAlpha() - a) * amount) >> 8;
  21422. }
  21423. /** Copies another pixel colour over this one.
  21424. This doesn't blend it - this colour is simply replaced by the other one.
  21425. */
  21426. template <class Pixel>
  21427. forcedinline void set (const Pixel& src) throw()
  21428. {
  21429. a = src.getAlpha();
  21430. }
  21431. /** Replaces the colour's alpha value with another one. */
  21432. forcedinline void setAlpha (const uint8 newAlpha) throw()
  21433. {
  21434. a = newAlpha;
  21435. }
  21436. /** Multiplies the colour's alpha value with another one. */
  21437. forcedinline void multiplyAlpha (int multiplier) throw()
  21438. {
  21439. ++multiplier;
  21440. a = (uint8) ((a * multiplier) >> 8);
  21441. }
  21442. forcedinline void multiplyAlpha (const float multiplier) throw()
  21443. {
  21444. a = (uint8) (a * multiplier);
  21445. }
  21446. /** Sets the pixel's colour from individual components. */
  21447. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  21448. {
  21449. a = a_;
  21450. }
  21451. /** Premultiplies the pixel's RGB values by its alpha. */
  21452. forcedinline void premultiply() throw()
  21453. {
  21454. }
  21455. /** Unpremultiplies the pixel's RGB values. */
  21456. forcedinline void unpremultiply() throw()
  21457. {
  21458. }
  21459. forcedinline void desaturate() throw()
  21460. {
  21461. }
  21462. /** The indexes of the different components in the byte layout of this type of colour. */
  21463. enum { indexA = 0 };
  21464. private:
  21465. uint8 a : 8;
  21466. }
  21467. #ifndef DOXYGEN
  21468. PACKED
  21469. #endif
  21470. ;
  21471. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  21472. {
  21473. blend (PixelARGB (src.getARGB()));
  21474. }
  21475. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  21476. {
  21477. uint32 sargb = src.getARGB();
  21478. const uint32 alpha = 0x100 - (sargb >> 24);
  21479. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21480. sargb += 0xff00ff00 & (getAG() * alpha);
  21481. argb = sargb;
  21482. }
  21483. #if JUCE_MSVC
  21484. #pragma pack (pop)
  21485. #endif
  21486. #undef PACKED
  21487. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  21488. /*** End of inlined file: juce_PixelFormats.h ***/
  21489. /**
  21490. Represents a colour, also including a transparency value.
  21491. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  21492. */
  21493. class JUCE_API Colour
  21494. {
  21495. public:
  21496. /** Creates a transparent black colour. */
  21497. Colour() throw();
  21498. /** Creates a copy of another Colour object. */
  21499. Colour (const Colour& other) throw();
  21500. /** Creates a colour from a 32-bit ARGB value.
  21501. The format of this number is:
  21502. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  21503. All components in the range 0x00 to 0xff.
  21504. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21505. @see getPixelARGB
  21506. */
  21507. explicit Colour (uint32 argb) throw();
  21508. /** Creates an opaque colour using 8-bit red, green and blue values */
  21509. Colour (uint8 red,
  21510. uint8 green,
  21511. uint8 blue) throw();
  21512. /** Creates an opaque colour using 8-bit red, green and blue values */
  21513. static const Colour fromRGB (uint8 red,
  21514. uint8 green,
  21515. uint8 blue) throw();
  21516. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21517. Colour (uint8 red,
  21518. uint8 green,
  21519. uint8 blue,
  21520. uint8 alpha) throw();
  21521. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21522. static const Colour fromRGBA (uint8 red,
  21523. uint8 green,
  21524. uint8 blue,
  21525. uint8 alpha) throw();
  21526. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  21527. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  21528. Values outside the valid range will be clipped.
  21529. */
  21530. Colour (uint8 red,
  21531. uint8 green,
  21532. uint8 blue,
  21533. float alpha) throw();
  21534. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  21535. static const Colour fromRGBAFloat (uint8 red,
  21536. uint8 green,
  21537. uint8 blue,
  21538. float alpha) throw();
  21539. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21540. The floating point values must be between 0.0 and 1.0.
  21541. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21542. Values outside the valid range will be clipped.
  21543. */
  21544. Colour (float hue,
  21545. float saturation,
  21546. float brightness,
  21547. uint8 alpha) throw();
  21548. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  21549. All values must be between 0.0 and 1.0.
  21550. Numbers outside the valid range will be clipped.
  21551. */
  21552. Colour (float hue,
  21553. float saturation,
  21554. float brightness,
  21555. float alpha) throw();
  21556. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21557. The floating point values must be between 0.0 and 1.0.
  21558. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21559. Values outside the valid range will be clipped.
  21560. */
  21561. static const Colour fromHSV (float hue,
  21562. float saturation,
  21563. float brightness,
  21564. float alpha) throw();
  21565. /** Destructor. */
  21566. ~Colour() throw();
  21567. /** Copies another Colour object. */
  21568. Colour& operator= (const Colour& other) throw();
  21569. /** Compares two colours. */
  21570. bool operator== (const Colour& other) const throw();
  21571. /** Compares two colours. */
  21572. bool operator!= (const Colour& other) const throw();
  21573. /** Returns the red component of this colour.
  21574. @returns a value between 0x00 and 0xff.
  21575. */
  21576. uint8 getRed() const throw() { return argb.getRed(); }
  21577. /** Returns the green component of this colour.
  21578. @returns a value between 0x00 and 0xff.
  21579. */
  21580. uint8 getGreen() const throw() { return argb.getGreen(); }
  21581. /** Returns the blue component of this colour.
  21582. @returns a value between 0x00 and 0xff.
  21583. */
  21584. uint8 getBlue() const throw() { return argb.getBlue(); }
  21585. /** Returns the red component of this colour as a floating point value.
  21586. @returns a value between 0.0 and 1.0
  21587. */
  21588. float getFloatRed() const throw();
  21589. /** Returns the green component of this colour as a floating point value.
  21590. @returns a value between 0.0 and 1.0
  21591. */
  21592. float getFloatGreen() const throw();
  21593. /** Returns the blue component of this colour as a floating point value.
  21594. @returns a value between 0.0 and 1.0
  21595. */
  21596. float getFloatBlue() const throw();
  21597. /** Returns a premultiplied ARGB pixel object that represents this colour.
  21598. */
  21599. const PixelARGB getPixelARGB() const throw();
  21600. /** Returns a 32-bit integer that represents this colour.
  21601. The format of this number is:
  21602. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  21603. */
  21604. uint32 getARGB() const throw();
  21605. /** Returns the colour's alpha (opacity).
  21606. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  21607. */
  21608. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  21609. /** Returns the colour's alpha (opacity) as a floating point value.
  21610. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  21611. */
  21612. float getFloatAlpha() const throw();
  21613. /** Returns true if this colour is completely opaque.
  21614. Equivalent to (getAlpha() == 0xff).
  21615. */
  21616. bool isOpaque() const throw();
  21617. /** Returns true if this colour is completely transparent.
  21618. Equivalent to (getAlpha() == 0x00).
  21619. */
  21620. bool isTransparent() const throw();
  21621. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21622. const Colour withAlpha (uint8 newAlpha) const throw();
  21623. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21624. const Colour withAlpha (float newAlpha) const throw();
  21625. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  21626. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  21627. */
  21628. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  21629. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  21630. If the foreground colour is semi-transparent, it is blended onto this colour
  21631. accordingly.
  21632. */
  21633. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  21634. /** Returns a colour that lies somewhere between this one and another.
  21635. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  21636. is 1.0, the result is 100% of the other colour.
  21637. */
  21638. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  21639. /** Returns the colour's hue component.
  21640. The value returned is in the range 0.0 to 1.0
  21641. */
  21642. float getHue() const throw();
  21643. /** Returns the colour's saturation component.
  21644. The value returned is in the range 0.0 to 1.0
  21645. */
  21646. float getSaturation() const throw();
  21647. /** Returns the colour's brightness component.
  21648. The value returned is in the range 0.0 to 1.0
  21649. */
  21650. float getBrightness() const throw();
  21651. /** Returns the colour's hue, saturation and brightness components all at once.
  21652. The values returned are in the range 0.0 to 1.0
  21653. */
  21654. void getHSB (float& hue,
  21655. float& saturation,
  21656. float& brightness) const throw();
  21657. /** Returns a copy of this colour with a different hue. */
  21658. const Colour withHue (float newHue) const throw();
  21659. /** Returns a copy of this colour with a different saturation. */
  21660. const Colour withSaturation (float newSaturation) const throw();
  21661. /** Returns a copy of this colour with a different brightness.
  21662. @see brighter, darker, withMultipliedBrightness
  21663. */
  21664. const Colour withBrightness (float newBrightness) const throw();
  21665. /** Returns a copy of this colour with it hue rotated.
  21666. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  21667. @see brighter, darker, withMultipliedBrightness
  21668. */
  21669. const Colour withRotatedHue (float amountToRotate) const throw();
  21670. /** Returns a copy of this colour with its saturation multiplied by the given value.
  21671. The new colour's saturation is (this->getSaturation() * multiplier)
  21672. (the result is clipped to legal limits).
  21673. */
  21674. const Colour withMultipliedSaturation (float multiplier) const throw();
  21675. /** Returns a copy of this colour with its brightness multiplied by the given value.
  21676. The new colour's saturation is (this->getBrightness() * multiplier)
  21677. (the result is clipped to legal limits).
  21678. */
  21679. const Colour withMultipliedBrightness (float amount) const throw();
  21680. /** Returns a brighter version of this colour.
  21681. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  21682. unchanged, and higher values make it brighter
  21683. @see withMultipliedBrightness
  21684. */
  21685. const Colour brighter (float amountBrighter = 0.4f) const throw();
  21686. /** Returns a darker version of this colour.
  21687. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  21688. unchanged, and higher values make it darker
  21689. @see withMultipliedBrightness
  21690. */
  21691. const Colour darker (float amountDarker = 0.4f) const throw();
  21692. /** Returns a colour that will be clearly visible against this colour.
  21693. The amount parameter indicates how contrasting the new colour should
  21694. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  21695. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  21696. return white; Colours::white.contrasting (1.0f) will return black, etc.
  21697. */
  21698. const Colour contrasting (float amount = 1.0f) const throw();
  21699. /** Returns a colour that contrasts against two colours.
  21700. Looks for a colour that contrasts with both of the colours passed-in.
  21701. Handy for things like choosing a highlight colour in text editors, etc.
  21702. */
  21703. static const Colour contrasting (const Colour& colour1,
  21704. const Colour& colour2) throw();
  21705. /** Returns an opaque shade of grey.
  21706. @param brightness the level of grey to return - 0 is black, 1.0 is white
  21707. */
  21708. static const Colour greyLevel (float brightness) throw();
  21709. /** Returns a stringified version of this colour.
  21710. The string can be turned back into a colour using the fromString() method.
  21711. */
  21712. const String toString() const;
  21713. /** Reads the colour from a string that was created with toString().
  21714. */
  21715. static const Colour fromString (const String& encodedColourString);
  21716. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  21717. const String toDisplayString (bool includeAlphaValue) const;
  21718. private:
  21719. PixelARGB argb;
  21720. };
  21721. #endif // __JUCE_COLOUR_JUCEHEADER__
  21722. /*** End of inlined file: juce_Colour.h ***/
  21723. /**
  21724. Contains a set of predefined named colours (mostly standard HTML colours)
  21725. @see Colour, Colours::greyLevel
  21726. */
  21727. class Colours
  21728. {
  21729. public:
  21730. static JUCE_API const Colour
  21731. transparentBlack, /**< ARGB = 0x00000000 */
  21732. transparentWhite, /**< ARGB = 0x00ffffff */
  21733. black, /**< ARGB = 0xff000000 */
  21734. white, /**< ARGB = 0xffffffff */
  21735. blue, /**< ARGB = 0xff0000ff */
  21736. grey, /**< ARGB = 0xff808080 */
  21737. green, /**< ARGB = 0xff008000 */
  21738. red, /**< ARGB = 0xffff0000 */
  21739. yellow, /**< ARGB = 0xffffff00 */
  21740. aliceblue, antiquewhite, aqua, aquamarine,
  21741. azure, beige, bisque, blanchedalmond,
  21742. blueviolet, brown, burlywood, cadetblue,
  21743. chartreuse, chocolate, coral, cornflowerblue,
  21744. cornsilk, crimson, cyan, darkblue,
  21745. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  21746. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  21747. darkorchid, darkred, darksalmon, darkseagreen,
  21748. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  21749. deeppink, deepskyblue, dimgrey, dodgerblue,
  21750. firebrick, floralwhite, forestgreen, fuchsia,
  21751. gainsboro, gold, goldenrod, greenyellow,
  21752. honeydew, hotpink, indianred, indigo,
  21753. ivory, khaki, lavender, lavenderblush,
  21754. lemonchiffon, lightblue, lightcoral, lightcyan,
  21755. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  21756. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  21757. lightsteelblue, lightyellow, lime, limegreen,
  21758. linen, magenta, maroon, mediumaquamarine,
  21759. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  21760. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  21761. midnightblue, mintcream, mistyrose, navajowhite,
  21762. navy, oldlace, olive, olivedrab,
  21763. orange, orangered, orchid, palegoldenrod,
  21764. palegreen, paleturquoise, palevioletred, papayawhip,
  21765. peachpuff, peru, pink, plum,
  21766. powderblue, purple, rosybrown, royalblue,
  21767. saddlebrown, salmon, sandybrown, seagreen,
  21768. seashell, sienna, silver, skyblue,
  21769. slateblue, slategrey, snow, springgreen,
  21770. steelblue, tan, teal, thistle,
  21771. tomato, turquoise, violet, wheat,
  21772. whitesmoke, yellowgreen;
  21773. /** Attempts to look up a string in the list of known colour names, and return
  21774. the appropriate colour.
  21775. A non-case-sensitive search is made of the list of predefined colours, and
  21776. if a match is found, that colour is returned. If no match is found, the
  21777. colour passed in as the defaultColour parameter is returned.
  21778. */
  21779. static JUCE_API const Colour findColourForName (const String& colourName,
  21780. const Colour& defaultColour);
  21781. private:
  21782. // this isn't a class you should ever instantiate - it's just here for the
  21783. // static values in it.
  21784. Colours();
  21785. JUCE_DECLARE_NON_COPYABLE (Colours);
  21786. };
  21787. #endif // __JUCE_COLOURS_JUCEHEADER__
  21788. /*** End of inlined file: juce_Colours.h ***/
  21789. /*** Start of inlined file: juce_ColourGradient.h ***/
  21790. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  21791. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  21792. /**
  21793. Describes the layout and colours that should be used to paint a colour gradient.
  21794. @see Graphics::setGradientFill
  21795. */
  21796. class JUCE_API ColourGradient
  21797. {
  21798. public:
  21799. /** Creates a gradient object.
  21800. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  21801. colour2 should be. In between them there's a gradient.
  21802. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  21803. its centre.
  21804. The alpha transparencies of the colours are used, so note that
  21805. if you blend from transparent to a solid colour, the RGB of the transparent
  21806. colour will become visible in parts of the gradient. e.g. blending
  21807. from Colour::transparentBlack to Colours::white will produce a
  21808. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  21809. will be white all the way across.
  21810. @see ColourGradient
  21811. */
  21812. ColourGradient (const Colour& colour1, float x1, float y1,
  21813. const Colour& colour2, float x2, float y2,
  21814. bool isRadial);
  21815. /** Creates an uninitialised gradient.
  21816. If you use this constructor instead of the other one, be sure to set all the
  21817. object's public member variables before using it!
  21818. */
  21819. ColourGradient() throw();
  21820. /** Destructor */
  21821. ~ColourGradient();
  21822. /** Removes any colours that have been added.
  21823. This will also remove any start and end colours, so the gradient won't work. You'll
  21824. need to add more colours with addColour().
  21825. */
  21826. void clearColours();
  21827. /** Adds a colour at a point along the length of the gradient.
  21828. This allows the gradient to go through a spectrum of colours, instead of just a
  21829. start and end colour.
  21830. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  21831. of the distance along the line between the two points
  21832. at which the colour should occur.
  21833. @param colour the colour that should be used at this point
  21834. @returns the index at which the new point was added
  21835. */
  21836. int addColour (double proportionAlongGradient,
  21837. const Colour& colour);
  21838. /** Removes one of the colours from the gradient. */
  21839. void removeColour (int index);
  21840. /** Multiplies the alpha value of all the colours by the given scale factor */
  21841. void multiplyOpacity (float multiplier) throw();
  21842. /** Returns the number of colour-stops that have been added. */
  21843. int getNumColours() const throw();
  21844. /** Returns the position along the length of the gradient of the colour with this index.
  21845. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  21846. */
  21847. double getColourPosition (int index) const throw();
  21848. /** Returns the colour that was added with a given index.
  21849. The index is from 0 to getNumColours() - 1.
  21850. */
  21851. const Colour getColour (int index) const throw();
  21852. /** Changes the colour at a given index.
  21853. The index is from 0 to getNumColours() - 1.
  21854. */
  21855. void setColour (int index, const Colour& newColour) throw();
  21856. /** Returns the an interpolated colour at any position along the gradient.
  21857. @param position the position along the gradient, between 0 and 1
  21858. */
  21859. const Colour getColourAtPosition (double position) const throw();
  21860. /** Creates a set of interpolated premultiplied ARGB values.
  21861. This will resize the HeapBlock, fill it with the colours, and will return the number of
  21862. colours that it added.
  21863. */
  21864. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  21865. /** Returns true if all colours are opaque. */
  21866. bool isOpaque() const throw();
  21867. /** Returns true if all colours are completely transparent. */
  21868. bool isInvisible() const throw();
  21869. Point<float> point1, point2;
  21870. /** If true, the gradient should be filled circularly, centred around
  21871. point1, with point2 defining a point on the circumference.
  21872. If false, the gradient is linear between the two points.
  21873. */
  21874. bool isRadial;
  21875. bool operator== (const ColourGradient& other) const throw();
  21876. bool operator!= (const ColourGradient& other) const throw();
  21877. private:
  21878. struct ColourPoint
  21879. {
  21880. ColourPoint() throw() {}
  21881. ColourPoint (const double position_, const Colour& colour_) throw()
  21882. : position (position_), colour (colour_)
  21883. {}
  21884. bool operator== (const ColourPoint& other) const throw();
  21885. bool operator!= (const ColourPoint& other) const throw();
  21886. double position;
  21887. Colour colour;
  21888. };
  21889. Array <ColourPoint> colours;
  21890. JUCE_LEAK_DETECTOR (ColourGradient);
  21891. };
  21892. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  21893. /*** End of inlined file: juce_ColourGradient.h ***/
  21894. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  21895. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21896. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21897. /**
  21898. Defines the method used to postion some kind of rectangular object within
  21899. a rectangular viewport.
  21900. Although similar to Justification, this is more specific, and has some extra
  21901. options.
  21902. */
  21903. class JUCE_API RectanglePlacement
  21904. {
  21905. public:
  21906. /** Creates a RectanglePlacement object using a combination of flags. */
  21907. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  21908. /** Creates a copy of another RectanglePlacement object. */
  21909. RectanglePlacement (const RectanglePlacement& other) throw();
  21910. /** Copies another RectanglePlacement object. */
  21911. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  21912. /** Flag values that can be combined and used in the constructor. */
  21913. enum
  21914. {
  21915. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  21916. xLeft = 1,
  21917. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  21918. xRight = 2,
  21919. /** Indicates that the source should be placed in the centre between the left and right
  21920. sides of the available space. */
  21921. xMid = 4,
  21922. /** Indicates that the source's top edge should be aligned with the top edge of the
  21923. destination rectangle. */
  21924. yTop = 8,
  21925. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  21926. destination rectangle. */
  21927. yBottom = 16,
  21928. /** Indicates that the source should be placed in the centre between the top and bottom
  21929. sides of the available space. */
  21930. yMid = 32,
  21931. /** If this flag is set, then the source rectangle will be resized to completely fill
  21932. the destination rectangle, and all other flags are ignored.
  21933. */
  21934. stretchToFit = 64,
  21935. /** If this flag is set, then the source rectangle will be resized so that it is the
  21936. minimum size to completely fill the destination rectangle, without changing its
  21937. aspect ratio. This means that some of the source rectangle may fall outside
  21938. the destination.
  21939. If this flag is not set, the source will be given the maximum size at which none
  21940. of it falls outside the destination rectangle.
  21941. */
  21942. fillDestination = 128,
  21943. /** Indicates that the source rectangle can be reduced in size if required, but should
  21944. never be made larger than its original size.
  21945. */
  21946. onlyReduceInSize = 256,
  21947. /** Indicates that the source rectangle can be enlarged if required, but should
  21948. never be made smaller than its original size.
  21949. */
  21950. onlyIncreaseInSize = 512,
  21951. /** Indicates that the source rectangle's size should be left unchanged.
  21952. */
  21953. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  21954. /** A shorthand value that is equivalent to (xMid | yMid). */
  21955. centred = 4 + 32
  21956. };
  21957. /** Returns the raw flags that are set for this object. */
  21958. inline int getFlags() const throw() { return flags; }
  21959. /** Tests a set of flags for this object.
  21960. @returns true if any of the flags passed in are set on this object.
  21961. */
  21962. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  21963. /** Adjusts the position and size of a rectangle to fit it into a space.
  21964. The source rectangle co-ordinates will be adjusted so that they fit into
  21965. the destination rectangle based on this object's flags.
  21966. */
  21967. void applyTo (double& sourceX,
  21968. double& sourceY,
  21969. double& sourceW,
  21970. double& sourceH,
  21971. double destinationX,
  21972. double destinationY,
  21973. double destinationW,
  21974. double destinationH) const throw();
  21975. /** Returns the transform that should be applied to these source co-ordinates to fit them
  21976. into the destination rectangle using the current flags.
  21977. */
  21978. template <typename ValueType>
  21979. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  21980. const Rectangle<ValueType>& destination) const throw()
  21981. {
  21982. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  21983. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  21984. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  21985. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  21986. static_cast <ValueType> (w), static_cast <ValueType> (h));
  21987. }
  21988. /** Returns the transform that should be applied to these source co-ordinates to fit them
  21989. into the destination rectangle using the current flags.
  21990. */
  21991. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  21992. const Rectangle<float>& destination) const throw();
  21993. private:
  21994. int flags;
  21995. };
  21996. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21997. /*** End of inlined file: juce_RectanglePlacement.h ***/
  21998. class LowLevelGraphicsContext;
  21999. class Image;
  22000. class FillType;
  22001. class RectangleList;
  22002. /**
  22003. A graphics context, used for drawing a component or image.
  22004. When a Component needs painting, a Graphics context is passed to its
  22005. Component::paint() method, and this you then call methods within this
  22006. object to actually draw the component's content.
  22007. A Graphics can also be created from an image, to allow drawing directly onto
  22008. that image.
  22009. @see Component::paint
  22010. */
  22011. class JUCE_API Graphics
  22012. {
  22013. public:
  22014. /** Creates a Graphics object to draw directly onto the given image.
  22015. The graphics object that is created will be set up to draw onto the image,
  22016. with the context's clipping area being the entire size of the image, and its
  22017. origin being the image's origin. To draw into a subsection of an image, use the
  22018. reduceClipRegion() and setOrigin() methods.
  22019. Obviously you shouldn't delete the image before this context is deleted.
  22020. */
  22021. explicit Graphics (const Image& imageToDrawOnto);
  22022. /** Destructor. */
  22023. ~Graphics();
  22024. /** Changes the current drawing colour.
  22025. This sets the colour that will now be used for drawing operations - it also
  22026. sets the opacity to that of the colour passed-in.
  22027. If a brush is being used when this method is called, the brush will be deselected,
  22028. and any subsequent drawing will be done with a solid colour brush instead.
  22029. @see setOpacity
  22030. */
  22031. void setColour (const Colour& newColour);
  22032. /** Changes the opacity to use with the current colour.
  22033. If a solid colour is being used for drawing, this changes its opacity
  22034. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  22035. If a gradient is being used, this will have no effect on it.
  22036. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  22037. */
  22038. void setOpacity (float newOpacity);
  22039. /** Sets the context to use a gradient for its fill pattern.
  22040. */
  22041. void setGradientFill (const ColourGradient& gradient);
  22042. /** Sets the context to use a tiled image pattern for filling.
  22043. Make sure that you don't delete this image while it's still being used by
  22044. this context!
  22045. */
  22046. void setTiledImageFill (const Image& imageToUse,
  22047. int anchorX, int anchorY,
  22048. float opacity);
  22049. /** Changes the current fill settings.
  22050. @see setColour, setGradientFill, setTiledImageFill
  22051. */
  22052. void setFillType (const FillType& newFill);
  22053. /** Changes the font to use for subsequent text-drawing functions.
  22054. Note there's also a setFont (float, int) method to quickly change the size and
  22055. style of the current font.
  22056. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  22057. */
  22058. void setFont (const Font& newFont);
  22059. /** Changes the size and style of the currently-selected font.
  22060. This is a convenient shortcut that changes the context's current font to a
  22061. different size or style. The typeface won't be changed.
  22062. @see Font
  22063. */
  22064. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  22065. /** Returns the currently selected font. */
  22066. const Font getCurrentFont() const;
  22067. /** Draws a one-line text string.
  22068. This will use the current colour (or brush) to fill the text. The font is the last
  22069. one specified by setFont().
  22070. @param text the string to draw
  22071. @param startX the position to draw the left-hand edge of the text
  22072. @param baselineY the position of the text's baseline
  22073. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  22074. */
  22075. void drawSingleLineText (const String& text,
  22076. int startX, int baselineY) const;
  22077. /** Draws text across multiple lines.
  22078. This will break the text onto a new line where there's a new-line or
  22079. carriage-return character, or at a word-boundary when the text becomes wider
  22080. than the size specified by the maximumLineWidth parameter.
  22081. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  22082. */
  22083. void drawMultiLineText (const String& text,
  22084. int startX, int baselineY,
  22085. int maximumLineWidth) const;
  22086. /** Renders a string of text as a vector path.
  22087. This allows a string to be transformed with an arbitrary AffineTransform and
  22088. rendered using the current colour/brush. It's much slower than the normal text methods
  22089. but more accurate.
  22090. @see setFont
  22091. */
  22092. void drawTextAsPath (const String& text,
  22093. const AffineTransform& transform) const;
  22094. /** Draws a line of text within a specified rectangle.
  22095. The text will be positioned within the rectangle based on the justification
  22096. flags passed-in. If the string is too long to fit inside the rectangle, it will
  22097. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  22098. flag is true).
  22099. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  22100. */
  22101. void drawText (const String& text,
  22102. int x, int y, int width, int height,
  22103. const Justification& justificationType,
  22104. bool useEllipsesIfTooBig) const;
  22105. /** Tries to draw a text string inside a given space.
  22106. This does its best to make the given text readable within the specified rectangle,
  22107. so it useful for labelling things.
  22108. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  22109. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  22110. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  22111. it's been truncated.
  22112. A Justification parameter lets you specify how the text is laid out within the rectangle,
  22113. both horizontally and vertically.
  22114. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  22115. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  22116. can set this value to 1.0f.
  22117. @see GlyphArrangement::addFittedText
  22118. */
  22119. void drawFittedText (const String& text,
  22120. int x, int y, int width, int height,
  22121. const Justification& justificationFlags,
  22122. int maximumNumberOfLines,
  22123. float minimumHorizontalScale = 0.7f) const;
  22124. /** Fills the context's entire clip region with the current colour or brush.
  22125. (See also the fillAll (const Colour&) method which is a quick way of filling
  22126. it with a given colour).
  22127. */
  22128. void fillAll() const;
  22129. /** Fills the context's entire clip region with a given colour.
  22130. This leaves the context's current colour and brush unchanged, it just
  22131. uses the specified colour temporarily.
  22132. */
  22133. void fillAll (const Colour& colourToUse) const;
  22134. /** Fills a rectangle with the current colour or brush.
  22135. @see drawRect, fillRoundedRectangle
  22136. */
  22137. void fillRect (int x, int y, int width, int height) const;
  22138. /** Fills a rectangle with the current colour or brush. */
  22139. void fillRect (const Rectangle<int>& rectangle) const;
  22140. /** Fills a rectangle with the current colour or brush.
  22141. This uses sub-pixel positioning so is slower than the fillRect method which
  22142. takes integer co-ordinates.
  22143. */
  22144. void fillRect (float x, float y, float width, float height) const;
  22145. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22146. @see drawRoundedRectangle, Path::addRoundedRectangle
  22147. */
  22148. void fillRoundedRectangle (float x, float y, float width, float height,
  22149. float cornerSize) const;
  22150. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  22151. @see drawRoundedRectangle, Path::addRoundedRectangle
  22152. */
  22153. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  22154. float cornerSize) const;
  22155. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  22156. */
  22157. void fillCheckerBoard (const Rectangle<int>& area,
  22158. int checkWidth, int checkHeight,
  22159. const Colour& colour1, const Colour& colour2) const;
  22160. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22161. The lines are drawn inside the given rectangle, and greater line thicknesses
  22162. extend inwards.
  22163. @see fillRect
  22164. */
  22165. void drawRect (int x, int y, int width, int height,
  22166. int lineThickness = 1) const;
  22167. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22168. The lines are drawn inside the given rectangle, and greater line thicknesses
  22169. extend inwards.
  22170. @see fillRect
  22171. */
  22172. void drawRect (float x, float y, float width, float height,
  22173. float lineThickness = 1.0f) const;
  22174. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  22175. The lines are drawn inside the given rectangle, and greater line thicknesses
  22176. extend inwards.
  22177. @see fillRect
  22178. */
  22179. void drawRect (const Rectangle<int>& rectangle,
  22180. int lineThickness = 1) const;
  22181. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22182. @see fillRoundedRectangle, Path::addRoundedRectangle
  22183. */
  22184. void drawRoundedRectangle (float x, float y, float width, float height,
  22185. float cornerSize, float lineThickness) const;
  22186. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  22187. @see fillRoundedRectangle, Path::addRoundedRectangle
  22188. */
  22189. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  22190. float cornerSize, float lineThickness) const;
  22191. /** Draws a 3D raised (or indented) bevel using two colours.
  22192. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  22193. extend inwards.
  22194. The top-left colour is used for the top- and left-hand edges of the
  22195. bevel; the bottom-right colour is used for the bottom- and right-hand
  22196. edges.
  22197. If useGradient is true, then the bevel fades out to make it look more curved
  22198. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  22199. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  22200. the centre edges are sharp and it fades towards the outside.
  22201. */
  22202. void drawBevel (int x, int y, int width, int height,
  22203. int bevelThickness,
  22204. const Colour& topLeftColour = Colours::white,
  22205. const Colour& bottomRightColour = Colours::black,
  22206. bool useGradient = true,
  22207. bool sharpEdgeOnOutside = true) const;
  22208. /** Draws a pixel using the current colour or brush.
  22209. */
  22210. void setPixel (int x, int y) const;
  22211. /** Fills an ellipse with the current colour or brush.
  22212. The ellipse is drawn to fit inside the given rectangle.
  22213. @see drawEllipse, Path::addEllipse
  22214. */
  22215. void fillEllipse (float x, float y, float width, float height) const;
  22216. /** Draws an elliptical stroke using the current colour or brush.
  22217. @see fillEllipse, Path::addEllipse
  22218. */
  22219. void drawEllipse (float x, float y, float width, float height,
  22220. float lineThickness) const;
  22221. /** Draws a line between two points.
  22222. The line is 1 pixel wide and drawn with the current colour or brush.
  22223. */
  22224. void drawLine (float startX, float startY, float endX, float endY) const;
  22225. /** Draws a line between two points with a given thickness.
  22226. @see Path::addLineSegment
  22227. */
  22228. void drawLine (float startX, float startY, float endX, float endY,
  22229. float lineThickness) const;
  22230. /** Draws a line between two points.
  22231. The line is 1 pixel wide and drawn with the current colour or brush.
  22232. */
  22233. void drawLine (const Line<float>& line) const;
  22234. /** Draws a line between two points with a given thickness.
  22235. @see Path::addLineSegment
  22236. */
  22237. void drawLine (const Line<float>& line, float lineThickness) const;
  22238. /** Draws a dashed line using a custom set of dash-lengths.
  22239. @param line the line to draw
  22240. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  22241. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  22242. draw 6 pixels, skip 7 pixels, and then repeat.
  22243. @param numDashLengths the number of elements in the array (this must be an even number).
  22244. @param lineThickness the thickness of the line to draw
  22245. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  22246. @see PathStrokeType::createDashedStroke
  22247. */
  22248. void drawDashedLine (const Line<float>& line,
  22249. const float* dashLengths, int numDashLengths,
  22250. float lineThickness = 1.0f,
  22251. int dashIndexToStartFrom = 0) const;
  22252. /** Draws a vertical line of pixels at a given x position.
  22253. The x position is an integer, but the top and bottom of the line can be sub-pixel
  22254. positions, and these will be anti-aliased if necessary.
  22255. */
  22256. void drawVerticalLine (int x, float top, float bottom) const;
  22257. /** Draws a horizontal line of pixels at a given y position.
  22258. The y position is an integer, but the left and right ends of the line can be sub-pixel
  22259. positions, and these will be anti-aliased if necessary.
  22260. */
  22261. void drawHorizontalLine (int y, float left, float right) const;
  22262. /** Fills a path using the currently selected colour or brush.
  22263. */
  22264. void fillPath (const Path& path,
  22265. const AffineTransform& transform = AffineTransform::identity) const;
  22266. /** Draws a path's outline using the currently selected colour or brush.
  22267. */
  22268. void strokePath (const Path& path,
  22269. const PathStrokeType& strokeType,
  22270. const AffineTransform& transform = AffineTransform::identity) const;
  22271. /** Draws a line with an arrowhead at its end.
  22272. @param line the line to draw
  22273. @param lineThickness the thickness of the line
  22274. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  22275. @param arrowheadLength the length of the arrow head (along the length of the line)
  22276. */
  22277. void drawArrow (const Line<float>& line,
  22278. float lineThickness,
  22279. float arrowheadWidth,
  22280. float arrowheadLength) const;
  22281. /** Types of rendering quality that can be specified when drawing images.
  22282. @see blendImage, Graphics::setImageResamplingQuality
  22283. */
  22284. enum ResamplingQuality
  22285. {
  22286. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  22287. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  22288. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  22289. };
  22290. /** Changes the quality that will be used when resampling images.
  22291. By default a Graphics object will be set to mediumRenderingQuality.
  22292. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  22293. */
  22294. void setImageResamplingQuality (const ResamplingQuality newQuality);
  22295. /** Draws an image.
  22296. This will draw the whole of an image, positioning its top-left corner at the
  22297. given co-ordinates, and keeping its size the same. This is the simplest image
  22298. drawing method - the others give more control over the scaling and clipping
  22299. of the images.
  22300. Images are composited using the context's current opacity, so if you
  22301. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22302. (or setColour() with an opaque colour) before drawing images.
  22303. */
  22304. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  22305. bool fillAlphaChannelWithCurrentBrush = false) const;
  22306. /** Draws part of an image, rescaling it to fit in a given target region.
  22307. The specified area of the source image is rescaled and drawn to fill the
  22308. specifed destination rectangle.
  22309. Images are composited using the context's current opacity, so if you
  22310. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22311. (or setColour() with an opaque colour) before drawing images.
  22312. @param imageToDraw the image to overlay
  22313. @param destX the left of the destination rectangle
  22314. @param destY the top of the destination rectangle
  22315. @param destWidth the width of the destination rectangle
  22316. @param destHeight the height of the destination rectangle
  22317. @param sourceX the left of the rectangle to copy from the source image
  22318. @param sourceY the top of the rectangle to copy from the source image
  22319. @param sourceWidth the width of the rectangle to copy from the source image
  22320. @param sourceHeight the height of the rectangle to copy from the source image
  22321. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  22322. the source image's alpha channel is used as a mask with
  22323. which to fill the destination using the current colour
  22324. or brush. (If the source is has no alpha channel, then
  22325. it will just fill the target with a solid rectangle)
  22326. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  22327. */
  22328. void drawImage (const Image& imageToDraw,
  22329. int destX, int destY, int destWidth, int destHeight,
  22330. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  22331. bool fillAlphaChannelWithCurrentBrush = false) const;
  22332. /** Draws an image, having applied an affine transform to it.
  22333. This lets you throw the image around in some wacky ways, rotate it, shear,
  22334. scale it, etc.
  22335. Images are composited using the context's current opacity, so if you
  22336. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  22337. (or setColour() with an opaque colour) before drawing images.
  22338. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  22339. are ignored and it is filled with the current brush, masked by its alpha channel.
  22340. If you want to render only a subsection of an image, use Image::getClippedImage() to
  22341. create the section that you need.
  22342. @see setImageResamplingQuality, drawImage
  22343. */
  22344. void drawImageTransformed (const Image& imageToDraw,
  22345. const AffineTransform& transform,
  22346. bool fillAlphaChannelWithCurrentBrush = false) const;
  22347. /** Draws an image to fit within a designated rectangle.
  22348. If the image is too big or too small for the space, it will be rescaled
  22349. to fit as nicely as it can do without affecting its aspect ratio. It will
  22350. then be placed within the target rectangle according to the justification flags
  22351. specified.
  22352. @param imageToDraw the source image to draw
  22353. @param destX top-left of the target rectangle to fit it into
  22354. @param destY top-left of the target rectangle to fit it into
  22355. @param destWidth size of the target rectangle to fit the image into
  22356. @param destHeight size of the target rectangle to fit the image into
  22357. @param placementWithinTarget this specifies how the image should be positioned
  22358. within the target rectangle - see the RectanglePlacement
  22359. class for more details about this.
  22360. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  22361. alpha channel will be used as a mask with which to
  22362. draw with the current brush or colour. This is
  22363. similar to fillAlphaMap(), and see also drawImage()
  22364. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  22365. */
  22366. void drawImageWithin (const Image& imageToDraw,
  22367. int destX, int destY, int destWidth, int destHeight,
  22368. const RectanglePlacement& placementWithinTarget,
  22369. bool fillAlphaChannelWithCurrentBrush = false) const;
  22370. /** Returns the position of the bounding box for the current clipping region.
  22371. @see getClipRegion, clipRegionIntersects
  22372. */
  22373. const Rectangle<int> getClipBounds() const;
  22374. /** Checks whether a rectangle overlaps the context's clipping region.
  22375. If this returns false, no part of the given area can be drawn onto, so this
  22376. method can be used to optimise a component's paint() method, by letting it
  22377. avoid drawing complex objects that aren't within the region being repainted.
  22378. */
  22379. bool clipRegionIntersects (const Rectangle<int>& area) const;
  22380. /** Intersects the current clipping region with another region.
  22381. @returns true if the resulting clipping region is non-zero in size
  22382. @see setOrigin, clipRegionIntersects
  22383. */
  22384. bool reduceClipRegion (int x, int y, int width, int height);
  22385. /** Intersects the current clipping region with another region.
  22386. @returns true if the resulting clipping region is non-zero in size
  22387. @see setOrigin, clipRegionIntersects
  22388. */
  22389. bool reduceClipRegion (const Rectangle<int>& area);
  22390. /** Intersects the current clipping region with a rectangle list region.
  22391. @returns true if the resulting clipping region is non-zero in size
  22392. @see setOrigin, clipRegionIntersects
  22393. */
  22394. bool reduceClipRegion (const RectangleList& clipRegion);
  22395. /** Intersects the current clipping region with a path.
  22396. @returns true if the resulting clipping region is non-zero in size
  22397. @see reduceClipRegion
  22398. */
  22399. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  22400. /** Intersects the current clipping region with an image's alpha-channel.
  22401. The current clipping path is intersected with the area covered by this image's
  22402. alpha-channel, after the image has been transformed by the specified matrix.
  22403. @param image the image whose alpha-channel should be used. If the image doesn't
  22404. have an alpha-channel, it is treated as entirely opaque.
  22405. @param transform a matrix to apply to the image
  22406. @returns true if the resulting clipping region is non-zero in size
  22407. @see reduceClipRegion
  22408. */
  22409. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  22410. /** Excludes a rectangle to stop it being drawn into. */
  22411. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  22412. /** Returns true if no drawing can be done because the clip region is zero. */
  22413. bool isClipEmpty() const;
  22414. /** Saves the current graphics state on an internal stack.
  22415. To restore the state, use restoreState().
  22416. @see ScopedSaveState
  22417. */
  22418. void saveState();
  22419. /** Restores a graphics state that was previously saved with saveState().
  22420. @see ScopedSaveState
  22421. */
  22422. void restoreState();
  22423. /** Uses RAII to save and restore the state of a graphics context.
  22424. On construction, this calls Graphics::saveState(), and on destruction it calls
  22425. Graphics::restoreState() on the Graphics object that you supply.
  22426. */
  22427. class ScopedSaveState
  22428. {
  22429. public:
  22430. ScopedSaveState (Graphics& g);
  22431. ~ScopedSaveState();
  22432. private:
  22433. Graphics& context;
  22434. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  22435. };
  22436. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  22437. context with the given opacity.
  22438. The context uses an internal stack of temporary image layers to do this. When you've
  22439. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  22440. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  22441. by a corresponding call to endTransparencyLayer()!
  22442. This call also saves the current state, and endTransparencyLayer() restores it.
  22443. */
  22444. void beginTransparencyLayer (float layerOpacity);
  22445. /** Completes a drawing operation to a temporary semi-transparent buffer.
  22446. See beginTransparencyLayer() for more details.
  22447. */
  22448. void endTransparencyLayer();
  22449. /** Moves the position of the context's origin.
  22450. This changes the position that the context considers to be (0, 0) to
  22451. the specified position.
  22452. So if you call setOrigin (100, 100), then the position that was previously
  22453. referred to as (100, 100) will subsequently be considered to be (0, 0).
  22454. @see reduceClipRegion, addTransform
  22455. */
  22456. void setOrigin (int newOriginX, int newOriginY);
  22457. /** Adds a transformation which will be performed on all the graphics operations that
  22458. the context subsequently performs.
  22459. After calling this, all the coordinates that are passed into the context will be
  22460. transformed by this matrix.
  22461. @see setOrigin
  22462. */
  22463. void addTransform (const AffineTransform& transform);
  22464. /** Resets the current colour, brush, and font to default settings. */
  22465. void resetToDefaultState();
  22466. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  22467. bool isVectorDevice() const;
  22468. /** Create a graphics that uses a given low-level renderer.
  22469. For internal use only.
  22470. NB. The context will NOT be deleted by this object when it is deleted.
  22471. */
  22472. Graphics (LowLevelGraphicsContext* internalContext) throw();
  22473. /** @internal */
  22474. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  22475. private:
  22476. LowLevelGraphicsContext* const context;
  22477. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  22478. bool saveStatePending;
  22479. void saveStateIfPending();
  22480. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  22481. };
  22482. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  22483. /*** End of inlined file: juce_Graphics.h ***/
  22484. /**
  22485. A graphical effect filter that can be applied to components.
  22486. An ImageEffectFilter can be applied to the image that a component
  22487. paints before it hits the screen.
  22488. This is used for adding effects like shadows, blurs, etc.
  22489. @see Component::setComponentEffect
  22490. */
  22491. class JUCE_API ImageEffectFilter
  22492. {
  22493. public:
  22494. /** Overridden to render the effect.
  22495. The implementation of this method must use the image that is passed in
  22496. as its source, and should render its output to the graphics context passed in.
  22497. @param sourceImage the image that the source component has just rendered with
  22498. its paint() method. The image may or may not have an alpha
  22499. channel, depending on whether the component is opaque.
  22500. @param destContext the graphics context to use to draw the resultant image.
  22501. @param alpha the alpha with which to draw the resultant image to the
  22502. target context
  22503. */
  22504. virtual void applyEffect (Image& sourceImage,
  22505. Graphics& destContext,
  22506. float alpha) = 0;
  22507. /** Destructor. */
  22508. virtual ~ImageEffectFilter() {}
  22509. };
  22510. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  22511. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  22512. /*** Start of inlined file: juce_Image.h ***/
  22513. #ifndef __JUCE_IMAGE_JUCEHEADER__
  22514. #define __JUCE_IMAGE_JUCEHEADER__
  22515. /**
  22516. Holds a fixed-size bitmap.
  22517. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  22518. To draw into an image, create a Graphics object for it.
  22519. e.g. @code
  22520. // create a transparent 500x500 image..
  22521. Image myImage (Image::RGB, 500, 500, true);
  22522. Graphics g (myImage);
  22523. g.setColour (Colours::red);
  22524. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  22525. @endcode
  22526. Other useful ways to create an image are with the ImageCache class, or the
  22527. ImageFileFormat, which provides a way to load common image files.
  22528. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  22529. */
  22530. class JUCE_API Image
  22531. {
  22532. public:
  22533. /**
  22534. */
  22535. enum PixelFormat
  22536. {
  22537. UnknownFormat,
  22538. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  22539. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  22540. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  22541. };
  22542. /**
  22543. */
  22544. enum ImageType
  22545. {
  22546. SoftwareImage = 0,
  22547. NativeImage
  22548. };
  22549. /** Creates a null image. */
  22550. Image();
  22551. /** Creates an image with a specified size and format.
  22552. @param format the number of colour channels in the image
  22553. @param imageWidth the desired width of the image, in pixels - this value must be
  22554. greater than zero (otherwise a width of 1 will be used)
  22555. @param imageHeight the desired width of the image, in pixels - this value must be
  22556. greater than zero (otherwise a height of 1 will be used)
  22557. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  22558. or transparent black (if it's ARGB). If false, the image may contain
  22559. junk initially, so you need to make sure you overwrite it thoroughly.
  22560. @param type the type of image - this lets you specify whether you want a purely
  22561. memory-based image, or one that may be managed by the OS if possible.
  22562. */
  22563. Image (PixelFormat format,
  22564. int imageWidth,
  22565. int imageHeight,
  22566. bool clearImage,
  22567. ImageType type = NativeImage);
  22568. /** Creates a shared reference to another image.
  22569. This won't create a duplicate of the image - when Image objects are copied, they simply
  22570. point to the same shared image data. To make sure that an Image object has its own unique,
  22571. unshared internal data, call duplicateIfShared().
  22572. */
  22573. Image (const Image& other);
  22574. /** Makes this image refer to the same underlying image as another object.
  22575. This won't create a duplicate of the image - when Image objects are copied, they simply
  22576. point to the same shared image data. To make sure that an Image object has its own unique,
  22577. unshared internal data, call duplicateIfShared().
  22578. */
  22579. Image& operator= (const Image&);
  22580. /** Destructor. */
  22581. ~Image();
  22582. /** Returns true if the two images are referring to the same internal, shared image. */
  22583. bool operator== (const Image& other) const throw() { return image == other.image; }
  22584. /** Returns true if the two images are not referring to the same internal, shared image. */
  22585. bool operator!= (const Image& other) const throw() { return image != other.image; }
  22586. /** Returns true if this image isn't null.
  22587. If you create an Image with the default constructor, it has no size or content, and is null
  22588. until you reassign it to an Image which contains some actual data.
  22589. The isNull() method is the opposite of isValid().
  22590. @see isNull
  22591. */
  22592. inline bool isValid() const throw() { return image != 0; }
  22593. /** Returns true if this image is not valid.
  22594. If you create an Image with the default constructor, it has no size or content, and is null
  22595. until you reassign it to an Image which contains some actual data.
  22596. The isNull() method is the opposite of isValid().
  22597. @see isValid
  22598. */
  22599. inline bool isNull() const throw() { return image == 0; }
  22600. /** A null Image object that can be used when you need to return an invalid image.
  22601. This object is the equivalient to an Image created with the default constructor.
  22602. */
  22603. static const Image null;
  22604. /** Returns the image's width (in pixels). */
  22605. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  22606. /** Returns the image's height (in pixels). */
  22607. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  22608. /** Returns a rectangle with the same size as this image.
  22609. The rectangle's origin is always (0, 0).
  22610. */
  22611. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  22612. /** Returns the image's pixel format. */
  22613. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  22614. /** True if the image's format is ARGB. */
  22615. bool isARGB() const throw() { return getFormat() == ARGB; }
  22616. /** True if the image's format is RGB. */
  22617. bool isRGB() const throw() { return getFormat() == RGB; }
  22618. /** True if the image's format is a single-channel alpha map. */
  22619. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  22620. /** True if the image contains an alpha-channel. */
  22621. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  22622. /** Clears a section of the image with a given colour.
  22623. This won't do any alpha-blending - it just sets all pixels in the image to
  22624. the given colour (which may be non-opaque if the image has an alpha channel).
  22625. */
  22626. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  22627. /** Returns a rescaled version of this image.
  22628. A new image is returned which is a copy of this one, rescaled to the given size.
  22629. Note that if the new size is identical to the existing image, this will just return
  22630. a reference to the original image, and won't actually create a duplicate.
  22631. */
  22632. const Image rescaled (int newWidth, int newHeight,
  22633. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  22634. /** Returns a version of this image with a different image format.
  22635. A new image is returned which has been converted to the specified format.
  22636. Note that if the new format is no different to the current one, this will just return
  22637. a reference to the original image, and won't actually create a copy.
  22638. */
  22639. const Image convertedToFormat (PixelFormat newFormat) const;
  22640. /** Makes sure that no other Image objects share the same underlying data as this one.
  22641. If no other Image objects refer to the same shared data as this one, this method has no
  22642. effect. But if there are other references to the data, this will create a new copy of
  22643. the data internally.
  22644. Call this if you want to draw onto the image, but want to make sure that this doesn't
  22645. affect any other code that may be sharing the same data.
  22646. @see getReferenceCount
  22647. */
  22648. void duplicateIfShared();
  22649. /** Returns an image which refers to a subsection of this image.
  22650. This will not make a copy of the original - the new image will keep a reference to it, so that
  22651. if the original image is changed, the contents of the subsection will also change. Likewise if you
  22652. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  22653. you use operator= to make the original Image object refer to something else, the subsection image
  22654. won't pick up this change, it'll remain pointing at the original.
  22655. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  22656. image than the area you asked for, or even a null image if the area was out-of-bounds.
  22657. */
  22658. const Image getClippedImage (const Rectangle<int>& area) const;
  22659. /** Returns the colour of one of the pixels in the image.
  22660. If the co-ordinates given are beyond the image's boundaries, this will
  22661. return Colours::transparentBlack.
  22662. @see setPixelAt, Image::BitmapData::getPixelColour
  22663. */
  22664. const Colour getPixelAt (int x, int y) const;
  22665. /** Sets the colour of one of the image's pixels.
  22666. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  22667. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  22668. with the given one. The colour's opacity will be ignored if this image doesn't have
  22669. an alpha-channel.
  22670. @see getPixelAt, Image::BitmapData::setPixelColour
  22671. */
  22672. void setPixelAt (int x, int y, const Colour& colour);
  22673. /** Changes the opacity of a pixel.
  22674. This only has an effect if the image has an alpha channel and if the
  22675. given co-ordinates are inside the image's boundary.
  22676. The multiplier must be in the range 0 to 1.0, and the current alpha
  22677. at the given co-ordinates will be multiplied by this value.
  22678. @see setPixelAt
  22679. */
  22680. void multiplyAlphaAt (int x, int y, float multiplier);
  22681. /** Changes the overall opacity of the image.
  22682. This will multiply the alpha value of each pixel in the image by the given
  22683. amount (limiting the resulting alpha values between 0 and 255). This allows
  22684. you to make an image more or less transparent.
  22685. If the image doesn't have an alpha channel, this won't have any effect.
  22686. */
  22687. void multiplyAllAlphas (float amountToMultiplyBy);
  22688. /** Changes all the colours to be shades of grey, based on their current luminosity.
  22689. */
  22690. void desaturate();
  22691. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  22692. You should only use this class as a last resort - messing about with the internals of
  22693. an image is only recommended for people who really know what they're doing!
  22694. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  22695. hanging around while the image is being used elsewhere.
  22696. Depending on the way the image class is implemented, this may create a temporary buffer
  22697. which is copied back to the image when the object is deleted, or it may just get a pointer
  22698. directly into the image's raw data.
  22699. You can use the stride and data values in this class directly, but don't alter them!
  22700. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  22701. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  22702. */
  22703. class BitmapData
  22704. {
  22705. public:
  22706. enum ReadWriteMode
  22707. {
  22708. readOnly,
  22709. writeOnly,
  22710. readWrite
  22711. };
  22712. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  22713. BitmapData (const Image& image, int x, int y, int w, int h);
  22714. BitmapData (const Image& image, ReadWriteMode mode);
  22715. ~BitmapData();
  22716. /** Returns a pointer to the start of a line in the image.
  22717. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  22718. sure it's not out-of-range.
  22719. */
  22720. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  22721. /** Returns a pointer to a pixel in the image.
  22722. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  22723. not out-of-range.
  22724. */
  22725. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  22726. /** Returns the colour of a given pixel.
  22727. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22728. repsonsibility to make sure they're within the image's size.
  22729. */
  22730. const Colour getPixelColour (int x, int y) const throw();
  22731. /** Sets the colour of a given pixel.
  22732. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22733. repsonsibility to make sure they're within the image's size.
  22734. */
  22735. void setPixelColour (int x, int y, const Colour& colour) const throw();
  22736. uint8* data;
  22737. PixelFormat pixelFormat;
  22738. int lineStride, pixelStride, width, height;
  22739. /** Used internally by custom image types to manage pixel data lifetime. */
  22740. class BitmapDataReleaser
  22741. {
  22742. protected:
  22743. BitmapDataReleaser() {}
  22744. public:
  22745. virtual ~BitmapDataReleaser() {}
  22746. };
  22747. ScopedPointer<BitmapDataReleaser> dataReleaser;
  22748. private:
  22749. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  22750. };
  22751. /** Copies some pixel values to a rectangle of the image.
  22752. The format of the pixel data must match that of the image itself, and the
  22753. rectangle supplied must be within the image's bounds.
  22754. */
  22755. void setPixelData (int destX, int destY, int destW, int destH,
  22756. const uint8* sourcePixelData, int sourceLineStride);
  22757. /** Copies a section of the image to somewhere else within itself. */
  22758. void moveImageSection (int destX, int destY,
  22759. int sourceX, int sourceY,
  22760. int width, int height);
  22761. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  22762. of the image.
  22763. @param result the list that will have the area added to it
  22764. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  22765. above this level will be considered opaque
  22766. */
  22767. void createSolidAreaMask (RectangleList& result,
  22768. float alphaThreshold = 0.5f) const;
  22769. /** Returns a NamedValueSet that is attached to the image and which can be used for
  22770. associating custom values with it.
  22771. If this is a null image, this will return a null pointer.
  22772. */
  22773. NamedValueSet* getProperties() const;
  22774. /** Creates a context suitable for drawing onto this image.
  22775. Don't call this method directly! It's used internally by the Graphics class.
  22776. */
  22777. LowLevelGraphicsContext* createLowLevelContext() const;
  22778. /** Returns the number of Image objects which are currently referring to the same internal
  22779. shared image data.
  22780. @see duplicateIfShared
  22781. */
  22782. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  22783. /** This is a base class for task-specific types of image.
  22784. Don't use this class directly! It's used internally by the Image class.
  22785. */
  22786. class SharedImage : public ReferenceCountedObject
  22787. {
  22788. public:
  22789. SharedImage (PixelFormat format, int width, int height);
  22790. ~SharedImage();
  22791. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  22792. virtual SharedImage* clone() = 0;
  22793. virtual ImageType getType() const = 0;
  22794. virtual void initialiseBitmapData (BitmapData& bitmapData, int x, int y, BitmapData::ReadWriteMode mode) = 0;
  22795. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  22796. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  22797. const PixelFormat getPixelFormat() const throw() { return format; }
  22798. int getWidth() const throw() { return width; }
  22799. int getHeight() const throw() { return height; }
  22800. protected:
  22801. friend class Image;
  22802. friend class BitmapData;
  22803. const PixelFormat format;
  22804. const int width, height;
  22805. NamedValueSet userData;
  22806. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  22807. };
  22808. /** @internal */
  22809. SharedImage* getSharedImage() const throw() { return image; }
  22810. /** @internal */
  22811. explicit Image (SharedImage* instance);
  22812. private:
  22813. friend class SharedImage;
  22814. friend class BitmapData;
  22815. ReferenceCountedObjectPtr<SharedImage> image;
  22816. JUCE_LEAK_DETECTOR (Image);
  22817. };
  22818. #endif // __JUCE_IMAGE_JUCEHEADER__
  22819. /*** End of inlined file: juce_Image.h ***/
  22820. /*** Start of inlined file: juce_RectangleList.h ***/
  22821. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  22822. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  22823. /**
  22824. Maintains a set of rectangles as a complex region.
  22825. This class allows a set of rectangles to be treated as a solid shape, and can
  22826. add and remove rectangular sections of it, and simplify overlapping or
  22827. adjacent rectangles.
  22828. @see Rectangle
  22829. */
  22830. class JUCE_API RectangleList
  22831. {
  22832. public:
  22833. /** Creates an empty RectangleList */
  22834. RectangleList() throw();
  22835. /** Creates a copy of another list */
  22836. RectangleList (const RectangleList& other);
  22837. /** Creates a list containing just one rectangle. */
  22838. RectangleList (const Rectangle<int>& rect);
  22839. /** Copies this list from another one. */
  22840. RectangleList& operator= (const RectangleList& other);
  22841. /** Destructor. */
  22842. ~RectangleList();
  22843. /** Returns true if the region is empty. */
  22844. bool isEmpty() const throw();
  22845. /** Returns the number of rectangles in the list. */
  22846. int getNumRectangles() const throw() { return rects.size(); }
  22847. /** Returns one of the rectangles at a particular index.
  22848. @returns the rectangle at the index, or an empty rectangle if the
  22849. index is out-of-range.
  22850. */
  22851. const Rectangle<int> getRectangle (int index) const throw();
  22852. /** Removes all rectangles to leave an empty region. */
  22853. void clear();
  22854. /** Merges a new rectangle into the list.
  22855. The rectangle being added will first be clipped to remove any parts of it
  22856. that overlap existing rectangles in the list.
  22857. */
  22858. void add (int x, int y, int width, int height);
  22859. /** Merges a new rectangle into the list.
  22860. The rectangle being added will first be clipped to remove any parts of it
  22861. that overlap existing rectangles in the list, and adjacent rectangles will be
  22862. merged into it.
  22863. */
  22864. void add (const Rectangle<int>& rect);
  22865. /** Dumbly adds a rectangle to the list without checking for overlaps.
  22866. This simply adds the rectangle to the end, it doesn't merge it or remove
  22867. any overlapping bits.
  22868. */
  22869. void addWithoutMerging (const Rectangle<int>& rect);
  22870. /** Merges another rectangle list into this one.
  22871. Any overlaps between the two lists will be clipped, so that the result is
  22872. the union of both lists.
  22873. */
  22874. void add (const RectangleList& other);
  22875. /** Removes a rectangular region from the list.
  22876. Any rectangles in the list which overlap this will be clipped and subdivided
  22877. if necessary.
  22878. */
  22879. void subtract (const Rectangle<int>& rect);
  22880. /** Removes all areas in another RectangleList from this one.
  22881. Any rectangles in the list which overlap this will be clipped and subdivided
  22882. if necessary.
  22883. @returns true if the resulting list is non-empty.
  22884. */
  22885. bool subtract (const RectangleList& otherList);
  22886. /** Removes any areas of the region that lie outside a given rectangle.
  22887. Any rectangles in the list which overlap this will be clipped and subdivided
  22888. if necessary.
  22889. Returns true if the resulting region is not empty, false if it is empty.
  22890. @see getIntersectionWith
  22891. */
  22892. bool clipTo (const Rectangle<int>& rect);
  22893. /** Removes any areas of the region that lie outside a given rectangle list.
  22894. Any rectangles in this object which overlap the specified list will be clipped
  22895. and subdivided if necessary.
  22896. Returns true if the resulting region is not empty, false if it is empty.
  22897. @see getIntersectionWith
  22898. */
  22899. bool clipTo (const RectangleList& other);
  22900. /** Creates a region which is the result of clipping this one to a given rectangle.
  22901. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  22902. resulting region into the list whose reference is passed-in.
  22903. Returns true if the resulting region is not empty, false if it is empty.
  22904. @see clipTo
  22905. */
  22906. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  22907. /** Swaps the contents of this and another list.
  22908. This swaps their internal pointers, so is hugely faster than using copy-by-value
  22909. to swap them.
  22910. */
  22911. void swapWith (RectangleList& otherList) throw();
  22912. /** Checks whether the region contains a given point.
  22913. @returns true if the point lies within one of the rectangles in the list
  22914. */
  22915. bool containsPoint (int x, int y) const throw();
  22916. /** Checks whether the region contains the whole of a given rectangle.
  22917. @returns true all parts of the rectangle passed in lie within the region
  22918. defined by this object
  22919. @see intersectsRectangle, containsPoint
  22920. */
  22921. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  22922. /** Checks whether the region contains any part of a given rectangle.
  22923. @returns true if any part of the rectangle passed in lies within the region
  22924. defined by this object
  22925. @see containsRectangle
  22926. */
  22927. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  22928. /** Checks whether this region intersects any part of another one.
  22929. @see intersectsRectangle
  22930. */
  22931. bool intersects (const RectangleList& other) const throw();
  22932. /** Returns the smallest rectangle that can enclose the whole of this region. */
  22933. const Rectangle<int> getBounds() const throw();
  22934. /** Optimises the list into a minimum number of constituent rectangles.
  22935. This will try to combine any adjacent rectangles into larger ones where
  22936. possible, to simplify lists that might have been fragmented by repeated
  22937. add/subtract calls.
  22938. */
  22939. void consolidate();
  22940. /** Adds an x and y value to all the co-ordinates. */
  22941. void offsetAll (int dx, int dy) throw();
  22942. /** Creates a Path object to represent this region. */
  22943. const Path toPath() const;
  22944. /** An iterator for accessing all the rectangles in a RectangleList. */
  22945. class JUCE_API Iterator
  22946. {
  22947. public:
  22948. Iterator (const RectangleList& list) throw();
  22949. ~Iterator();
  22950. /** Advances to the next rectangle, and returns true if it's not finished.
  22951. Call this before using getRectangle() to find the rectangle that was returned.
  22952. */
  22953. bool next() throw();
  22954. /** Returns the current rectangle. */
  22955. const Rectangle<int>* getRectangle() const throw() { return current; }
  22956. private:
  22957. const Rectangle<int>* current;
  22958. const RectangleList& owner;
  22959. int index;
  22960. JUCE_DECLARE_NON_COPYABLE (Iterator);
  22961. };
  22962. private:
  22963. friend class Iterator;
  22964. Array <Rectangle<int> > rects;
  22965. JUCE_LEAK_DETECTOR (RectangleList);
  22966. };
  22967. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  22968. /*** End of inlined file: juce_RectangleList.h ***/
  22969. /*** Start of inlined file: juce_BorderSize.h ***/
  22970. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  22971. #define __JUCE_BORDERSIZE_JUCEHEADER__
  22972. /**
  22973. Specifies a set of gaps to be left around the sides of a rectangle.
  22974. This is basically the size of the spaces at the top, bottom, left and right of
  22975. a rectangle. It's used by various component classes to specify borders.
  22976. @see Rectangle
  22977. */
  22978. template <typename ValueType>
  22979. class BorderSize
  22980. {
  22981. public:
  22982. /** Creates a null border.
  22983. All sizes are left as 0.
  22984. */
  22985. BorderSize() throw()
  22986. : top(), left(), bottom(), right()
  22987. {
  22988. }
  22989. /** Creates a copy of another border. */
  22990. BorderSize (const BorderSize& other) throw()
  22991. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  22992. {
  22993. }
  22994. /** Creates a border with the given gaps. */
  22995. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) throw()
  22996. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  22997. {
  22998. }
  22999. /** Creates a border with the given gap on all sides. */
  23000. explicit BorderSize (ValueType allGaps) throw()
  23001. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  23002. {
  23003. }
  23004. /** Returns the gap that should be left at the top of the region. */
  23005. ValueType getTop() const throw() { return top; }
  23006. /** Returns the gap that should be left at the top of the region. */
  23007. ValueType getLeft() const throw() { return left; }
  23008. /** Returns the gap that should be left at the top of the region. */
  23009. ValueType getBottom() const throw() { return bottom; }
  23010. /** Returns the gap that should be left at the top of the region. */
  23011. ValueType getRight() const throw() { return right; }
  23012. /** Returns the sum of the top and bottom gaps. */
  23013. ValueType getTopAndBottom() const throw() { return top + bottom; }
  23014. /** Returns the sum of the left and right gaps. */
  23015. ValueType getLeftAndRight() const throw() { return left + right; }
  23016. /** Returns true if this border has no thickness along any edge. */
  23017. bool isEmpty() const throw() { return left + right + top + bottom == ValueType(); }
  23018. /** Changes the top gap. */
  23019. void setTop (ValueType newTopGap) throw() { top = newTopGap; }
  23020. /** Changes the left gap. */
  23021. void setLeft (ValueType newLeftGap) throw() { left = newLeftGap; }
  23022. /** Changes the bottom gap. */
  23023. void setBottom (ValueType newBottomGap) throw() { bottom = newBottomGap; }
  23024. /** Changes the right gap. */
  23025. void setRight (ValueType newRightGap) throw() { right = newRightGap; }
  23026. /** Returns a rectangle with these borders removed from it. */
  23027. const Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const throw()
  23028. {
  23029. return Rectangle<ValueType> (original.getX() + left,
  23030. original.getY() + top,
  23031. original.getWidth() - (left + right),
  23032. original.getHeight() - (top + bottom));
  23033. }
  23034. /** Removes this border from a given rectangle. */
  23035. void subtractFrom (Rectangle<ValueType>& rectangle) const throw()
  23036. {
  23037. rectangle = subtractedFrom (rectangle);
  23038. }
  23039. /** Returns a rectangle with these borders added around it. */
  23040. const Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const throw()
  23041. {
  23042. return Rectangle<ValueType> (original.getX() - left,
  23043. original.getY() - top,
  23044. original.getWidth() + (left + right),
  23045. original.getHeight() + (top + bottom));
  23046. }
  23047. /** Adds this border around a given rectangle. */
  23048. void addTo (Rectangle<ValueType>& rectangle) const throw()
  23049. {
  23050. rectangle = addedTo (rectangle);
  23051. }
  23052. bool operator== (const BorderSize& other) const throw()
  23053. {
  23054. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  23055. }
  23056. bool operator!= (const BorderSize& other) const throw()
  23057. {
  23058. return ! operator== (other);
  23059. }
  23060. private:
  23061. ValueType top, left, bottom, right;
  23062. JUCE_LEAK_DETECTOR (BorderSize);
  23063. };
  23064. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  23065. /*** End of inlined file: juce_BorderSize.h ***/
  23066. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  23067. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23068. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23069. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  23070. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23071. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23072. /**
  23073. Classes derived from this will be automatically deleted when the application exits.
  23074. After JUCEApplication::shutdown() has been called, any objects derived from
  23075. DeletedAtShutdown which are still in existence will be deleted in the reverse
  23076. order to that in which they were created.
  23077. So if you've got a singleton and don't want to have to explicitly delete it, just
  23078. inherit from this and it'll be taken care of.
  23079. */
  23080. class JUCE_API DeletedAtShutdown
  23081. {
  23082. protected:
  23083. /** Creates a DeletedAtShutdown object. */
  23084. DeletedAtShutdown();
  23085. /** Destructor.
  23086. It's ok to delete these objects explicitly - it's only the ones left
  23087. dangling at the end that will be deleted automatically.
  23088. */
  23089. virtual ~DeletedAtShutdown();
  23090. public:
  23091. /** Deletes all extant objects.
  23092. This shouldn't be used by applications, as it's called automatically
  23093. in the shutdown code of the JUCEApplication class.
  23094. */
  23095. static void deleteAll();
  23096. private:
  23097. static Array <DeletedAtShutdown*>& getObjects();
  23098. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  23099. };
  23100. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  23101. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  23102. /**
  23103. Manages the system's stack of modal components.
  23104. Normally you'll just use the Component methods to invoke modal states in components,
  23105. and won't have to deal with this class directly, but this is the singleton object that's
  23106. used internally to manage the stack.
  23107. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  23108. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  23109. */
  23110. class JUCE_API ModalComponentManager : public AsyncUpdater,
  23111. public DeletedAtShutdown
  23112. {
  23113. public:
  23114. /** Receives callbacks when a modal component is dismissed.
  23115. You can register a callback using Component::enterModalState() or
  23116. ModalComponentManager::attachCallback().
  23117. For some quick ways of creating callback objects, see the ModalCallbackFunction class.
  23118. @see ModalCallbackFunction
  23119. */
  23120. class Callback
  23121. {
  23122. public:
  23123. /** */
  23124. Callback() {}
  23125. /** Destructor. */
  23126. virtual ~Callback() {}
  23127. /** Called to indicate that a modal component has been dismissed.
  23128. You can register a callback using Component::enterModalState() or
  23129. ModalComponentManager::attachCallback().
  23130. The returnValue parameter is the value that was passed to Component::exitModalState()
  23131. when the component was dismissed.
  23132. The callback object will be deleted shortly after this method is called.
  23133. */
  23134. virtual void modalStateFinished (int returnValue) = 0;
  23135. };
  23136. /** Returns the number of components currently being shown modally.
  23137. @see getModalComponent
  23138. */
  23139. int getNumModalComponents() const;
  23140. /** Returns one of the components being shown modally.
  23141. An index of 0 is the most recently-shown, topmost component.
  23142. */
  23143. Component* getModalComponent (int index) const;
  23144. /** Returns true if the specified component is in a modal state. */
  23145. bool isModal (Component* component) const;
  23146. /** Returns true if the specified component is currently the topmost modal component. */
  23147. bool isFrontModalComponent (Component* component) const;
  23148. /** Adds a new callback that will be called when the specified modal component is dismissed.
  23149. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  23150. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  23151. called.
  23152. Each component can have any number of callbacks associated with it, and this one is added
  23153. to that list.
  23154. The object that is passed in will be deleted by the manager when it's no longer needed. If
  23155. the given component is not currently modal, the callback object is deleted immediately and
  23156. no action is taken.
  23157. */
  23158. void attachCallback (Component* component, Callback* callback);
  23159. /** Brings any modal components to the front. */
  23160. void bringModalComponentsToFront (bool topOneShouldGrabFocus = true);
  23161. #if JUCE_MODAL_LOOPS_PERMITTED
  23162. /** Runs the event loop until the currently topmost modal component is dismissed, and
  23163. returns the exit code for that component.
  23164. */
  23165. int runEventLoopForCurrentComponent();
  23166. #endif
  23167. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  23168. protected:
  23169. /** Creates a ModalComponentManager.
  23170. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  23171. */
  23172. ModalComponentManager();
  23173. /** Destructor. */
  23174. ~ModalComponentManager();
  23175. /** @internal */
  23176. void handleAsyncUpdate();
  23177. private:
  23178. class ModalItem;
  23179. class ReturnValueRetriever;
  23180. friend class Component;
  23181. friend class OwnedArray <ModalItem>;
  23182. OwnedArray <ModalItem> stack;
  23183. void startModal (Component* component);
  23184. void endModal (Component* component, int returnValue);
  23185. void endModal (Component* component);
  23186. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  23187. };
  23188. /**
  23189. This class provides some handy utility methods for creating ModalComponentManager::Callback
  23190. objects that will invoke a static function with some parameters when a modal component is dismissed.
  23191. */
  23192. class ModalCallbackFunction
  23193. {
  23194. public:
  23195. /** This is a utility function to create a ModalComponentManager::Callback that will
  23196. call a static function with a parameter.
  23197. The function that you supply must take two parameters - the first being an int, which is
  23198. the result code that was used when the modal component was dismissed, and the second
  23199. can be a custom type. Note that this custom value will be copied and stored, so it must
  23200. be a primitive type or a class that provides copy-by-value semantics.
  23201. E.g. @code
  23202. static void myCallbackFunction (int modalResult, double customValue)
  23203. {
  23204. if (modalResult == 1)
  23205. doSomethingWith (customValue);
  23206. }
  23207. Component* someKindOfComp;
  23208. ...
  23209. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0));
  23210. @endcode
  23211. @see ModalComponentManager::Callback
  23212. */
  23213. template <typename ParamType>
  23214. static ModalComponentManager::Callback* create (void (*functionToCall) (int, ParamType),
  23215. ParamType parameterValue)
  23216. {
  23217. return new FunctionCaller1 <ParamType> (functionToCall, parameterValue);
  23218. }
  23219. /** This is a utility function to create a ModalComponentManager::Callback that will
  23220. call a static function with two custom parameters.
  23221. The function that you supply must take three parameters - the first being an int, which is
  23222. the result code that was used when the modal component was dismissed, and the next two are
  23223. your custom types. Note that these custom values will be copied and stored, so they must
  23224. be primitive types or classes that provide copy-by-value semantics.
  23225. E.g. @code
  23226. static void myCallbackFunction (int modalResult, double customValue1, String customValue2)
  23227. {
  23228. if (modalResult == 1)
  23229. doSomethingWith (customValue1, customValue2);
  23230. }
  23231. Component* someKindOfComp;
  23232. ...
  23233. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0, String ("xyz")));
  23234. @endcode
  23235. @see ModalComponentManager::Callback
  23236. */
  23237. template <typename ParamType1, typename ParamType2>
  23238. static ModalComponentManager::Callback* withParam (void (*functionToCall) (int, ParamType1, ParamType2),
  23239. ParamType1 parameterValue1,
  23240. ParamType2 parameterValue2)
  23241. {
  23242. return new FunctionCaller2 <ParamType1, ParamType2> (functionToCall, parameterValue1, parameterValue2);
  23243. }
  23244. /** This is a utility function to create a ModalComponentManager::Callback that will
  23245. call a static function with a component.
  23246. The function that you supply must take two parameters - the first being an int, which is
  23247. the result code that was used when the modal component was dismissed, and the second
  23248. can be a Component class. The component will be stored as a WeakReference, so that if it gets
  23249. deleted before this callback is invoked, the pointer that is passed to the function will be null.
  23250. E.g. @code
  23251. static void myCallbackFunction (int modalResult, Slider* mySlider)
  23252. {
  23253. if (modalResult == 1 && mySlider != 0) // (must check that mySlider isn't null in case it was deleted..)
  23254. mySlider->setValue (0.0);
  23255. }
  23256. Component* someKindOfComp;
  23257. Slider* mySlider;
  23258. ...
  23259. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider));
  23260. @endcode
  23261. @see ModalComponentManager::Callback
  23262. */
  23263. template <class ComponentType>
  23264. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*),
  23265. ComponentType* component)
  23266. {
  23267. return new ComponentCaller1 <ComponentType> (functionToCall, component);
  23268. }
  23269. /** Creates a ModalComponentManager::Callback that will call a static function with a component.
  23270. The function that you supply must take three parameters - the first being an int, which is
  23271. the result code that was used when the modal component was dismissed, the second being a Component
  23272. class, and the third being a custom type (which must be a primitive type or have copy-by-value semantics).
  23273. The component will be stored as a WeakReference, so that if it gets deleted before this callback is
  23274. invoked, the pointer that is passed into the function will be null.
  23275. E.g. @code
  23276. static void myCallbackFunction (int modalResult, Slider* mySlider, String customParam)
  23277. {
  23278. if (modalResult == 1 && mySlider != 0) // (must check that mySlider isn't null in case it was deleted..)
  23279. mySlider->setName (customParam);
  23280. }
  23281. Component* someKindOfComp;
  23282. Slider* mySlider;
  23283. ...
  23284. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider, String ("hello")));
  23285. @endcode
  23286. @see ModalComponentManager::Callback
  23287. */
  23288. template <class ComponentType, typename ParamType>
  23289. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*, ParamType),
  23290. ComponentType* component,
  23291. ParamType param)
  23292. {
  23293. return new ComponentCaller2 <ComponentType, ParamType> (functionToCall, component, param);
  23294. }
  23295. private:
  23296. template <typename ParamType>
  23297. class FunctionCaller1 : public ModalComponentManager::Callback
  23298. {
  23299. public:
  23300. typedef void (*FunctionType) (int, ParamType);
  23301. FunctionCaller1 (FunctionType& function_, ParamType& param_)
  23302. : function (function_), param (param_) {}
  23303. void modalStateFinished (int returnValue) { function (returnValue, param); }
  23304. private:
  23305. const FunctionType function;
  23306. ParamType param;
  23307. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller1);
  23308. };
  23309. template <typename ParamType1, typename ParamType2>
  23310. class FunctionCaller2 : public ModalComponentManager::Callback
  23311. {
  23312. public:
  23313. typedef void (*FunctionType) (int, ParamType1, ParamType2);
  23314. FunctionCaller2 (FunctionType& function_, ParamType1& param1_, ParamType2& param2_)
  23315. : function (function_), param1 (param1_), param2 (param2_) {}
  23316. void modalStateFinished (int returnValue) { function (returnValue, param1, param2); }
  23317. private:
  23318. const FunctionType function;
  23319. ParamType1 param1;
  23320. ParamType2 param2;
  23321. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller2);
  23322. };
  23323. template <typename ComponentType>
  23324. class ComponentCaller1 : public ModalComponentManager::Callback
  23325. {
  23326. public:
  23327. typedef void (*FunctionType) (int, ComponentType*);
  23328. ComponentCaller1 (FunctionType& function_, ComponentType* comp_)
  23329. : function (function_), comp (comp_) {}
  23330. void modalStateFinished (int returnValue)
  23331. {
  23332. function (returnValue, static_cast <ComponentType*> (comp.get()));
  23333. }
  23334. private:
  23335. const FunctionType function;
  23336. WeakReference<Component> comp;
  23337. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller1);
  23338. };
  23339. template <typename ComponentType, typename ParamType1>
  23340. class ComponentCaller2 : public ModalComponentManager::Callback
  23341. {
  23342. public:
  23343. typedef void (*FunctionType) (int, ComponentType*, ParamType1);
  23344. ComponentCaller2 (FunctionType& function_, ComponentType* comp_, ParamType1 param1_)
  23345. : function (function_), comp (comp_), param1 (param1_) {}
  23346. void modalStateFinished (int returnValue)
  23347. {
  23348. function (returnValue, static_cast <ComponentType*> (comp.get()), param1);
  23349. }
  23350. private:
  23351. const FunctionType function;
  23352. WeakReference<Component> comp;
  23353. ParamType1 param1;
  23354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller2);
  23355. };
  23356. ModalCallbackFunction();
  23357. ~ModalCallbackFunction();
  23358. JUCE_DECLARE_NON_COPYABLE (ModalCallbackFunction);
  23359. };
  23360. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  23361. /*** End of inlined file: juce_ModalComponentManager.h ***/
  23362. class LookAndFeel;
  23363. class MouseInputSource;
  23364. class MouseInputSourceInternal;
  23365. class ComponentPeer;
  23366. class MarkerList;
  23367. class RelativeRectangle;
  23368. /**
  23369. The base class for all JUCE user-interface objects.
  23370. */
  23371. class JUCE_API Component : public MouseListener
  23372. {
  23373. public:
  23374. /** Creates a component.
  23375. To get it to actually appear, you'll also need to:
  23376. - Either add it to a parent component or use the addToDesktop() method to
  23377. make it a desktop window
  23378. - Set its size and position to something sensible
  23379. - Use setVisible() to make it visible
  23380. And for it to serve any useful purpose, you'll need to write a
  23381. subclass of Component or use one of the other types of component from
  23382. the library.
  23383. */
  23384. Component();
  23385. /** Destructor.
  23386. Note that when a component is deleted, any child components it contains are NOT
  23387. automatically deleted. It's your responsibilty to manage their lifespan - you
  23388. may want to use helper methods like deleteAllChildren(), or less haphazard
  23389. approaches like using ScopedPointers or normal object aggregation to manage them.
  23390. If the component being deleted is currently the child of another one, then during
  23391. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  23392. callback. Any ComponentListener objects that have registered with it will also have their
  23393. ComponentListener::componentBeingDeleted() methods called.
  23394. */
  23395. virtual ~Component();
  23396. /** Creates a component, setting its name at the same time.
  23397. @see getName, setName
  23398. */
  23399. explicit Component (const String& componentName);
  23400. /** Returns the name of this component.
  23401. @see setName
  23402. */
  23403. const String& getName() const throw() { return componentName; }
  23404. /** Sets the name of this component.
  23405. When the name changes, all registered ComponentListeners will receive a
  23406. ComponentListener::componentNameChanged() callback.
  23407. @see getName
  23408. */
  23409. virtual void setName (const String& newName);
  23410. /** Returns the ID string that was set by setComponentID().
  23411. @see setComponentID
  23412. */
  23413. const String& getComponentID() const throw() { return componentID; }
  23414. /** Sets the component's ID string.
  23415. You can retrieve the ID using getComponentID().
  23416. @see getComponentID
  23417. */
  23418. void setComponentID (const String& newID);
  23419. /** Makes the component visible or invisible.
  23420. This method will show or hide the component.
  23421. Note that components default to being non-visible when first created.
  23422. Also note that visible components won't be seen unless all their parent components
  23423. are also visible.
  23424. This method will call visibilityChanged() and also componentVisibilityChanged()
  23425. for any component listeners that are interested in this component.
  23426. @param shouldBeVisible whether to show or hide the component
  23427. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  23428. */
  23429. virtual void setVisible (bool shouldBeVisible);
  23430. /** Tests whether the component is visible or not.
  23431. this doesn't necessarily tell you whether this comp is actually on the screen
  23432. because this depends on whether all the parent components are also visible - use
  23433. isShowing() to find this out.
  23434. @see isShowing, setVisible
  23435. */
  23436. bool isVisible() const throw() { return flags.visibleFlag; }
  23437. /** Called when this component's visiblility changes.
  23438. @see setVisible, isVisible
  23439. */
  23440. virtual void visibilityChanged();
  23441. /** Tests whether this component and all its parents are visible.
  23442. @returns true only if this component and all its parents are visible.
  23443. @see isVisible
  23444. */
  23445. bool isShowing() const;
  23446. /** Makes this component appear as a window on the desktop.
  23447. Note that before calling this, you should make sure that the component's opacity is
  23448. set correctly using setOpaque(). If the component is non-opaque, the windowing
  23449. system will try to create a special transparent window for it, which will generally take
  23450. a lot more CPU to operate (and might not even be possible on some platforms).
  23451. If the component is inside a parent component at the time this method is called, it
  23452. will be first be removed from that parent. Likewise if a component on the desktop
  23453. is subsequently added to another component, it'll be removed from the desktop.
  23454. @param windowStyleFlags a combination of the flags specified in the
  23455. ComponentPeer::StyleFlags enum, which define the
  23456. window's characteristics.
  23457. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  23458. in which the juce component should place itself. On Windows,
  23459. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  23460. supported on all platforms, and best left as 0 unless you know
  23461. what you're doing
  23462. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  23463. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  23464. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  23465. */
  23466. virtual void addToDesktop (int windowStyleFlags,
  23467. void* nativeWindowToAttachTo = 0);
  23468. /** If the component is currently showing on the desktop, this will hide it.
  23469. You can also use setVisible() to hide a desktop window temporarily, but
  23470. removeFromDesktop() will free any system resources that are being used up.
  23471. @see addToDesktop, isOnDesktop
  23472. */
  23473. void removeFromDesktop();
  23474. /** Returns true if this component is currently showing on the desktop.
  23475. @see addToDesktop, removeFromDesktop
  23476. */
  23477. bool isOnDesktop() const throw();
  23478. /** Returns the heavyweight window that contains this component.
  23479. If this component is itself on the desktop, this will return the window
  23480. object that it is using. Otherwise, it will return the window of
  23481. its top-level parent component.
  23482. This may return 0 if there isn't a desktop component.
  23483. @see addToDesktop, isOnDesktop
  23484. */
  23485. ComponentPeer* getPeer() const;
  23486. /** For components on the desktop, this is called if the system wants to close the window.
  23487. This is a signal that either the user or the system wants the window to close. The
  23488. default implementation of this method will trigger an assertion to warn you that your
  23489. component should do something about it, but you can override this to ignore the event
  23490. if you want.
  23491. */
  23492. virtual void userTriedToCloseWindow();
  23493. /** Called for a desktop component which has just been minimised or un-minimised.
  23494. This will only be called for components on the desktop.
  23495. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  23496. */
  23497. virtual void minimisationStateChanged (bool isNowMinimised);
  23498. /** Brings the component to the front of its siblings.
  23499. If some of the component's siblings have had their 'always-on-top' flag set,
  23500. then they will still be kept in front of this one (unless of course this
  23501. one is also 'always-on-top').
  23502. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  23503. to the component (see grabKeyboardFocus() for more details)
  23504. @see toBack, toBehind, setAlwaysOnTop
  23505. */
  23506. void toFront (bool shouldAlsoGainFocus);
  23507. /** Changes this component's z-order to be at the back of all its siblings.
  23508. If the component is set to be 'always-on-top', it will only be moved to the
  23509. back of the other other 'always-on-top' components.
  23510. @see toFront, toBehind, setAlwaysOnTop
  23511. */
  23512. void toBack();
  23513. /** Changes this component's z-order so that it's just behind another component.
  23514. @see toFront, toBack
  23515. */
  23516. void toBehind (Component* other);
  23517. /** Sets whether the component should always be kept at the front of its siblings.
  23518. @see isAlwaysOnTop
  23519. */
  23520. void setAlwaysOnTop (bool shouldStayOnTop);
  23521. /** Returns true if this component is set to always stay in front of its siblings.
  23522. @see setAlwaysOnTop
  23523. */
  23524. bool isAlwaysOnTop() const throw();
  23525. /** Returns the x coordinate of the component's left edge.
  23526. This is a distance in pixels from the left edge of the component's parent.
  23527. Note that if you've used setTransform() to apply a transform, then the component's
  23528. bounds will no longer be a direct reflection of the position at which it appears within
  23529. its parent, as the transform will be applied to its bounding box.
  23530. */
  23531. inline int getX() const throw() { return bounds.getX(); }
  23532. /** Returns the y coordinate of the top of this component.
  23533. This is a distance in pixels from the top edge of the component's parent.
  23534. Note that if you've used setTransform() to apply a transform, then the component's
  23535. bounds will no longer be a direct reflection of the position at which it appears within
  23536. its parent, as the transform will be applied to its bounding box.
  23537. */
  23538. inline int getY() const throw() { return bounds.getY(); }
  23539. /** Returns the component's width in pixels. */
  23540. inline int getWidth() const throw() { return bounds.getWidth(); }
  23541. /** Returns the component's height in pixels. */
  23542. inline int getHeight() const throw() { return bounds.getHeight(); }
  23543. /** Returns the x coordinate of the component's right-hand edge.
  23544. This is a distance in pixels from the left edge of the component's parent.
  23545. Note that if you've used setTransform() to apply a transform, then the component's
  23546. bounds will no longer be a direct reflection of the position at which it appears within
  23547. its parent, as the transform will be applied to its bounding box.
  23548. */
  23549. int getRight() const throw() { return bounds.getRight(); }
  23550. /** Returns the component's top-left position as a Point. */
  23551. const Point<int> getPosition() const throw() { return bounds.getPosition(); }
  23552. /** Returns the y coordinate of the bottom edge of this component.
  23553. This is a distance in pixels from the top edge of the component's parent.
  23554. Note that if you've used setTransform() to apply a transform, then the component's
  23555. bounds will no longer be a direct reflection of the position at which it appears within
  23556. its parent, as the transform will be applied to its bounding box.
  23557. */
  23558. int getBottom() const throw() { return bounds.getBottom(); }
  23559. /** Returns this component's bounding box.
  23560. The rectangle returned is relative to the top-left of the component's parent.
  23561. Note that if you've used setTransform() to apply a transform, then the component's
  23562. bounds will no longer be a direct reflection of the position at which it appears within
  23563. its parent, as the transform will be applied to its bounding box.
  23564. */
  23565. const Rectangle<int>& getBounds() const throw() { return bounds; }
  23566. /** Returns the component's bounds, relative to its own origin.
  23567. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  23568. return a rectangle with position (0, 0), and the same size as this component.
  23569. */
  23570. const Rectangle<int> getLocalBounds() const throw();
  23571. /** Returns the area of this component's parent which this component covers.
  23572. The returned area is relative to the parent's coordinate space.
  23573. If the component has an affine transform specified, then the resulting area will be
  23574. the smallest rectangle that fully covers the component's transformed bounding box.
  23575. If this component has no parent, the return value will simply be the same as getBounds().
  23576. */
  23577. const Rectangle<int> getBoundsInParent() const throw();
  23578. /** Returns the region of this component that's not obscured by other, opaque components.
  23579. The RectangleList that is returned represents the area of this component
  23580. which isn't covered by opaque child components.
  23581. If includeSiblings is true, it will also take into account any siblings
  23582. that may be overlapping the component.
  23583. */
  23584. void getVisibleArea (RectangleList& result,
  23585. bool includeSiblings) const;
  23586. /** Returns this component's x coordinate relative the the screen's top-left origin.
  23587. @see getX, localPointToGlobal
  23588. */
  23589. int getScreenX() const;
  23590. /** Returns this component's y coordinate relative the the screen's top-left origin.
  23591. @see getY, localPointToGlobal
  23592. */
  23593. int getScreenY() const;
  23594. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  23595. @see getScreenBounds
  23596. */
  23597. const Point<int> getScreenPosition() const;
  23598. /** Returns the bounds of this component, relative to the screen's top-left.
  23599. @see getScreenPosition
  23600. */
  23601. const Rectangle<int> getScreenBounds() const;
  23602. /** Converts a point to be relative to this component's coordinate space.
  23603. This takes a point relative to a different component, and returns its position relative to this
  23604. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  23605. screen coordinate.
  23606. */
  23607. const Point<int> getLocalPoint (const Component* sourceComponent,
  23608. const Point<int>& pointRelativeToSourceComponent) const;
  23609. /** Converts a rectangle to be relative to this component's coordinate space.
  23610. This takes a rectangle that is relative to a different component, and returns its position relative
  23611. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  23612. a screen coordinate.
  23613. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23614. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23615. the smallest rectangle that fully contains the transformed area.
  23616. */
  23617. const Rectangle<int> getLocalArea (const Component* sourceComponent,
  23618. const Rectangle<int>& areaRelativeToSourceComponent) const;
  23619. /** Converts a point relative to this component's top-left into a screen coordinate.
  23620. @see getLocalPoint, localAreaToGlobal
  23621. */
  23622. const Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  23623. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  23624. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23625. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23626. the smallest rectangle that fully contains the transformed area.
  23627. @see getLocalPoint, localPointToGlobal
  23628. */
  23629. const Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  23630. /** Moves the component to a new position.
  23631. Changes the component's top-left position (without changing its size).
  23632. The position is relative to the top-left of the component's parent.
  23633. If the component actually moves, this method will make a synchronous call to moved().
  23634. Note that if you've used setTransform() to apply a transform, then the component's
  23635. bounds will no longer be a direct reflection of the position at which it appears within
  23636. its parent, as the transform will be applied to whatever bounds you set for it.
  23637. @see setBounds, ComponentListener::componentMovedOrResized
  23638. */
  23639. void setTopLeftPosition (int x, int y);
  23640. /** Moves the component to a new position.
  23641. Changes the position of the component's top-right corner (keeping it the same size).
  23642. The position is relative to the top-left of the component's parent.
  23643. If the component actually moves, this method will make a synchronous call to moved().
  23644. Note that if you've used setTransform() to apply a transform, then the component's
  23645. bounds will no longer be a direct reflection of the position at which it appears within
  23646. its parent, as the transform will be applied to whatever bounds you set for it.
  23647. */
  23648. void setTopRightPosition (int x, int y);
  23649. /** Changes the size of the component.
  23650. A synchronous call to resized() will be occur if the size actually changes.
  23651. Note that if you've used setTransform() to apply a transform, then the component's
  23652. bounds will no longer be a direct reflection of the position at which it appears within
  23653. its parent, as the transform will be applied to whatever bounds you set for it.
  23654. */
  23655. void setSize (int newWidth, int newHeight);
  23656. /** Changes the component's position and size.
  23657. The coordinates are relative to the top-left of the component's parent, or relative
  23658. to the origin of the screen is the component is on the desktop.
  23659. If this method changes the component's top-left position, it will make a synchronous
  23660. call to moved(). If it changes the size, it will also make a call to resized().
  23661. Note that if you've used setTransform() to apply a transform, then the component's
  23662. bounds will no longer be a direct reflection of the position at which it appears within
  23663. its parent, as the transform will be applied to whatever bounds you set for it.
  23664. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  23665. */
  23666. void setBounds (int x, int y, int width, int height);
  23667. /** Changes the component's position and size.
  23668. The coordinates are relative to the top-left of the component's parent, or relative
  23669. to the origin of the screen is the component is on the desktop.
  23670. If this method changes the component's top-left position, it will make a synchronous
  23671. call to moved(). If it changes the size, it will also make a call to resized().
  23672. Note that if you've used setTransform() to apply a transform, then the component's
  23673. bounds will no longer be a direct reflection of the position at which it appears within
  23674. its parent, as the transform will be applied to whatever bounds you set for it.
  23675. @see setBounds
  23676. */
  23677. void setBounds (const Rectangle<int>& newBounds);
  23678. /** Changes the component's position and size.
  23679. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  23680. to set the position, This uses a Component::Positioner to make sure that any dynamic
  23681. expressions are used in the RelativeRectangle will be automatically re-applied to the
  23682. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  23683. for more details.
  23684. When using relative expressions, the following symbols are available:
  23685. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  23686. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  23687. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  23688. the identifier of one of this component's siblings. A component's identifier is set with
  23689. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  23690. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  23691. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  23692. any other component, these values are relative to their component's parent, so "parent.right" won't be
  23693. very useful for positioning a component because it refers to a position with the parent's parent.. but
  23694. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  23695. component which remains 1 pixel away from its parent's bottom-right, you could use
  23696. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  23697. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  23698. used, the parent component must implement its Component::getMarkers() method, and return at least one
  23699. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  23700. marker called "foobar", you'd set it to "foobar + 10".
  23701. See the Expression class for details about the operators that are supported, but for example
  23702. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  23703. you could express it as:
  23704. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  23705. @endcode
  23706. ..or an alternative way to achieve the same thing:
  23707. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  23708. @endcode
  23709. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  23710. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  23711. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  23712. @endcode
  23713. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  23714. be thrown!
  23715. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  23716. */
  23717. void setBounds (const RelativeRectangle& newBounds);
  23718. /** Sets the component's bounds with an expression.
  23719. The string is parsed as a RelativeRectangle expression - see the notes for
  23720. Component::setBounds (const RelativeRectangle&) for more information. This method is
  23721. basically just a shortcut for writing setBounds (RelativeRectangle ("..."))
  23722. */
  23723. void setBounds (const String& newBoundsExpression);
  23724. /** Changes the component's position and size in terms of fractions of its parent's size.
  23725. The values are factors of the parent's size, so for example
  23726. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  23727. width and height of the parent, with its top-left position 20% of
  23728. the way across and down the parent.
  23729. @see setBounds
  23730. */
  23731. void setBoundsRelative (float proportionalX, float proportionalY,
  23732. float proportionalWidth, float proportionalHeight);
  23733. /** Changes the component's position and size based on the amount of space to leave around it.
  23734. This will position the component within its parent, leaving the specified number of
  23735. pixels around each edge.
  23736. @see setBounds
  23737. */
  23738. void setBoundsInset (const BorderSize<int>& borders);
  23739. /** Positions the component within a given rectangle, keeping its proportions
  23740. unchanged.
  23741. If onlyReduceInSize is false, the component will be resized to fill as much of the
  23742. rectangle as possible without changing its aspect ratio (the component's
  23743. current size is used to determine its aspect ratio, so a zero-size component
  23744. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  23745. too big to fit inside the rectangle.
  23746. It will then be positioned within the rectangle according to the justification flags
  23747. specified.
  23748. @see setBounds
  23749. */
  23750. void setBoundsToFit (int x, int y, int width, int height,
  23751. const Justification& justification,
  23752. bool onlyReduceInSize);
  23753. /** Changes the position of the component's centre.
  23754. Leaves the component's size unchanged, but sets the position of its centre
  23755. relative to its parent's top-left.
  23756. @see setBounds
  23757. */
  23758. void setCentrePosition (int x, int y);
  23759. /** Changes the position of the component's centre.
  23760. Leaves the position unchanged, but positions its centre relative to its
  23761. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  23762. its parent.
  23763. */
  23764. void setCentreRelative (float x, float y);
  23765. /** Changes the component's size and centres it within its parent.
  23766. After changing the size, the component will be moved so that it's
  23767. centred within its parent. If the component is on the desktop (or has no
  23768. parent component), then it'll be centred within the main monitor area.
  23769. */
  23770. void centreWithSize (int width, int height);
  23771. /** Sets a transform matrix to be applied to this component.
  23772. If you set a transform for a component, the component's position will be warped by it, relative to
  23773. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  23774. longer reflect the actual area within the parent that the component covers, as the bounds will be
  23775. transformed and the component will probably end up actually appearing somewhere else within its parent.
  23776. When using transforms you need to be extremely careful when converting coordinates between the
  23777. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  23778. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  23779. convert it between different components (but I'm sure you would never have done that anyway...).
  23780. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  23781. put a component on the desktop.
  23782. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  23783. */
  23784. void setTransform (const AffineTransform& transform);
  23785. /** Returns the transform that is currently being applied to this component.
  23786. For more details about transforms, see setTransform().
  23787. @see setTransform
  23788. */
  23789. const AffineTransform getTransform() const;
  23790. /** Returns true if a non-identity transform is being applied to this component.
  23791. For more details about transforms, see setTransform().
  23792. @see setTransform
  23793. */
  23794. bool isTransformed() const throw();
  23795. /** Returns a proportion of the component's width.
  23796. This is a handy equivalent of (getWidth() * proportion).
  23797. */
  23798. int proportionOfWidth (float proportion) const throw();
  23799. /** Returns a proportion of the component's height.
  23800. This is a handy equivalent of (getHeight() * proportion).
  23801. */
  23802. int proportionOfHeight (float proportion) const throw();
  23803. /** Returns the width of the component's parent.
  23804. If the component has no parent (i.e. if it's on the desktop), this will return
  23805. the width of the screen.
  23806. */
  23807. int getParentWidth() const throw();
  23808. /** Returns the height of the component's parent.
  23809. If the component has no parent (i.e. if it's on the desktop), this will return
  23810. the height of the screen.
  23811. */
  23812. int getParentHeight() const throw();
  23813. /** Returns the screen coordinates of the monitor that contains this component.
  23814. If there's only one monitor, this will return its size - if there are multiple
  23815. monitors, it will return the area of the monitor that contains the component's
  23816. centre.
  23817. */
  23818. const Rectangle<int> getParentMonitorArea() const;
  23819. /** Returns the number of child components that this component contains.
  23820. @see getChildComponent, getIndexOfChildComponent
  23821. */
  23822. int getNumChildComponents() const throw();
  23823. /** Returns one of this component's child components, by it index.
  23824. The component with index 0 is at the back of the z-order, the one at the
  23825. front will have index (getNumChildComponents() - 1).
  23826. If the index is out-of-range, this will return a null pointer.
  23827. @see getNumChildComponents, getIndexOfChildComponent
  23828. */
  23829. Component* getChildComponent (int index) const throw();
  23830. /** Returns the index of this component in the list of child components.
  23831. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  23832. values are further towards the front.
  23833. Returns -1 if the component passed-in is not a child of this component.
  23834. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  23835. */
  23836. int getIndexOfChildComponent (const Component* child) const throw();
  23837. /** Adds a child component to this one.
  23838. Adding a child component does not mean that the component will own or delete the child - it's
  23839. your responsibility to delete the component. Note that it's safe to delete a component
  23840. without first removing it from its parent - doing so will automatically remove it and
  23841. send out the appropriate notifications before the deletion completes.
  23842. If the child is already a child of this component, then no action will be taken, and its
  23843. z-order will be left unchanged.
  23844. @param child the new component to add. If the component passed-in is already
  23845. the child of another component, it'll first be removed from it current parent.
  23846. @param zOrder The index in the child-list at which this component should be inserted.
  23847. A value of -1 will insert it in front of the others, 0 is the back.
  23848. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  23849. */
  23850. void addChildComponent (Component* child, int zOrder = -1);
  23851. /** Adds a child component to this one, and also makes the child visible if it isn't.
  23852. Quite a useful function, this is just the same as calling setVisible (true) on the child
  23853. and then addChildComponent(). See addChildComponent() for more details.
  23854. */
  23855. void addAndMakeVisible (Component* child, int zOrder = -1);
  23856. /** Removes one of this component's child-components.
  23857. If the child passed-in isn't actually a child of this component (either because
  23858. it's invalid or is the child of a different parent), then no action is taken.
  23859. Note that removing a child will not delete it! But it's ok to delete a component
  23860. without first removing it - doing so will automatically remove it and send out the
  23861. appropriate notifications before the deletion completes.
  23862. @see addChildComponent, ComponentListener::componentChildrenChanged
  23863. */
  23864. void removeChildComponent (Component* childToRemove);
  23865. /** Removes one of this component's child-components by index.
  23866. This will return a pointer to the component that was removed, or null if
  23867. the index was out-of-range.
  23868. Note that removing a child will not delete it! But it's ok to delete a component
  23869. without first removing it - doing so will automatically remove it and send out the
  23870. appropriate notifications before the deletion completes.
  23871. @see addChildComponent, ComponentListener::componentChildrenChanged
  23872. */
  23873. Component* removeChildComponent (int childIndexToRemove);
  23874. /** Removes all this component's children.
  23875. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  23876. */
  23877. void removeAllChildren();
  23878. /** Removes all this component's children, and deletes them.
  23879. @see removeAllChildren
  23880. */
  23881. void deleteAllChildren();
  23882. /** Returns the component which this component is inside.
  23883. If this is the highest-level component or hasn't yet been added to
  23884. a parent, this will return null.
  23885. */
  23886. Component* getParentComponent() const throw() { return parentComponent; }
  23887. /** Searches the parent components for a component of a specified class.
  23888. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  23889. component that can be dynamically cast to a MyComp, or will return 0 if none
  23890. of the parents are suitable.
  23891. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  23892. */
  23893. template <class TargetClass>
  23894. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  23895. {
  23896. (void) dummyParameter;
  23897. Component* p = parentComponent;
  23898. while (p != 0)
  23899. {
  23900. TargetClass* target = dynamic_cast <TargetClass*> (p);
  23901. if (target != 0)
  23902. return target;
  23903. p = p->parentComponent;
  23904. }
  23905. return 0;
  23906. }
  23907. /** Returns the highest-level component which contains this one or its parents.
  23908. This will search upwards in the parent-hierarchy from this component, until it
  23909. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  23910. not yet added to a parent), and will return that.
  23911. */
  23912. Component* getTopLevelComponent() const throw();
  23913. /** Checks whether a component is anywhere inside this component or its children.
  23914. This will recursively check through this component's children to see if the
  23915. given component is anywhere inside.
  23916. */
  23917. bool isParentOf (const Component* possibleChild) const throw();
  23918. /** Called to indicate that the component's parents have changed.
  23919. When a component is added or removed from its parent, this method will
  23920. be called on all of its children (recursively - so all children of its
  23921. children will also be called as well).
  23922. Subclasses can override this if they need to react to this in some way.
  23923. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  23924. */
  23925. virtual void parentHierarchyChanged();
  23926. /** Subclasses can use this callback to be told when children are added or removed.
  23927. @see parentHierarchyChanged
  23928. */
  23929. virtual void childrenChanged();
  23930. /** Tests whether a given point inside the component.
  23931. Overriding this method allows you to create components which only intercept
  23932. mouse-clicks within a user-defined area.
  23933. This is called to find out whether a particular x, y coordinate is
  23934. considered to be inside the component or not, and is used by methods such
  23935. as contains() and getComponentAt() to work out which component
  23936. the mouse is clicked on.
  23937. Components with custom shapes will probably want to override it to perform
  23938. some more complex hit-testing.
  23939. The default implementation of this method returns either true or false,
  23940. depending on the value that was set by calling setInterceptsMouseClicks() (true
  23941. is the default return value).
  23942. Note that the hit-test region is not related to the opacity with which
  23943. areas of a component are painted.
  23944. Applications should never call hitTest() directly - instead use the
  23945. contains() method, because this will also test for occlusion by the
  23946. component's parent.
  23947. Note that for components on the desktop, this method will be ignored, because it's
  23948. not always possible to implement this behaviour on all platforms.
  23949. @param x the x coordinate to test, relative to the left hand edge of this
  23950. component. This value is guaranteed to be greater than or equal to
  23951. zero, and less than the component's width
  23952. @param y the y coordinate to test, relative to the top edge of this
  23953. component. This value is guaranteed to be greater than or equal to
  23954. zero, and less than the component's height
  23955. @returns true if the click is considered to be inside the component
  23956. @see setInterceptsMouseClicks, contains
  23957. */
  23958. virtual bool hitTest (int x, int y);
  23959. /** Changes the default return value for the hitTest() method.
  23960. Setting this to false is an easy way to make a component pass its mouse-clicks
  23961. through to the components behind it.
  23962. When a component is created, the default setting for this is true.
  23963. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  23964. return false (or true for child components if allowClicksOnChildComponents
  23965. is true)
  23966. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  23967. components can be clicked on as normal but clicks on this component pass
  23968. straight through; if this is false and allowClicksOnThisComponent
  23969. is false, then neither this component nor any child components can
  23970. be clicked on
  23971. @see hitTest, getInterceptsMouseClicks
  23972. */
  23973. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  23974. bool allowClicksOnChildComponents) throw();
  23975. /** Retrieves the current state of the mouse-click interception flags.
  23976. On return, the two parameters are set to the state used in the last call to
  23977. setInterceptsMouseClicks().
  23978. @see setInterceptsMouseClicks
  23979. */
  23980. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  23981. bool& allowsClicksOnChildComponents) const throw();
  23982. /** Returns true if a given point lies within this component or one of its children.
  23983. Never override this method! Use hitTest to create custom hit regions.
  23984. @param localPoint the coordinate to test, relative to this component's top-left.
  23985. @returns true if the point is within the component's hit-test area, but only if
  23986. that part of the component isn't clipped by its parent component. Note
  23987. that this won't take into account any overlapping sibling components
  23988. which might be in the way - for that, see reallyContains()
  23989. @see hitTest, reallyContains, getComponentAt
  23990. */
  23991. bool contains (const Point<int>& localPoint);
  23992. /** Returns true if a given point lies in this component, taking any overlapping
  23993. siblings into account.
  23994. @param localPoint the coordinate to test, relative to this component's top-left.
  23995. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  23996. this determines whether that is counted as a hit.
  23997. @see contains, getComponentAt
  23998. */
  23999. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  24000. /** Returns the component at a certain point within this one.
  24001. @param x the x coordinate to test, relative to this component's left edge.
  24002. @param y the y coordinate to test, relative to this component's top edge.
  24003. @returns the component that is at this position - which may be 0, this component,
  24004. or one of its children. Note that overlapping siblings that might actually
  24005. be in the way are not taken into account by this method - to account for these,
  24006. instead call getComponentAt on the top-level parent of this component.
  24007. @see hitTest, contains, reallyContains
  24008. */
  24009. Component* getComponentAt (int x, int y);
  24010. /** Returns the component at a certain point within this one.
  24011. @param position the coordinate to test, relative to this component's top-left.
  24012. @returns the component that is at this position - which may be 0, this component,
  24013. or one of its children. Note that overlapping siblings that might actually
  24014. be in the way are not taken into account by this method - to account for these,
  24015. instead call getComponentAt on the top-level parent of this component.
  24016. @see hitTest, contains, reallyContains
  24017. */
  24018. Component* getComponentAt (const Point<int>& position);
  24019. /** Marks the whole component as needing to be redrawn.
  24020. Calling this will not do any repainting immediately, but will mark the component
  24021. as 'dirty'. At some point in the near future the operating system will send a paint
  24022. message, which will redraw all the dirty regions of all components.
  24023. There's no guarantee about how soon after calling repaint() the redraw will actually
  24024. happen, and other queued events may be delivered before a redraw is done.
  24025. If the setBufferedToImage() method has been used to cause this component
  24026. to use a buffer, the repaint() call will invalidate the component's buffer.
  24027. To redraw just a subsection of the component rather than the whole thing,
  24028. use the repaint (int, int, int, int) method.
  24029. @see paint
  24030. */
  24031. void repaint();
  24032. /** Marks a subsection of this component as needing to be redrawn.
  24033. Calling this will not do any repainting immediately, but will mark the given region
  24034. of the component as 'dirty'. At some point in the near future the operating system
  24035. will send a paint message, which will redraw all the dirty regions of all components.
  24036. There's no guarantee about how soon after calling repaint() the redraw will actually
  24037. happen, and other queued events may be delivered before a redraw is done.
  24038. The region that is passed in will be clipped to keep it within the bounds of this
  24039. component.
  24040. @see repaint()
  24041. */
  24042. void repaint (int x, int y, int width, int height);
  24043. /** Marks a subsection of this component as needing to be redrawn.
  24044. Calling this will not do any repainting immediately, but will mark the given region
  24045. of the component as 'dirty'. At some point in the near future the operating system
  24046. will send a paint message, which will redraw all the dirty regions of all components.
  24047. There's no guarantee about how soon after calling repaint() the redraw will actually
  24048. happen, and other queued events may be delivered before a redraw is done.
  24049. The region that is passed in will be clipped to keep it within the bounds of this
  24050. component.
  24051. @see repaint()
  24052. */
  24053. void repaint (const Rectangle<int>& area);
  24054. /** Makes the component use an internal buffer to optimise its redrawing.
  24055. Setting this flag to true will cause the component to allocate an
  24056. internal buffer into which it paints itself, so that when asked to
  24057. redraw itself, it can use this buffer rather than actually calling the
  24058. paint() method.
  24059. The buffer is kept until the repaint() method is called directly on
  24060. this component (or until it is resized), when the image is invalidated
  24061. and then redrawn the next time the component is painted.
  24062. Note that only the drawing that happens within the component's paint()
  24063. method is drawn into the buffer, it's child components are not buffered, and
  24064. nor is the paintOverChildren() method.
  24065. @see repaint, paint, createComponentSnapshot
  24066. */
  24067. void setBufferedToImage (bool shouldBeBuffered);
  24068. /** Generates a snapshot of part of this component.
  24069. This will return a new Image, the size of the rectangle specified,
  24070. containing a snapshot of the specified area of the component and all
  24071. its children.
  24072. The image may or may not have an alpha-channel, depending on whether the
  24073. image is opaque or not.
  24074. If the clipImageToComponentBounds parameter is true and the area is greater than
  24075. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  24076. then parts of the component beyond its bounds can be drawn.
  24077. @see paintEntireComponent
  24078. */
  24079. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  24080. bool clipImageToComponentBounds = true);
  24081. /** Draws this component and all its subcomponents onto the specified graphics
  24082. context.
  24083. You should very rarely have to use this method, it's simply there in case you need
  24084. to draw a component with a custom graphics context for some reason, e.g. for
  24085. creating a snapshot of the component.
  24086. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  24087. on its children in order to render the entire tree.
  24088. The graphics context may be left in an undefined state after this method returns,
  24089. so you may need to reset it if you're going to use it again.
  24090. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  24091. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  24092. an alpha of 1.0 will be used.
  24093. */
  24094. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  24095. /** This allows you to indicate that this component doesn't require its graphics
  24096. context to be clipped when it is being painted.
  24097. Most people will never need to use this setting, but in situations where you have a very large
  24098. number of simple components being rendered, and where they are guaranteed never to do any drawing
  24099. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  24100. the graphics context that gets passed to the component's paint() callback.
  24101. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  24102. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  24103. artifacts. Your component also can't have any child components that may be placed beyond its
  24104. bounds.
  24105. */
  24106. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) throw();
  24107. /** Adds an effect filter to alter the component's appearance.
  24108. When a component has an effect filter set, then this is applied to the
  24109. results of its paint() method. There are a few preset effects, such as
  24110. a drop-shadow or glow, but they can be user-defined as well.
  24111. The effect that is passed in will not be deleted by the component - the
  24112. caller must take care of deleting it.
  24113. To remove an effect from a component, pass a null pointer in as the parameter.
  24114. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  24115. */
  24116. void setComponentEffect (ImageEffectFilter* newEffect);
  24117. /** Returns the current component effect.
  24118. @see setComponentEffect
  24119. */
  24120. ImageEffectFilter* getComponentEffect() const throw() { return effect; }
  24121. /** Finds the appropriate look-and-feel to use for this component.
  24122. If the component hasn't had a look-and-feel explicitly set, this will
  24123. return the parent's look-and-feel, or just the default one if there's no
  24124. parent.
  24125. @see setLookAndFeel, lookAndFeelChanged
  24126. */
  24127. LookAndFeel& getLookAndFeel() const throw();
  24128. /** Sets the look and feel to use for this component.
  24129. This will also change the look and feel for any child components that haven't
  24130. had their look set explicitly.
  24131. The object passed in will not be deleted by the component, so it's the caller's
  24132. responsibility to manage it. It may be used at any time until this component
  24133. has been deleted.
  24134. Calling this method will also invoke the sendLookAndFeelChange() method.
  24135. @see getLookAndFeel, lookAndFeelChanged
  24136. */
  24137. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  24138. /** Called to let the component react to a change in the look-and-feel setting.
  24139. When the look-and-feel is changed for a component, this will be called in
  24140. all its child components, recursively.
  24141. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  24142. an application uses a LookAndFeel class that might have changed internally.
  24143. @see sendLookAndFeelChange, getLookAndFeel
  24144. */
  24145. virtual void lookAndFeelChanged();
  24146. /** Calls the lookAndFeelChanged() method in this component and all its children.
  24147. This will recurse through the children and their children, calling lookAndFeelChanged()
  24148. on them all.
  24149. @see lookAndFeelChanged
  24150. */
  24151. void sendLookAndFeelChange();
  24152. /** Indicates whether any parts of the component might be transparent.
  24153. Components that always paint all of their contents with solid colour and
  24154. thus completely cover any components behind them should use this method
  24155. to tell the repaint system that they are opaque.
  24156. This information is used to optimise drawing, because it means that
  24157. objects underneath opaque windows don't need to be painted.
  24158. By default, components are considered transparent, unless this is used to
  24159. make it otherwise.
  24160. @see isOpaque, getVisibleArea
  24161. */
  24162. void setOpaque (bool shouldBeOpaque);
  24163. /** Returns true if no parts of this component are transparent.
  24164. @returns the value that was set by setOpaque, (the default being false)
  24165. @see setOpaque
  24166. */
  24167. bool isOpaque() const throw();
  24168. /** Indicates whether the component should be brought to the front when clicked.
  24169. Setting this flag to true will cause the component to be brought to the front
  24170. when the mouse is clicked somewhere inside it or its child components.
  24171. Note that a top-level desktop window might still be brought to the front by the
  24172. operating system when it's clicked, depending on how the OS works.
  24173. By default this is set to false.
  24174. @see setMouseClickGrabsKeyboardFocus
  24175. */
  24176. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  24177. /** Indicates whether the component should be brought to the front when clicked-on.
  24178. @see setBroughtToFrontOnMouseClick
  24179. */
  24180. bool isBroughtToFrontOnMouseClick() const throw();
  24181. // Keyboard focus methods
  24182. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  24183. By default components aren't actually interested in gaining the
  24184. focus, but this method can be used to turn this on.
  24185. See the grabKeyboardFocus() method for details about the way a component
  24186. is chosen to receive the focus.
  24187. @see grabKeyboardFocus, getWantsKeyboardFocus
  24188. */
  24189. void setWantsKeyboardFocus (bool wantsFocus) throw();
  24190. /** Returns true if the component is interested in getting keyboard focus.
  24191. This returns the flag set by setWantsKeyboardFocus(). The default
  24192. setting is false.
  24193. @see setWantsKeyboardFocus
  24194. */
  24195. bool getWantsKeyboardFocus() const throw();
  24196. /** Chooses whether a click on this component automatically grabs the focus.
  24197. By default this is set to true, but you might want a component which can
  24198. be focused, but where you don't want the user to be able to affect it directly
  24199. by clicking.
  24200. */
  24201. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  24202. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  24203. See setMouseClickGrabsKeyboardFocus() for more info.
  24204. */
  24205. bool getMouseClickGrabsKeyboardFocus() const throw();
  24206. /** Tries to give keyboard focus to this component.
  24207. When the user clicks on a component or its grabKeyboardFocus()
  24208. method is called, the following procedure is used to work out which
  24209. component should get it:
  24210. - if the component that was clicked on actually wants focus (as indicated
  24211. by calling getWantsKeyboardFocus), it gets it.
  24212. - if the component itself doesn't want focus, it will try to pass it
  24213. on to whichever of its children is the default component, as determined by
  24214. KeyboardFocusTraverser::getDefaultComponent()
  24215. - if none of its children want focus at all, it will pass it up to its
  24216. parent instead, unless it's a top-level component without a parent,
  24217. in which case it just takes the focus itself.
  24218. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  24219. getCurrentlyFocusedComponent, focusGained, focusLost,
  24220. keyPressed, keyStateChanged
  24221. */
  24222. void grabKeyboardFocus();
  24223. /** Returns true if this component currently has the keyboard focus.
  24224. @param trueIfChildIsFocused if this is true, then the method returns true if
  24225. either this component or any of its children (recursively)
  24226. have the focus. If false, the method only returns true if
  24227. this component has the focus.
  24228. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  24229. focusGained, focusLost
  24230. */
  24231. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  24232. /** Returns the component that currently has the keyboard focus.
  24233. @returns the focused component, or null if nothing is focused.
  24234. */
  24235. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  24236. /** Tries to move the keyboard focus to one of this component's siblings.
  24237. This will try to move focus to either the next or previous component. (This
  24238. is the method that is used when shifting focus by pressing the tab key).
  24239. Components for which getWantsKeyboardFocus() returns false are not looked at.
  24240. @param moveToNext if true, the focus will move forwards; if false, it will
  24241. move backwards
  24242. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  24243. */
  24244. void moveKeyboardFocusToSibling (bool moveToNext);
  24245. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  24246. which focus should be passed from this component.
  24247. The default implementation of this method will return a default
  24248. KeyboardFocusTraverser if this component is a focus container (as determined
  24249. by the setFocusContainer() method). If the component isn't a focus
  24250. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  24251. If you overrride this to return a custom KeyboardFocusTraverser, then
  24252. this component and all its sub-components will use the new object to
  24253. make their focusing decisions.
  24254. The method should return a new object, which the caller is required to
  24255. delete when no longer needed.
  24256. */
  24257. virtual KeyboardFocusTraverser* createFocusTraverser();
  24258. /** Returns the focus order of this component, if one has been specified.
  24259. By default components don't have a focus order - in that case, this
  24260. will return 0. Lower numbers indicate that the component will be
  24261. earlier in the focus traversal order.
  24262. To change the order, call setExplicitFocusOrder().
  24263. The focus order may be used by the KeyboardFocusTraverser class as part of
  24264. its algorithm for deciding the order in which components should be traversed.
  24265. See the KeyboardFocusTraverser class for more details on this.
  24266. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  24267. */
  24268. int getExplicitFocusOrder() const;
  24269. /** Sets the index used in determining the order in which focusable components
  24270. should be traversed.
  24271. A value of 0 or less is taken to mean that no explicit order is wanted, and
  24272. that traversal should use other factors, like the component's position.
  24273. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  24274. */
  24275. void setExplicitFocusOrder (int newFocusOrderIndex);
  24276. /** Indicates whether this component is a parent for components that can have
  24277. their focus traversed.
  24278. This flag is used by the default implementation of the createFocusTraverser()
  24279. method, which uses the flag to find the first parent component (of the currently
  24280. focused one) which wants to be a focus container.
  24281. So using this method to set the flag to 'true' causes this component to
  24282. act as the top level within which focus is passed around.
  24283. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  24284. */
  24285. void setFocusContainer (bool shouldBeFocusContainer) throw();
  24286. /** Returns true if this component has been marked as a focus container.
  24287. See setFocusContainer() for more details.
  24288. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  24289. */
  24290. bool isFocusContainer() const throw();
  24291. /** Returns true if the component (and all its parents) are enabled.
  24292. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  24293. what difference this makes to the component depends on the type. E.g. buttons
  24294. and sliders will choose to draw themselves differently, etc.
  24295. Note that if one of this component's parents is disabled, this will always
  24296. return false, even if this component itself is enabled.
  24297. @see setEnabled, enablementChanged
  24298. */
  24299. bool isEnabled() const throw();
  24300. /** Enables or disables this component.
  24301. Disabling a component will also cause all of its child components to become
  24302. disabled.
  24303. Similarly, enabling a component which is inside a disabled parent
  24304. component won't make any difference until the parent is re-enabled.
  24305. @see isEnabled, enablementChanged
  24306. */
  24307. void setEnabled (bool shouldBeEnabled);
  24308. /** Callback to indicate that this component has been enabled or disabled.
  24309. This can be triggered by one of the component's parent components
  24310. being enabled or disabled, as well as changes to the component itself.
  24311. The default implementation of this method does nothing; your class may
  24312. wish to repaint itself or something when this happens.
  24313. @see setEnabled, isEnabled
  24314. */
  24315. virtual void enablementChanged();
  24316. /** Changes the transparency of this component.
  24317. When painted, the entire component and all its children will be rendered
  24318. with this as the overall opacity level, where 0 is completely invisible, and
  24319. 1.0 is fully opaque (i.e. normal).
  24320. @see getAlpha
  24321. */
  24322. void setAlpha (float newAlpha);
  24323. /** Returns the component's current transparancy level.
  24324. See setAlpha() for more details.
  24325. */
  24326. float getAlpha() const;
  24327. /** Changes the mouse cursor shape to use when the mouse is over this component.
  24328. Note that the cursor set by this method can be overridden by the getMouseCursor
  24329. method.
  24330. @see MouseCursor
  24331. */
  24332. void setMouseCursor (const MouseCursor& cursorType);
  24333. /** Returns the mouse cursor shape to use when the mouse is over this component.
  24334. The default implementation will return the cursor that was set by setCursor()
  24335. but can be overridden for more specialised purposes, e.g. returning different
  24336. cursors depending on the mouse position.
  24337. @see MouseCursor
  24338. */
  24339. virtual const MouseCursor getMouseCursor();
  24340. /** Forces the current mouse cursor to be updated.
  24341. If you're overriding the getMouseCursor() method to control which cursor is
  24342. displayed, then this will only be checked each time the user moves the mouse. So
  24343. if you want to force the system to check that the cursor being displayed is
  24344. up-to-date (even if the mouse is just sitting there), call this method.
  24345. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  24346. calling this).
  24347. */
  24348. void updateMouseCursor() const;
  24349. /** Components can override this method to draw their content.
  24350. The paint() method gets called when a region of a component needs redrawing,
  24351. either because the component's repaint() method has been called, or because
  24352. something has happened on the screen that means a section of a window needs
  24353. to be redrawn.
  24354. Any child components will draw themselves over whatever this method draws. If
  24355. you need to paint over the top of your child components, you can also implement
  24356. the paintOverChildren() method to do this.
  24357. If you want to cause a component to redraw itself, this is done asynchronously -
  24358. calling the repaint() method marks a region of the component as "dirty", and the
  24359. paint() method will automatically be called sometime later, by the message thread,
  24360. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  24361. you never redraw something synchronously.
  24362. You should never need to call this method directly - to take a snapshot of the
  24363. component you could use createComponentSnapshot() or paintEntireComponent().
  24364. @param g the graphics context that must be used to do the drawing operations.
  24365. @see repaint, paintOverChildren, Graphics
  24366. */
  24367. virtual void paint (Graphics& g);
  24368. /** Components can override this method to draw over the top of their children.
  24369. For most drawing operations, it's better to use the normal paint() method,
  24370. but if you need to overlay something on top of the children, this can be
  24371. used.
  24372. @see paint, Graphics
  24373. */
  24374. virtual void paintOverChildren (Graphics& g);
  24375. /** Called when the mouse moves inside this component.
  24376. If the mouse button isn't pressed and the mouse moves over a component,
  24377. this will be called to let the component react to this.
  24378. A component will always get a mouseEnter callback before a mouseMove.
  24379. @param e details about the position and status of the mouse event
  24380. @see mouseEnter, mouseExit, mouseDrag, contains
  24381. */
  24382. virtual void mouseMove (const MouseEvent& e);
  24383. /** Called when the mouse first enters this component.
  24384. If the mouse button isn't pressed and the mouse moves into a component,
  24385. this will be called to let the component react to this.
  24386. When the mouse button is pressed and held down while being moved in
  24387. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  24388. mouseDrag messages are sent to the component that the mouse was originally
  24389. clicked on, until the button is released.
  24390. If you're writing a component that needs to repaint itself when the mouse
  24391. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24392. method.
  24393. @param e details about the position and status of the mouse event
  24394. @see mouseExit, mouseDrag, mouseMove, contains
  24395. */
  24396. virtual void mouseEnter (const MouseEvent& e);
  24397. /** Called when the mouse moves out of this component.
  24398. This will be called when the mouse moves off the edge of this
  24399. component.
  24400. If the mouse button was pressed, and it was then dragged off the
  24401. edge of the component and released, then this callback will happen
  24402. when the button is released, after the mouseUp callback.
  24403. If you're writing a component that needs to repaint itself when the mouse
  24404. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  24405. method.
  24406. @param e details about the position and status of the mouse event
  24407. @see mouseEnter, mouseDrag, mouseMove, contains
  24408. */
  24409. virtual void mouseExit (const MouseEvent& e);
  24410. /** Called when a mouse button is pressed while it's over this component.
  24411. The MouseEvent object passed in contains lots of methods for finding out
  24412. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24413. were held down at the time.
  24414. Once a button is held down, the mouseDrag method will be called when the
  24415. mouse moves, until the button is released.
  24416. @param e details about the position and status of the mouse event
  24417. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  24418. */
  24419. virtual void mouseDown (const MouseEvent& e);
  24420. /** Called when the mouse is moved while a button is held down.
  24421. When a mouse button is pressed inside a component, that component
  24422. receives mouseDrag callbacks each time the mouse moves, even if the
  24423. mouse strays outside the component's bounds.
  24424. If you want to be able to drag things off the edge of a component
  24425. and have the component scroll when you get to the edges, the
  24426. beginDragAutoRepeat() method might be useful.
  24427. @param e details about the position and status of the mouse event
  24428. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  24429. */
  24430. virtual void mouseDrag (const MouseEvent& e);
  24431. /** Called when a mouse button is released.
  24432. A mouseUp callback is sent to the component in which a button was pressed
  24433. even if the mouse is actually over a different component when the
  24434. button is released.
  24435. The MouseEvent object passed in contains lots of methods for finding out
  24436. which buttons were down just before they were released.
  24437. @param e details about the position and status of the mouse event
  24438. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  24439. */
  24440. virtual void mouseUp (const MouseEvent& e);
  24441. /** Called when a mouse button has been double-clicked in this component.
  24442. The MouseEvent object passed in contains lots of methods for finding out
  24443. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  24444. were held down at the time.
  24445. For altering the time limit used to detect double-clicks,
  24446. see MouseEvent::setDoubleClickTimeout.
  24447. @param e details about the position and status of the mouse event
  24448. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  24449. MouseEvent::getDoubleClickTimeout
  24450. */
  24451. virtual void mouseDoubleClick (const MouseEvent& e);
  24452. /** Called when the mouse-wheel is moved.
  24453. This callback is sent to the component that the mouse is over when the
  24454. wheel is moved.
  24455. If not overridden, the component will forward this message to its parent, so
  24456. that parent components can collect mouse-wheel messages that happen to
  24457. child components which aren't interested in them.
  24458. @param e details about the position and status of the mouse event
  24459. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  24460. value means the wheel has been pushed to the right, negative means it
  24461. was pushed to the left
  24462. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  24463. value means the wheel has been pushed upwards, negative means it
  24464. was pushed downwards
  24465. */
  24466. virtual void mouseWheelMove (const MouseEvent& e,
  24467. float wheelIncrementX,
  24468. float wheelIncrementY);
  24469. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  24470. current mouse-drag operation.
  24471. This allows you to make sure that mouseDrag() events are sent continuously, even
  24472. when the mouse isn't moving. This can be useful for things like auto-scrolling
  24473. components when the mouse is near an edge.
  24474. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  24475. minimum interval between consecutive mouse drag callbacks. The callbacks
  24476. will continue until the mouse is released, and then the interval will be reset,
  24477. so you need to make sure it's called every time you begin a drag event.
  24478. Passing an interval of 0 or less will cancel the auto-repeat.
  24479. @see mouseDrag, Desktop::beginDragAutoRepeat
  24480. */
  24481. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  24482. /** Causes automatic repaints when the mouse enters or exits this component.
  24483. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  24484. on the component, it will trigger a repaint.
  24485. This is handy for things like buttons that need to draw themselves differently when
  24486. the mouse moves over them, and it avoids having to override all the different mouse
  24487. callbacks and call repaint().
  24488. @see mouseEnter, mouseExit, mouseDown, mouseUp
  24489. */
  24490. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  24491. /** Registers a listener to be told when mouse events occur in this component.
  24492. If you need to get informed about mouse events in a component but can't or
  24493. don't want to override its methods, you can attach any number of listeners
  24494. to the component, and these will get told about the events in addition to
  24495. the component's own callbacks being called.
  24496. Note that a MouseListener can also be attached to more than one component.
  24497. @param newListener the listener to register
  24498. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  24499. for events that happen to any child component
  24500. within this component, including deeply-nested
  24501. child components. If false, it will only be
  24502. told about events that this component handles.
  24503. @see MouseListener, removeMouseListener
  24504. */
  24505. void addMouseListener (MouseListener* newListener,
  24506. bool wantsEventsForAllNestedChildComponents);
  24507. /** Deregisters a mouse listener.
  24508. @see addMouseListener, MouseListener
  24509. */
  24510. void removeMouseListener (MouseListener* listenerToRemove);
  24511. /** Adds a listener that wants to hear about keypresses that this component receives.
  24512. The listeners that are registered with a component are called by its keyPressed() or
  24513. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  24514. If you add an object as a key listener, be careful to remove it when the object
  24515. is deleted, or the component will be left with a dangling pointer.
  24516. @see keyPressed, keyStateChanged, removeKeyListener
  24517. */
  24518. void addKeyListener (KeyListener* newListener);
  24519. /** Removes a previously-registered key listener.
  24520. @see addKeyListener
  24521. */
  24522. void removeKeyListener (KeyListener* listenerToRemove);
  24523. /** Called when a key is pressed.
  24524. When a key is pressed, the component that has the keyboard focus will have this
  24525. method called. Remember that a component will only be given the focus if its
  24526. setWantsKeyboardFocus() method has been used to enable this.
  24527. If your implementation returns true, the event will be consumed and not passed
  24528. on to any other listeners. If it returns false, the key will be passed to any
  24529. KeyListeners that have been registered with this component. As soon as one of these
  24530. returns true, the process will stop, but if they all return false, the event will
  24531. be passed upwards to this component's parent, and so on.
  24532. The default implementation of this method does nothing and returns false.
  24533. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  24534. */
  24535. virtual bool keyPressed (const KeyPress& key);
  24536. /** Called when a key is pressed or released.
  24537. Whenever a key on the keyboard is pressed or released (including modifier keys
  24538. like shift and ctrl), this method will be called on the component that currently
  24539. has the keyboard focus. Remember that a component will only be given the focus if
  24540. its setWantsKeyboardFocus() method has been used to enable this.
  24541. If your implementation returns true, the event will be consumed and not passed
  24542. on to any other listeners. If it returns false, then any KeyListeners that have
  24543. been registered with this component will have their keyStateChanged methods called.
  24544. As soon as one of these returns true, the process will stop, but if they all return
  24545. false, the event will be passed upwards to this component's parent, and so on.
  24546. The default implementation of this method does nothing and returns false.
  24547. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  24548. method.
  24549. @param isKeyDown true if a key has been pressed; false if it has been released
  24550. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  24551. */
  24552. virtual bool keyStateChanged (bool isKeyDown);
  24553. /** Called when a modifier key is pressed or released.
  24554. Whenever the shift, control, alt or command keys are pressed or released,
  24555. this method will be called on the component that currently has the keyboard focus.
  24556. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  24557. method has been used to enable this.
  24558. The default implementation of this method actually calls its parent's modifierKeysChanged
  24559. method, so that focused components which aren't interested in this will give their
  24560. parents a chance to act on the event instead.
  24561. @see keyStateChanged, ModifierKeys
  24562. */
  24563. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  24564. /** Enumeration used by the focusChanged() and focusLost() methods. */
  24565. enum FocusChangeType
  24566. {
  24567. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  24568. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  24569. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  24570. };
  24571. /** Called to indicate that this component has just acquired the keyboard focus.
  24572. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24573. */
  24574. virtual void focusGained (FocusChangeType cause);
  24575. /** Called to indicate that this component has just lost the keyboard focus.
  24576. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24577. */
  24578. virtual void focusLost (FocusChangeType cause);
  24579. /** Called to indicate that one of this component's children has been focused or unfocused.
  24580. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  24581. changed. It happens when focus moves from one of this component's children (at any depth)
  24582. to a component that isn't contained in this one, (or vice-versa).
  24583. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24584. */
  24585. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  24586. /** Returns true if the mouse is currently over this component.
  24587. If the mouse isn't over the component, this will return false, even if the
  24588. mouse is currently being dragged - so you can use this in your mouseDrag
  24589. method to find out whether it's really over the component or not.
  24590. Note that when the mouse button is being held down, then the only component
  24591. for which this method will return true is the one that was originally
  24592. clicked on.
  24593. If includeChildren is true, then this will also return true if the mouse is over
  24594. any of the component's children (recursively) as well as the component itself.
  24595. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  24596. */
  24597. bool isMouseOver (bool includeChildren = false) const;
  24598. /** Returns true if the mouse button is currently held down in this component.
  24599. Note that this is a test to see whether the mouse is being pressed in this
  24600. component, so it'll return false if called on component A when the mouse
  24601. is actually being dragged in component B.
  24602. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  24603. */
  24604. bool isMouseButtonDown() const throw();
  24605. /** True if the mouse is over this component, or if it's being dragged in this component.
  24606. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  24607. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  24608. */
  24609. bool isMouseOverOrDragging() const throw();
  24610. /** Returns true if a mouse button is currently down.
  24611. Unlike isMouseButtonDown, this will test the current state of the
  24612. buttons without regard to which component (if any) it has been
  24613. pressed in.
  24614. @see isMouseButtonDown, ModifierKeys
  24615. */
  24616. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  24617. /** Returns the mouse's current position, relative to this component.
  24618. The return value is relative to the component's top-left corner.
  24619. */
  24620. const Point<int> getMouseXYRelative() const;
  24621. /** Called when this component's size has been changed.
  24622. A component can implement this method to do things such as laying out its
  24623. child components when its width or height changes.
  24624. The method is called synchronously as a result of the setBounds or setSize
  24625. methods, so repeatedly changing a components size will repeatedly call its
  24626. resized method (unlike things like repainting, where multiple calls to repaint
  24627. are coalesced together).
  24628. If the component is a top-level window on the desktop, its size could also
  24629. be changed by operating-system factors beyond the application's control.
  24630. @see moved, setSize
  24631. */
  24632. virtual void resized();
  24633. /** Called when this component's position has been changed.
  24634. This is called when the position relative to its parent changes, not when
  24635. its absolute position on the screen changes (so it won't be called for
  24636. all child components when a parent component is moved).
  24637. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  24638. or any of the other repositioning methods, and like resized(), it will be
  24639. called each time those methods are called.
  24640. If the component is a top-level window on the desktop, its position could also
  24641. be changed by operating-system factors beyond the application's control.
  24642. @see resized, setBounds
  24643. */
  24644. virtual void moved();
  24645. /** Called when one of this component's children is moved or resized.
  24646. If the parent wants to know about changes to its immediate children (not
  24647. to children of its children), this is the method to override.
  24648. @see moved, resized, parentSizeChanged
  24649. */
  24650. virtual void childBoundsChanged (Component* child);
  24651. /** Called when this component's immediate parent has been resized.
  24652. If the component is a top-level window, this indicates that the screen size
  24653. has changed.
  24654. @see childBoundsChanged, moved, resized
  24655. */
  24656. virtual void parentSizeChanged();
  24657. /** Called when this component has been moved to the front of its siblings.
  24658. The component may have been brought to the front by the toFront() method, or
  24659. by the operating system if it's a top-level window.
  24660. @see toFront
  24661. */
  24662. virtual void broughtToFront();
  24663. /** Adds a listener to be told about changes to the component hierarchy or position.
  24664. Component listeners get called when this component's size, position or children
  24665. change - see the ComponentListener class for more details.
  24666. @param newListener the listener to register - if this is already registered, it
  24667. will be ignored.
  24668. @see ComponentListener, removeComponentListener
  24669. */
  24670. void addComponentListener (ComponentListener* newListener);
  24671. /** Removes a component listener.
  24672. @see addComponentListener
  24673. */
  24674. void removeComponentListener (ComponentListener* listenerToRemove);
  24675. /** Dispatches a numbered message to this component.
  24676. This is a quick and cheap way of allowing simple asynchronous messages to
  24677. be sent to components. It's also safe, because if the component that you
  24678. send the message to is a null or dangling pointer, this won't cause an error.
  24679. The command ID is later delivered to the component's handleCommandMessage() method by
  24680. the application's message queue.
  24681. @see handleCommandMessage
  24682. */
  24683. void postCommandMessage (int commandId);
  24684. /** Called to handle a command that was sent by postCommandMessage().
  24685. This is called by the message thread when a command message arrives, and
  24686. the component can override this method to process it in any way it needs to.
  24687. @see postCommandMessage
  24688. */
  24689. virtual void handleCommandMessage (int commandId);
  24690. /** Runs a component modally, waiting until the loop terminates.
  24691. This method first makes the component visible, brings it to the front and
  24692. gives it the keyboard focus.
  24693. It then runs a loop, dispatching messages from the system message queue, but
  24694. blocking all mouse or keyboard messages from reaching any components other
  24695. than this one and its children.
  24696. This loop continues until the component's exitModalState() method is called (or
  24697. the component is deleted), and then this method returns, returning the value
  24698. passed into exitModalState().
  24699. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  24700. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  24701. */
  24702. #if JUCE_MODAL_LOOPS_PERMITTED
  24703. int runModalLoop();
  24704. #endif
  24705. /** Puts the component into a modal state.
  24706. This makes the component modal, so that messages are blocked from reaching
  24707. any components other than this one and its children, but unlike runModalLoop(),
  24708. this method returns immediately.
  24709. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  24710. get the focus, which is usually what you'll want it to do. If not, it will leave
  24711. the focus unchanged.
  24712. The callback is an optional object which will receive a callback when the modal
  24713. component loses its modal status, either by being hidden or when exitModalState()
  24714. is called. If you pass an object in here, the system will take care of deleting it
  24715. later, after making the callback
  24716. If deleteWhenDismissed is true, then when it is dismissed, the component will be
  24717. deleted and then the callback will be called. (This will safely handle the situation
  24718. where the component is deleted before its exitModalState() method is called).
  24719. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  24720. */
  24721. void enterModalState (bool takeKeyboardFocus = true,
  24722. ModalComponentManager::Callback* callback = 0,
  24723. bool deleteWhenDismissed = false);
  24724. /** Ends a component's modal state.
  24725. If this component is currently modal, this will turn of its modalness, and return
  24726. a value to the runModalLoop() method that might have be running its modal loop.
  24727. @see runModalLoop, enterModalState, isCurrentlyModal
  24728. */
  24729. void exitModalState (int returnValue);
  24730. /** Returns true if this component is the modal one.
  24731. It's possible to have nested modal components, e.g. a pop-up dialog box
  24732. that launches another pop-up, but this will only return true for
  24733. the one at the top of the stack.
  24734. @see getCurrentlyModalComponent
  24735. */
  24736. bool isCurrentlyModal() const throw();
  24737. /** Returns the number of components that are currently in a modal state.
  24738. @see getCurrentlyModalComponent
  24739. */
  24740. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  24741. /** Returns one of the components that are currently modal.
  24742. The index specifies which of the possible modal components to return. The order
  24743. of the components in this list is the reverse of the order in which they became
  24744. modal - so the component at index 0 is always the active component, and the others
  24745. are progressively earlier ones that are themselves now blocked by later ones.
  24746. @returns the modal component, or null if no components are modal (or if the
  24747. index is out of range)
  24748. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  24749. */
  24750. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  24751. /** Checks whether there's a modal component somewhere that's stopping this one
  24752. from receiving messages.
  24753. If there is a modal component, its canModalEventBeSentToComponent() method
  24754. will be called to see if it will still allow this component to receive events.
  24755. @see runModalLoop, getCurrentlyModalComponent
  24756. */
  24757. bool isCurrentlyBlockedByAnotherModalComponent() const;
  24758. /** When a component is modal, this callback allows it to choose which other
  24759. components can still receive events.
  24760. When a modal component is active and the user clicks on a non-modal component,
  24761. this method is called on the modal component, and if it returns true, the
  24762. event is allowed to reach its target. If it returns false, the event is blocked
  24763. and the inputAttemptWhenModal() callback is made.
  24764. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  24765. implementation just returns false in all cases.
  24766. */
  24767. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  24768. /** Called when the user tries to click on a component that is blocked by another
  24769. modal component.
  24770. When a component is modal and the user clicks on one of the other components,
  24771. the modal component will receive this callback.
  24772. The default implementation of this method will play a beep, and bring the currently
  24773. modal component to the front, but it can be overridden to do other tasks.
  24774. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  24775. */
  24776. virtual void inputAttemptWhenModal();
  24777. /** Returns the set of properties that belong to this component.
  24778. Each component has a NamedValueSet object which you can use to attach arbitrary
  24779. items of data to it.
  24780. */
  24781. NamedValueSet& getProperties() throw() { return properties; }
  24782. /** Returns the set of properties that belong to this component.
  24783. Each component has a NamedValueSet object which you can use to attach arbitrary
  24784. items of data to it.
  24785. */
  24786. const NamedValueSet& getProperties() const throw() { return properties; }
  24787. /** Looks for a colour that has been registered with the given colour ID number.
  24788. If a colour has been set for this ID number using setColour(), then it is
  24789. returned. If none has been set, the method will try calling the component's
  24790. LookAndFeel class's findColour() method. If none has been registered with the
  24791. look-and-feel either, it will just return black.
  24792. The colour IDs for various purposes are stored as enums in the components that
  24793. they are relevent to - for an example, see Slider::ColourIds,
  24794. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  24795. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24796. */
  24797. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  24798. /** Registers a colour to be used for a particular purpose.
  24799. Changing a colour will cause a synchronous callback to the colourChanged()
  24800. method, which your component can override if it needs to do something when
  24801. colours are altered.
  24802. For more details about colour IDs, see the comments for findColour().
  24803. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24804. */
  24805. void setColour (int colourId, const Colour& colour);
  24806. /** If a colour has been set with setColour(), this will remove it.
  24807. This allows you to make a colour revert to its default state.
  24808. */
  24809. void removeColour (int colourId);
  24810. /** Returns true if the specified colour ID has been explicitly set for this
  24811. component using the setColour() method.
  24812. */
  24813. bool isColourSpecified (int colourId) const;
  24814. /** This looks for any colours that have been specified for this component,
  24815. and copies them to the specified target component.
  24816. */
  24817. void copyAllExplicitColoursTo (Component& target) const;
  24818. /** This method is called when a colour is changed by the setColour() method.
  24819. @see setColour, findColour
  24820. */
  24821. virtual void colourChanged();
  24822. /** Components can implement this method to provide a MarkerList.
  24823. The default implementation of this method returns 0, but you can override it to
  24824. return a pointer to the component's marker list. If xAxis is true, it should
  24825. return the X marker list; if false, it should return the Y markers.
  24826. */
  24827. virtual MarkerList* getMarkers (bool xAxis);
  24828. /** Returns the underlying native window handle for this component.
  24829. This is platform-dependent and strictly for power-users only!
  24830. */
  24831. void* getWindowHandle() const;
  24832. /** Holds a pointer to some type of Component, which automatically becomes null if
  24833. the component is deleted.
  24834. If you're using a component which may be deleted by another event that's outside
  24835. of your control, use a SafePointer instead of a normal pointer to refer to it,
  24836. and you can test whether it's null before using it to see if something has deleted
  24837. it.
  24838. The ComponentType typedef must be Component, or some subclass of Component.
  24839. You may also want to use a WeakReference<Component> object for the same purpose.
  24840. */
  24841. template <class ComponentType>
  24842. class SafePointer
  24843. {
  24844. public:
  24845. /** Creates a null SafePointer. */
  24846. SafePointer() throw() {}
  24847. /** Creates a SafePointer that points at the given component. */
  24848. SafePointer (ComponentType* const component) : weakRef (component) {}
  24849. /** Creates a copy of another SafePointer. */
  24850. SafePointer (const SafePointer& other) throw() : weakRef (other.weakRef) {}
  24851. /** Copies another pointer to this one. */
  24852. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  24853. /** Copies another pointer to this one. */
  24854. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  24855. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24856. ComponentType* getComponent() const throw() { return dynamic_cast <ComponentType*> (weakRef.get()); }
  24857. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24858. operator ComponentType*() const throw() { return getComponent(); }
  24859. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24860. ComponentType* operator->() throw() { return getComponent(); }
  24861. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24862. const ComponentType* operator->() const throw() { return getComponent(); }
  24863. /** If the component is valid, this deletes it and sets this pointer to null. */
  24864. void deleteAndZero() { delete getComponent(); jassert (getComponent() == 0); }
  24865. bool operator== (ComponentType* component) const throw() { return weakRef == component; }
  24866. bool operator!= (ComponentType* component) const throw() { return weakRef != component; }
  24867. private:
  24868. WeakReference<Component> weakRef;
  24869. };
  24870. /** A class to keep an eye on a component and check for it being deleted.
  24871. This is designed for use with the ListenerList::callChecked() methods, to allow
  24872. the list iterator to stop cleanly if the component is deleted by a listener callback
  24873. while the list is still being iterated.
  24874. */
  24875. class JUCE_API BailOutChecker
  24876. {
  24877. public:
  24878. /** Creates a checker that watches one component. */
  24879. BailOutChecker (Component* component);
  24880. /** Returns true if either of the two components have been deleted since this object was created. */
  24881. bool shouldBailOut() const throw();
  24882. private:
  24883. const WeakReference<Component> safePointer;
  24884. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  24885. };
  24886. /**
  24887. Base class for objects that can be used to automatically position a component according to
  24888. some kind of algorithm.
  24889. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  24890. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  24891. it might choose to watch some kind of value and move the component when the value changes).
  24892. */
  24893. class JUCE_API Positioner
  24894. {
  24895. public:
  24896. /** Creates a Positioner which can control the specified component. */
  24897. explicit Positioner (Component& component) throw();
  24898. /** Destructor. */
  24899. virtual ~Positioner() {}
  24900. /** Returns the component that this positioner controls. */
  24901. Component& getComponent() const throw() { return component; }
  24902. /** Attempts to set the component's position to the given rectangle.
  24903. Unlike simply calling Component::setBounds(), this may involve the positioner
  24904. being smart enough to adjust itself to fit the new bounds, e.g. a RelativeRectangle's
  24905. positioner may try to reverse the expressions used to make them fit these new coordinates.
  24906. */
  24907. virtual void applyNewBounds (const Rectangle<int>& newBounds) = 0;
  24908. private:
  24909. Component& component;
  24910. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  24911. };
  24912. /** Returns the Positioner object that has been set for this component.
  24913. @see setPositioner()
  24914. */
  24915. Positioner* getPositioner() const throw();
  24916. /** Sets a new Positioner object for this component.
  24917. If there's currently another positioner set, it will be deleted. The object that is passed in
  24918. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  24919. to clear the current positioner.
  24920. @see getPositioner()
  24921. */
  24922. void setPositioner (Positioner* newPositioner);
  24923. #ifndef DOXYGEN
  24924. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  24925. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  24926. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  24927. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  24928. #endif
  24929. private:
  24930. friend class ComponentPeer;
  24931. friend class MouseInputSource;
  24932. friend class MouseInputSourceInternal;
  24933. #ifndef DOXYGEN
  24934. static Component* currentlyFocusedComponent;
  24935. String componentName, componentID;
  24936. Component* parentComponent;
  24937. Rectangle<int> bounds;
  24938. ScopedPointer <Positioner> positioner;
  24939. ScopedPointer <AffineTransform> affineTransform;
  24940. Array <Component*> childComponentList;
  24941. LookAndFeel* lookAndFeel;
  24942. MouseCursor cursor;
  24943. ImageEffectFilter* effect;
  24944. Image bufferedImage;
  24945. class MouseListenerList;
  24946. friend class MouseListenerList;
  24947. friend class ScopedPointer <MouseListenerList>;
  24948. ScopedPointer <MouseListenerList> mouseListeners;
  24949. ScopedPointer <Array <KeyListener*> > keyListeners;
  24950. ListenerList <ComponentListener> componentListeners;
  24951. NamedValueSet properties;
  24952. friend class WeakReference<Component>;
  24953. WeakReference<Component>::Master weakReferenceMaster;
  24954. const WeakReference<Component>::SharedRef& getWeakReference();
  24955. struct ComponentFlags
  24956. {
  24957. bool hasHeavyweightPeerFlag : 1;
  24958. bool visibleFlag : 1;
  24959. bool opaqueFlag : 1;
  24960. bool ignoresMouseClicksFlag : 1;
  24961. bool allowChildMouseClicksFlag : 1;
  24962. bool wantsFocusFlag : 1;
  24963. bool isFocusContainerFlag : 1;
  24964. bool dontFocusOnMouseClickFlag : 1;
  24965. bool alwaysOnTopFlag : 1;
  24966. bool bufferToImageFlag : 1;
  24967. bool bringToFrontOnClickFlag : 1;
  24968. bool repaintOnMouseActivityFlag : 1;
  24969. bool mouseDownFlag : 1;
  24970. bool mouseOverFlag : 1;
  24971. bool mouseInsideFlag : 1;
  24972. bool currentlyModalFlag : 1;
  24973. bool isDisabledFlag : 1;
  24974. bool childCompFocusedFlag : 1;
  24975. bool dontClipGraphicsFlag : 1;
  24976. #if JUCE_DEBUG
  24977. bool isInsidePaintCall : 1;
  24978. #endif
  24979. };
  24980. union
  24981. {
  24982. uint32 componentFlags;
  24983. ComponentFlags flags;
  24984. };
  24985. uint8 componentTransparency;
  24986. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24987. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24988. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24989. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  24990. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24991. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24992. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  24993. void internalBroughtToFront();
  24994. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  24995. void internalFocusGain (const FocusChangeType cause);
  24996. void internalFocusLoss (const FocusChangeType cause);
  24997. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  24998. void internalModalInputAttempt();
  24999. void internalModifierKeysChanged();
  25000. void internalChildrenChanged();
  25001. void internalHierarchyChanged();
  25002. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  25003. void moveChildInternal (int sourceIndex, int destIndex);
  25004. void paintComponentAndChildren (Graphics& g);
  25005. void paintComponent (Graphics& g);
  25006. void paintWithinParentContext (Graphics& g);
  25007. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  25008. void repaintParent();
  25009. void sendFakeMouseMove() const;
  25010. void takeKeyboardFocus (const FocusChangeType cause);
  25011. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  25012. static void giveAwayFocus (bool sendFocusLossEvent);
  25013. void sendEnablementChangeMessage();
  25014. void sendVisibilityChangeMessage();
  25015. class ComponentHelpers;
  25016. friend class ComponentHelpers;
  25017. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  25018. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  25019. */
  25020. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  25021. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25022. // This is included here just to cause a compile error if your code is still handling
  25023. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  25024. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  25025. // implement its methods instead of this Component method).
  25026. virtual void filesDropped (const StringArray&, int, int) {}
  25027. // This is included here to cause an error if you use or overload it - it has been deprecated in
  25028. // favour of contains (const Point<int>&)
  25029. void contains (int, int);
  25030. #endif
  25031. protected:
  25032. /** @internal */
  25033. virtual void internalRepaint (int x, int y, int w, int h);
  25034. /** @internal */
  25035. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  25036. #endif
  25037. };
  25038. #endif // __JUCE_COMPONENT_JUCEHEADER__
  25039. /*** End of inlined file: juce_Component.h ***/
  25040. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  25041. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25042. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25043. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  25044. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25045. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25046. /** A type used to hold the unique ID for an application command.
  25047. This is a numeric type, so it can be stored as an integer.
  25048. @see ApplicationCommandInfo, ApplicationCommandManager,
  25049. ApplicationCommandTarget, KeyPressMappingSet
  25050. */
  25051. typedef int CommandID;
  25052. /** A set of general-purpose application command IDs.
  25053. Because these commands are likely to be used in most apps, they're defined
  25054. here to help different apps to use the same numeric values for them.
  25055. Of course you don't have to use these, but some of them are used internally by
  25056. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  25057. @see ApplicationCommandInfo, ApplicationCommandManager,
  25058. ApplicationCommandTarget, KeyPressMappingSet
  25059. */
  25060. namespace StandardApplicationCommandIDs
  25061. {
  25062. /** This command ID should be used to send a "Quit the App" command.
  25063. This command is recognised by the JUCEApplication class, so if it is invoked
  25064. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  25065. object will catch it and call JUCEApplication::systemRequestedQuit().
  25066. */
  25067. static const CommandID quit = 0x1001;
  25068. /** The command ID that should be used to send a "Delete" command. */
  25069. static const CommandID del = 0x1002;
  25070. /** The command ID that should be used to send a "Cut" command. */
  25071. static const CommandID cut = 0x1003;
  25072. /** The command ID that should be used to send a "Copy to clipboard" command. */
  25073. static const CommandID copy = 0x1004;
  25074. /** The command ID that should be used to send a "Paste from clipboard" command. */
  25075. static const CommandID paste = 0x1005;
  25076. /** The command ID that should be used to send a "Select all" command. */
  25077. static const CommandID selectAll = 0x1006;
  25078. /** The command ID that should be used to send a "Deselect all" command. */
  25079. static const CommandID deselectAll = 0x1007;
  25080. }
  25081. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25082. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  25083. /**
  25084. Holds information describing an application command.
  25085. This object is used to pass information about a particular command, such as its
  25086. name, description and other usage flags.
  25087. When an ApplicationCommandTarget is asked to provide information about the commands
  25088. it can perform, this is the structure gets filled-in to describe each one.
  25089. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  25090. ApplicationCommandManager
  25091. */
  25092. struct JUCE_API ApplicationCommandInfo
  25093. {
  25094. explicit ApplicationCommandInfo (CommandID commandID) throw();
  25095. /** Sets a number of the structures values at once.
  25096. The meanings of each of the parameters is described below, in the appropriate
  25097. member variable's description.
  25098. */
  25099. void setInfo (const String& shortName,
  25100. const String& description,
  25101. const String& categoryName,
  25102. int flags) throw();
  25103. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  25104. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  25105. is false, the bit is set.
  25106. */
  25107. void setActive (bool isActive) throw();
  25108. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  25109. */
  25110. void setTicked (bool isTicked) throw();
  25111. /** Handy method for adding a keypress to the defaultKeypresses array.
  25112. This is just so you can write things like:
  25113. @code
  25114. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  25115. @endcode
  25116. instead of
  25117. @code
  25118. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  25119. @endcode
  25120. */
  25121. void addDefaultKeypress (int keyCode,
  25122. const ModifierKeys& modifiers) throw();
  25123. /** The command's unique ID number.
  25124. */
  25125. CommandID commandID;
  25126. /** A short name to describe the command.
  25127. This should be suitable for use in menus, on buttons that trigger the command, etc.
  25128. You can use the setInfo() method to quickly set this and some of the command's
  25129. other properties.
  25130. */
  25131. String shortName;
  25132. /** A longer description of the command.
  25133. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  25134. pop-up tooltip describing what the command does.
  25135. You can use the setInfo() method to quickly set this and some of the command's
  25136. other properties.
  25137. */
  25138. String description;
  25139. /** A named category that the command fits into.
  25140. You can give your commands any category you like, and these will be displayed in
  25141. contexts such as the KeyMappingEditorComponent, where the category is used to group
  25142. commands together.
  25143. You can use the setInfo() method to quickly set this and some of the command's
  25144. other properties.
  25145. */
  25146. String categoryName;
  25147. /** A list of zero or more keypresses that should be used as the default keys for
  25148. this command.
  25149. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  25150. this list to initialise the default set of key-to-command mappings.
  25151. @see addDefaultKeypress
  25152. */
  25153. Array <KeyPress> defaultKeypresses;
  25154. /** Flags describing the ways in which this command should be used.
  25155. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  25156. variable.
  25157. */
  25158. enum CommandFlags
  25159. {
  25160. /** Indicates that the command can't currently be performed.
  25161. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  25162. not currently permissable to perform the command. If the flag is set, then
  25163. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  25164. command or show themselves as not being enabled.
  25165. @see ApplicationCommandInfo::setActive
  25166. */
  25167. isDisabled = 1 << 0,
  25168. /** Indicates that the command should have a tick next to it on a menu.
  25169. If your command is shown on a menu and this is set, it'll show a tick next to
  25170. it. Other components such as buttons may also use this flag to indicate that it
  25171. is a value that can be toggled, and is currently in the 'on' state.
  25172. @see ApplicationCommandInfo::setTicked
  25173. */
  25174. isTicked = 1 << 1,
  25175. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  25176. it will call the command twice, once on key-down and again on key-up.
  25177. @see ApplicationCommandTarget::InvocationInfo
  25178. */
  25179. wantsKeyUpDownCallbacks = 1 << 2,
  25180. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  25181. command in its list.
  25182. */
  25183. hiddenFromKeyEditor = 1 << 3,
  25184. /** If this flag is present, then a KeyMappingEditorComponent will display the
  25185. command in its list, but won't allow the assigned keypress to be changed.
  25186. */
  25187. readOnlyInKeyEditor = 1 << 4,
  25188. /** If this flag is present and the command is invoked from a keypress, then any
  25189. buttons or menus that are also connected to the command will not flash to
  25190. indicate that they've been triggered.
  25191. */
  25192. dontTriggerVisualFeedback = 1 << 5
  25193. };
  25194. /** A bitwise-OR of the values specified in the CommandFlags enum.
  25195. You can use the setInfo() method to quickly set this and some of the command's
  25196. other properties.
  25197. */
  25198. int flags;
  25199. };
  25200. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25201. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  25202. /*** Start of inlined file: juce_MessageListener.h ***/
  25203. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  25204. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  25205. /**
  25206. MessageListener subclasses can post and receive Message objects.
  25207. @see Message, MessageManager, ActionListener, ChangeListener
  25208. */
  25209. class JUCE_API MessageListener
  25210. {
  25211. protected:
  25212. /** Creates a MessageListener. */
  25213. MessageListener() throw();
  25214. public:
  25215. /** Destructor.
  25216. When a MessageListener is deleted, it removes itself from a global list
  25217. of registered listeners, so that the isValidMessageListener() method
  25218. will no longer return true.
  25219. */
  25220. virtual ~MessageListener();
  25221. /** This is the callback method that receives incoming messages.
  25222. This is called by the MessageManager from its dispatch loop.
  25223. @see postMessage
  25224. */
  25225. virtual void handleMessage (const Message& message) = 0;
  25226. /** Sends a message to the message queue, for asynchronous delivery to this listener
  25227. later on.
  25228. This method can be called safely by any thread.
  25229. @param message the message object to send - this will be deleted
  25230. automatically by the message queue, so don't keep any
  25231. references to it after calling this method.
  25232. @see handleMessage
  25233. */
  25234. void postMessage (Message* message) const throw();
  25235. /** Checks whether this MessageListener has been deleted.
  25236. Although not foolproof, this method is safe to call on dangling or null
  25237. pointers. A list of active MessageListeners is kept internally, so this
  25238. checks whether the object is on this list or not.
  25239. Note that it's possible to get a false-positive here, if an object is
  25240. deleted and another is subsequently created that happens to be at the
  25241. exact same memory location, but I can't think of a good way of avoiding
  25242. this.
  25243. */
  25244. bool isValidMessageListener() const throw();
  25245. };
  25246. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  25247. /*** End of inlined file: juce_MessageListener.h ***/
  25248. /**
  25249. A command target publishes a list of command IDs that it can perform.
  25250. An ApplicationCommandManager despatches commands to targets, which must be
  25251. able to provide information about what commands they can handle.
  25252. To create a target, you'll need to inherit from this class, implementing all of
  25253. its pure virtual methods.
  25254. For info about how a target is chosen to receive a command, see
  25255. ApplicationCommandManager::getFirstCommandTarget().
  25256. @see ApplicationCommandManager, ApplicationCommandInfo
  25257. */
  25258. class JUCE_API ApplicationCommandTarget
  25259. {
  25260. public:
  25261. /** Creates a command target. */
  25262. ApplicationCommandTarget();
  25263. /** Destructor. */
  25264. virtual ~ApplicationCommandTarget();
  25265. /**
  25266. */
  25267. struct JUCE_API InvocationInfo
  25268. {
  25269. InvocationInfo (const CommandID commandID);
  25270. /** The UID of the command that should be performed. */
  25271. CommandID commandID;
  25272. /** The command's flags.
  25273. See ApplicationCommandInfo for a description of these flag values.
  25274. */
  25275. int commandFlags;
  25276. /** The types of context in which the command might be called. */
  25277. enum InvocationMethod
  25278. {
  25279. direct = 0, /**< The command is being invoked directly by a piece of code. */
  25280. fromKeyPress, /**< The command is being invoked by a key-press. */
  25281. fromMenu, /**< The command is being invoked by a menu selection. */
  25282. fromButton /**< The command is being invoked by a button click. */
  25283. };
  25284. /** The type of event that triggered this command. */
  25285. InvocationMethod invocationMethod;
  25286. /** If triggered by a keypress or menu, this will be the component that had the
  25287. keyboard focus at the time.
  25288. If triggered by a button, it may be set to that component, or it may be null.
  25289. */
  25290. Component* originatingComponent;
  25291. /** The keypress that was used to invoke it.
  25292. Note that this will be an invalid keypress if the command was invoked
  25293. by some other means than a keyboard shortcut.
  25294. */
  25295. KeyPress keyPress;
  25296. /** True if the callback is being invoked when the key is pressed,
  25297. false if the key is being released.
  25298. @see KeyPressMappingSet::addCommand()
  25299. */
  25300. bool isKeyDown;
  25301. /** If the key is being released, this indicates how long it had been held
  25302. down for.
  25303. (Only relevant if isKeyDown is false.)
  25304. */
  25305. int millisecsSinceKeyPressed;
  25306. };
  25307. /** This must return the next target to try after this one.
  25308. When a command is being sent, and the first target can't handle
  25309. that command, this method is used to determine the next target that should
  25310. be tried.
  25311. It may return 0 if it doesn't know of another target.
  25312. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  25313. method to return a parent component that might want to handle it.
  25314. @see invoke
  25315. */
  25316. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  25317. /** This must return a complete list of commands that this target can handle.
  25318. Your target should add all the command IDs that it handles to the array that is
  25319. passed-in.
  25320. */
  25321. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  25322. /** This must provide details about one of the commands that this target can perform.
  25323. This will be called with one of the command IDs that the target provided in its
  25324. getAllCommands() methods.
  25325. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  25326. suitable information about the command. (The commandID field will already have been filled-in
  25327. by the caller).
  25328. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  25329. set all the fields at once.
  25330. If the command is currently inactive for some reason, this method must use
  25331. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  25332. bit of the ApplicationCommandInfo::flags field).
  25333. Any default key-presses for the command should be appended to the
  25334. ApplicationCommandInfo::defaultKeypresses field.
  25335. Note that if you change something that affects the status of the commands
  25336. that would be returned by this method (e.g. something that makes some commands
  25337. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  25338. to cause the manager to refresh its status.
  25339. */
  25340. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  25341. /** This must actually perform the specified command.
  25342. If this target is able to perform the command specified by the commandID field of the
  25343. InvocationInfo structure, then it should do so, and must return true.
  25344. If it can't handle this command, it should return false, which tells the caller to pass
  25345. the command on to the next target in line.
  25346. @see invoke, ApplicationCommandManager::invoke
  25347. */
  25348. virtual bool perform (const InvocationInfo& info) = 0;
  25349. /** Makes this target invoke a command.
  25350. Your code can call this method to invoke a command on this target, but normally
  25351. you'd call it indirectly via ApplicationCommandManager::invoke() or
  25352. ApplicationCommandManager::invokeDirectly().
  25353. If this target can perform the given command, it will call its perform() method to
  25354. do so. If not, then getNextCommandTarget() will be used to determine the next target
  25355. to try, and the command will be passed along to it.
  25356. @param invocationInfo this must be correctly filled-in, describing the context for
  25357. the invocation.
  25358. @param asynchronously if false, the command will be performed before this method returns.
  25359. If true, a message will be posted so that the command will be performed
  25360. later on the message thread, and this method will return immediately.
  25361. @see perform, ApplicationCommandManager::invoke
  25362. */
  25363. bool invoke (const InvocationInfo& invocationInfo,
  25364. const bool asynchronously);
  25365. /** Invokes a given command directly on this target.
  25366. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25367. structure.
  25368. */
  25369. bool invokeDirectly (const CommandID commandID,
  25370. const bool asynchronously);
  25371. /** Searches this target and all subsequent ones for the first one that can handle
  25372. the specified command.
  25373. This will use getNextCommandTarget() to determine the chain of targets to try
  25374. after this one.
  25375. */
  25376. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  25377. /** Checks whether this command can currently be performed by this target.
  25378. This will return true only if a call to getCommandInfo() doesn't set the
  25379. isDisabled flag to indicate that the command is inactive.
  25380. */
  25381. bool isCommandActive (const CommandID commandID);
  25382. /** If this object is a Component, this method will seach upwards in its current
  25383. UI hierarchy for the next parent component that implements the
  25384. ApplicationCommandTarget class.
  25385. If your target is a Component, this is a very handy method to use in your
  25386. getNextCommandTarget() implementation.
  25387. */
  25388. ApplicationCommandTarget* findFirstTargetParentComponent();
  25389. private:
  25390. // (for async invocation of commands)
  25391. class CommandTargetMessageInvoker : public MessageListener
  25392. {
  25393. public:
  25394. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  25395. ~CommandTargetMessageInvoker();
  25396. void handleMessage (const Message& message);
  25397. private:
  25398. ApplicationCommandTarget* const owner;
  25399. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  25400. };
  25401. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  25402. friend class CommandTargetMessageInvoker;
  25403. bool tryToInvoke (const InvocationInfo& info, bool async);
  25404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  25405. };
  25406. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25407. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  25408. /*** Start of inlined file: juce_ActionListener.h ***/
  25409. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  25410. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  25411. /**
  25412. Receives callbacks to indicate that some kind of event has occurred.
  25413. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  25414. about something that's happened.
  25415. @see ActionBroadcaster, ChangeListener
  25416. */
  25417. class JUCE_API ActionListener
  25418. {
  25419. public:
  25420. /** Destructor. */
  25421. virtual ~ActionListener() {}
  25422. /** Overridden by your subclass to receive the callback.
  25423. @param message the string that was specified when the event was triggered
  25424. by a call to ActionBroadcaster::sendActionMessage()
  25425. */
  25426. virtual void actionListenerCallback (const String& message) = 0;
  25427. };
  25428. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  25429. /*** End of inlined file: juce_ActionListener.h ***/
  25430. /**
  25431. An instance of this class is used to specify initialisation and shutdown
  25432. code for the application.
  25433. An application that wants to run in the JUCE framework needs to declare a
  25434. subclass of JUCEApplication and implement its various pure virtual methods.
  25435. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  25436. to declare an instance of this class and generate a suitable platform-specific
  25437. main() function.
  25438. e.g. @code
  25439. class MyJUCEApp : public JUCEApplication
  25440. {
  25441. public:
  25442. MyJUCEApp()
  25443. {
  25444. }
  25445. ~MyJUCEApp()
  25446. {
  25447. }
  25448. void initialise (const String& commandLine)
  25449. {
  25450. myMainWindow = new MyApplicationWindow();
  25451. myMainWindow->setBounds (100, 100, 400, 500);
  25452. myMainWindow->setVisible (true);
  25453. }
  25454. void shutdown()
  25455. {
  25456. myMainWindow = 0;
  25457. }
  25458. const String getApplicationName()
  25459. {
  25460. return "Super JUCE-o-matic";
  25461. }
  25462. const String getApplicationVersion()
  25463. {
  25464. return "1.0";
  25465. }
  25466. private:
  25467. ScopedPointer <MyApplicationWindow> myMainWindow;
  25468. };
  25469. // this creates wrapper code to actually launch the app properly.
  25470. START_JUCE_APPLICATION (MyJUCEApp)
  25471. @endcode
  25472. @see MessageManager, DeletedAtShutdown
  25473. */
  25474. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  25475. private ActionListener
  25476. {
  25477. protected:
  25478. /** Constructs a JUCE app object.
  25479. If subclasses implement a constructor or destructor, they shouldn't call any
  25480. JUCE code in there - put your startup/shutdown code in initialise() and
  25481. shutdown() instead.
  25482. */
  25483. JUCEApplication();
  25484. public:
  25485. /** Destructor.
  25486. If subclasses implement a constructor or destructor, they shouldn't call any
  25487. JUCE code in there - put your startup/shutdown code in initialise() and
  25488. shutdown() instead.
  25489. */
  25490. virtual ~JUCEApplication();
  25491. /** Returns the global instance of the application object being run. */
  25492. static JUCEApplication* getInstance() throw() { return appInstance; }
  25493. /** Called when the application starts.
  25494. This will be called once to let the application do whatever initialisation
  25495. it needs, create its windows, etc.
  25496. After the method returns, the normal event-dispatch loop will be run,
  25497. until the quit() method is called, at which point the shutdown()
  25498. method will be called to let the application clear up anything it needs
  25499. to delete.
  25500. If during the initialise() method, the application decides not to start-up
  25501. after all, it can just call the quit() method and the event loop won't be run.
  25502. @param commandLineParameters the line passed in does not include the
  25503. name of the executable, just the parameter list.
  25504. @see shutdown, quit
  25505. */
  25506. virtual void initialise (const String& commandLineParameters) = 0;
  25507. /** Returns true if the application hasn't yet completed its initialise() method
  25508. and entered the main event loop.
  25509. This is handy for things like splash screens to know when the app's up-and-running
  25510. properly.
  25511. */
  25512. bool isInitialising() const throw() { return stillInitialising; }
  25513. /* Called to allow the application to clear up before exiting.
  25514. After JUCEApplication::quit() has been called, the event-dispatch loop will
  25515. terminate, and this method will get called to allow the app to sort itself
  25516. out.
  25517. Be careful that nothing happens in this method that might rely on messages
  25518. being sent, or any kind of window activity, because the message loop is no
  25519. longer running at this point.
  25520. @see DeletedAtShutdown
  25521. */
  25522. virtual void shutdown() = 0;
  25523. /** Returns the application's name.
  25524. An application must implement this to name itself.
  25525. */
  25526. virtual const String getApplicationName() = 0;
  25527. /** Returns the application's version number.
  25528. */
  25529. virtual const String getApplicationVersion() = 0;
  25530. /** Checks whether multiple instances of the app are allowed.
  25531. If you application class returns true for this, more than one instance is
  25532. permitted to run (except on the Mac where this isn't possible).
  25533. If it's false, the second instance won't start, but it you will still get a
  25534. callback to anotherInstanceStarted() to tell you about this - which
  25535. gives you a chance to react to what the user was trying to do.
  25536. */
  25537. virtual bool moreThanOneInstanceAllowed();
  25538. /** Indicates that the user has tried to start up another instance of the app.
  25539. This will get called even if moreThanOneInstanceAllowed() is false.
  25540. */
  25541. virtual void anotherInstanceStarted (const String& commandLine);
  25542. /** Called when the operating system is trying to close the application.
  25543. The default implementation of this method is to call quit(), but it may
  25544. be overloaded to ignore the request or do some other special behaviour
  25545. instead. For example, you might want to offer the user the chance to save
  25546. their changes before quitting, and give them the chance to cancel.
  25547. If you want to send a quit signal to your app, this is the correct method
  25548. to call, because it means that requests that come from the system get handled
  25549. in the same way as those from your own application code. So e.g. you'd
  25550. call this method from a "quit" item on a menu bar.
  25551. */
  25552. virtual void systemRequestedQuit();
  25553. /** If any unhandled exceptions make it through to the message dispatch loop, this
  25554. callback will be triggered, in case you want to log them or do some other
  25555. type of error-handling.
  25556. If the type of exception is derived from the std::exception class, the pointer
  25557. passed-in will be valid. If the exception is of unknown type, this pointer
  25558. will be null.
  25559. */
  25560. virtual void unhandledException (const std::exception* e,
  25561. const String& sourceFilename,
  25562. int lineNumber);
  25563. /** Signals that the main message loop should stop and the application should terminate.
  25564. This isn't synchronous, it just posts a quit message to the main queue, and
  25565. when this message arrives, the message loop will stop, the shutdown() method
  25566. will be called, and the app will exit.
  25567. Note that this will cause an unconditional quit to happen, so if you need an
  25568. extra level before this, e.g. to give the user the chance to save their work
  25569. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  25570. method - see that method's help for more info.
  25571. @see MessageManager, DeletedAtShutdown
  25572. */
  25573. static void quit();
  25574. /** Sets the value that should be returned as the application's exit code when the
  25575. app quits.
  25576. This is the value that's returned by the main() function. Normally you'd leave this
  25577. as 0 unless you want to indicate an error code.
  25578. @see getApplicationReturnValue
  25579. */
  25580. void setApplicationReturnValue (int newReturnValue) throw();
  25581. /** Returns the value that has been set as the application's exit code.
  25582. @see setApplicationReturnValue
  25583. */
  25584. int getApplicationReturnValue() const throw() { return appReturnValue; }
  25585. /** Returns the application's command line params.
  25586. */
  25587. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  25588. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  25589. /** @internal */
  25590. static int main (const String& commandLine);
  25591. /** @internal */
  25592. static int main (int argc, const char* argv[]);
  25593. /** @internal */
  25594. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  25595. /** Returns true if this executable is running as an app (as opposed to being a plugin
  25596. or other kind of shared library. */
  25597. static inline bool isStandaloneApp() throw() { return createInstance != 0; }
  25598. /** @internal */
  25599. ApplicationCommandTarget* getNextCommandTarget();
  25600. /** @internal */
  25601. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  25602. /** @internal */
  25603. void getAllCommands (Array <CommandID>& commands);
  25604. /** @internal */
  25605. bool perform (const InvocationInfo& info);
  25606. /** @internal */
  25607. void actionListenerCallback (const String& message);
  25608. /** @internal */
  25609. bool initialiseApp (const String& commandLine);
  25610. /** @internal */
  25611. int shutdownApp();
  25612. /** @internal */
  25613. static void appWillTerminateByForce();
  25614. /** @internal */
  25615. typedef JUCEApplication* (*CreateInstanceFunction)();
  25616. /** @internal */
  25617. static CreateInstanceFunction createInstance;
  25618. private:
  25619. String commandLineParameters;
  25620. int appReturnValue;
  25621. bool stillInitialising;
  25622. ScopedPointer<InterProcessLock> appLock;
  25623. static JUCEApplication* appInstance;
  25624. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  25625. };
  25626. #endif // __JUCE_APPLICATION_JUCEHEADER__
  25627. /*** End of inlined file: juce_Application.h ***/
  25628. #endif
  25629. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25630. #endif
  25631. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25632. #endif
  25633. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25634. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  25635. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25636. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25637. /*** Start of inlined file: juce_Desktop.h ***/
  25638. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  25639. #define __JUCE_DESKTOP_JUCEHEADER__
  25640. /*** Start of inlined file: juce_Timer.h ***/
  25641. #ifndef __JUCE_TIMER_JUCEHEADER__
  25642. #define __JUCE_TIMER_JUCEHEADER__
  25643. class InternalTimerThread;
  25644. /**
  25645. Makes repeated callbacks to a virtual method at a specified time interval.
  25646. A Timer's timerCallback() method will be repeatedly called at a given
  25647. interval. When you create a Timer object, it will do nothing until the
  25648. startTimer() method is called, which will cause the message thread to
  25649. start making callbacks at the specified interval, until stopTimer() is called
  25650. or the object is deleted.
  25651. The time interval isn't guaranteed to be precise to any more than maybe
  25652. 10-20ms, and the intervals may end up being much longer than requested if the
  25653. system is busy. Because the callbacks are made by the main message thread,
  25654. anything that blocks the message queue for a period of time will also prevent
  25655. any timers from running until it can carry on.
  25656. If you need to have a single callback that is shared by multiple timers with
  25657. different frequencies, then the MultiTimer class allows you to do that - its
  25658. structure is very similar to the Timer class, but contains multiple timers
  25659. internally, each one identified by an ID number.
  25660. @see MultiTimer
  25661. */
  25662. class JUCE_API Timer
  25663. {
  25664. protected:
  25665. /** Creates a Timer.
  25666. When created, the timer is stopped, so use startTimer() to get it going.
  25667. */
  25668. Timer() throw();
  25669. /** Creates a copy of another timer.
  25670. Note that this timer won't be started, even if the one you're copying
  25671. is running.
  25672. */
  25673. Timer (const Timer& other) throw();
  25674. public:
  25675. /** Destructor. */
  25676. virtual ~Timer();
  25677. /** The user-defined callback routine that actually gets called periodically.
  25678. It's perfectly ok to call startTimer() or stopTimer() from within this
  25679. callback to change the subsequent intervals.
  25680. */
  25681. virtual void timerCallback() = 0;
  25682. /** Starts the timer and sets the length of interval required.
  25683. If the timer is already started, this will reset it, so the
  25684. time between calling this method and the next timer callback
  25685. will not be less than the interval length passed in.
  25686. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  25687. rounded up to 1)
  25688. */
  25689. void startTimer (int intervalInMilliseconds) throw();
  25690. /** Stops the timer.
  25691. No more callbacks will be made after this method returns.
  25692. If this is called from a different thread, any callbacks that may
  25693. be currently executing may be allowed to finish before the method
  25694. returns.
  25695. */
  25696. void stopTimer() throw();
  25697. /** Checks if the timer has been started.
  25698. @returns true if the timer is running.
  25699. */
  25700. bool isTimerRunning() const throw() { return periodMs > 0; }
  25701. /** Returns the timer's interval.
  25702. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  25703. */
  25704. int getTimerInterval() const throw() { return periodMs; }
  25705. private:
  25706. friend class InternalTimerThread;
  25707. int countdownMs, periodMs;
  25708. Timer* previous;
  25709. Timer* next;
  25710. Timer& operator= (const Timer&);
  25711. };
  25712. #endif // __JUCE_TIMER_JUCEHEADER__
  25713. /*** End of inlined file: juce_Timer.h ***/
  25714. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  25715. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25716. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25717. /**
  25718. Animates a set of components, moving them to a new position and/or fading their
  25719. alpha levels.
  25720. To animate a component, create a ComponentAnimator instance or (preferably) use the
  25721. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  25722. method to commence the movement.
  25723. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  25724. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  25725. destinations.
  25726. It's ok to delete components while they're being animated - the animator will detect this
  25727. and safely stop using them.
  25728. The class is a ChangeBroadcaster and sends a notification when any components
  25729. start or finish being animated.
  25730. @see Desktop::getAnimator
  25731. */
  25732. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  25733. private Timer
  25734. {
  25735. public:
  25736. /** Creates a ComponentAnimator. */
  25737. ComponentAnimator();
  25738. /** Destructor. */
  25739. ~ComponentAnimator();
  25740. /** Starts a component moving from its current position to a specified position.
  25741. If the component is already in the middle of an animation, that will be abandoned,
  25742. and a new animation will begin, moving the component from its current location.
  25743. The start and end speed parameters let you apply some acceleration to the component's
  25744. movement.
  25745. @param component the component to move
  25746. @param finalBounds the destination bounds to which the component should move. To leave the
  25747. component in the same place, just pass component->getBounds() for this value
  25748. @param finalAlpha the alpha value that the component should have at the end of the animation
  25749. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  25750. @param useProxyComponent if true, this means the component should be replaced by an internally
  25751. managed temporary component which is a snapshot of the original component.
  25752. This avoids the component having to paint itself as it moves, so may
  25753. be more efficient. This option also allows you to delete the original
  25754. component immediately after starting the animation, because the animation
  25755. can proceed without it. If you use a proxy, the original component will be
  25756. made invisible by this call, and then will become visible again at the end
  25757. of the animation. It'll also mean that the proxy component will be temporarily
  25758. added to the component's parent, so avoid it if this might confuse the parent
  25759. component, or if there's a chance the parent might decide to delete its children.
  25760. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  25761. the component will start by accelerating from rest; higher values mean that it
  25762. will have an initial speed greater than zero. If the value if greater than 1, it
  25763. will decelerate towards the middle of its journey. To move the component at a
  25764. constant rate for its entire animation, set both the start and end speeds to 1.0
  25765. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  25766. If this is 0, the component will decelerate to a standstill at its final position;
  25767. higher values mean the component will still be moving when it stops. To move the component
  25768. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  25769. */
  25770. void animateComponent (Component* component,
  25771. const Rectangle<int>& finalBounds,
  25772. float finalAlpha,
  25773. int animationDurationMilliseconds,
  25774. bool useProxyComponent,
  25775. double startSpeed,
  25776. double endSpeed);
  25777. /** Begins a fade-out of this components alpha level.
  25778. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  25779. a proxy. You're safe to delete the component after calling this method, and this won't
  25780. interfere with the animation's progress.
  25781. */
  25782. void fadeOut (Component* component, int millisecondsToTake);
  25783. /** Begins a fade-in of a component.
  25784. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  25785. */
  25786. void fadeIn (Component* component, int millisecondsToTake);
  25787. /** Stops a component if it's currently being animated.
  25788. If moveComponentToItsFinalPosition is true, then the component will
  25789. be immediately moved to its destination position and size. If false, it will be
  25790. left in whatever location it currently occupies.
  25791. */
  25792. void cancelAnimation (Component* component,
  25793. bool moveComponentToItsFinalPosition);
  25794. /** Clears all of the active animations.
  25795. If moveComponentsToTheirFinalPositions is true, all the components will
  25796. be immediately set to their final positions. If false, they will be
  25797. left in whatever locations they currently occupy.
  25798. */
  25799. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  25800. /** Returns the destination position for a component.
  25801. If the component is being animated, this will return the target position that
  25802. was specified when animateComponent() was called.
  25803. If the specified component isn't currently being animated, this method will just
  25804. return its current position.
  25805. */
  25806. const Rectangle<int> getComponentDestination (Component* component);
  25807. /** Returns true if the specified component is currently being animated. */
  25808. bool isAnimating (Component* component) const;
  25809. private:
  25810. class AnimationTask;
  25811. OwnedArray <AnimationTask> tasks;
  25812. uint32 lastTime;
  25813. AnimationTask* findTaskFor (Component* component) const;
  25814. void timerCallback();
  25815. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  25816. };
  25817. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25818. /*** End of inlined file: juce_ComponentAnimator.h ***/
  25819. class MouseInputSource;
  25820. class MouseInputSourceInternal;
  25821. class MouseListener;
  25822. /**
  25823. Classes can implement this interface and register themselves with the Desktop class
  25824. to receive callbacks when the currently focused component changes.
  25825. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  25826. */
  25827. class JUCE_API FocusChangeListener
  25828. {
  25829. public:
  25830. /** Destructor. */
  25831. virtual ~FocusChangeListener() {}
  25832. /** Callback to indicate that the currently focused component has changed. */
  25833. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  25834. };
  25835. /**
  25836. Describes and controls aspects of the computer's desktop.
  25837. */
  25838. class JUCE_API Desktop : private DeletedAtShutdown,
  25839. private Timer,
  25840. private AsyncUpdater
  25841. {
  25842. public:
  25843. /** There's only one dektop object, and this method will return it.
  25844. */
  25845. static Desktop& JUCE_CALLTYPE getInstance();
  25846. /** Returns a list of the positions of all the monitors available.
  25847. The first rectangle in the list will be the main monitor area.
  25848. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25849. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25850. */
  25851. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  25852. /** Returns the position and size of the main monitor.
  25853. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25854. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25855. */
  25856. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  25857. /** Returns the position and size of the monitor which contains this co-ordinate.
  25858. If none of the monitors contains the point, this will just return the
  25859. main monitor.
  25860. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25861. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25862. */
  25863. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  25864. /** Returns the mouse position.
  25865. The co-ordinates are relative to the top-left of the main monitor.
  25866. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  25867. you should only resort to grabbing the global mouse position if there's really no
  25868. way to get the coordinates via a mouse event callback instead.
  25869. */
  25870. static const Point<int> getMousePosition();
  25871. /** Makes the mouse pointer jump to a given location.
  25872. The co-ordinates are relative to the top-left of the main monitor.
  25873. */
  25874. static void setMousePosition (const Point<int>& newPosition);
  25875. /** Returns the last position at which a mouse button was pressed.
  25876. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  25877. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  25878. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  25879. if possible, and only ever call this as a last resort.
  25880. */
  25881. static const Point<int> getLastMouseDownPosition();
  25882. /** Returns the number of times the mouse button has been clicked since the
  25883. app started.
  25884. Each mouse-down event increments this number by 1.
  25885. */
  25886. static int getMouseButtonClickCounter();
  25887. /** This lets you prevent the screensaver from becoming active.
  25888. Handy if you're running some sort of presentation app where having a screensaver
  25889. appear would be annoying.
  25890. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  25891. won't enable a screensaver unless the user has actually set one up).
  25892. The disablement will only happen while the Juce application is the foreground
  25893. process - if another task is running in front of it, then the screensaver will
  25894. be unaffected.
  25895. @see isScreenSaverEnabled
  25896. */
  25897. static void setScreenSaverEnabled (bool isEnabled);
  25898. /** Returns true if the screensaver has not been turned off.
  25899. This will return the last value passed into setScreenSaverEnabled(). Note that
  25900. it won't tell you whether the user is actually using a screen saver, just
  25901. whether this app is deliberately preventing one from running.
  25902. @see setScreenSaverEnabled
  25903. */
  25904. static bool isScreenSaverEnabled();
  25905. /** Registers a MouseListener that will receive all mouse events that occur on
  25906. any component.
  25907. @see removeGlobalMouseListener
  25908. */
  25909. void addGlobalMouseListener (MouseListener* listener);
  25910. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  25911. method.
  25912. @see addGlobalMouseListener
  25913. */
  25914. void removeGlobalMouseListener (MouseListener* listener);
  25915. /** Registers a MouseListener that will receive a callback whenever the focused
  25916. component changes.
  25917. */
  25918. void addFocusChangeListener (FocusChangeListener* listener);
  25919. /** Unregisters a listener that was added with addFocusChangeListener(). */
  25920. void removeFocusChangeListener (FocusChangeListener* listener);
  25921. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  25922. The component must already be on the desktop for this method to work. It will
  25923. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  25924. etc will be hidden.
  25925. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  25926. the component that's currently being used will be resized back to the size
  25927. and position it was in before being put into this mode.
  25928. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  25929. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  25930. to hide as much on-screen paraphenalia as possible.
  25931. */
  25932. void setKioskModeComponent (Component* componentToUse,
  25933. bool allowMenusAndBars = true);
  25934. /** Returns the component that is currently being used in kiosk-mode.
  25935. This is the component that was last set by setKioskModeComponent(). If none
  25936. has been set, this returns 0.
  25937. */
  25938. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  25939. /** Returns the number of components that are currently active as top-level
  25940. desktop windows.
  25941. @see getComponent, Component::addToDesktop
  25942. */
  25943. int getNumComponents() const throw();
  25944. /** Returns one of the top-level desktop window components.
  25945. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  25946. index is out-of-range.
  25947. @see getNumComponents, Component::addToDesktop
  25948. */
  25949. Component* getComponent (int index) const throw();
  25950. /** Finds the component at a given screen location.
  25951. This will drill down into top-level windows to find the child component at
  25952. the given position.
  25953. Returns 0 if the co-ordinates are inside a non-Juce window.
  25954. */
  25955. Component* findComponentAt (const Point<int>& screenPosition) const;
  25956. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  25957. your animations.
  25958. Having a single shared ComponentAnimator object makes it more efficient when multiple
  25959. components are being moved around simultaneously. It's also more convenient than having
  25960. to manage your own instance of one.
  25961. @see ComponentAnimator
  25962. */
  25963. ComponentAnimator& getAnimator() throw() { return animator; }
  25964. /** Returns the number of MouseInputSource objects the system has at its disposal.
  25965. In a traditional single-mouse system, there might be only one object. On a multi-touch
  25966. system, there could be one input source per potential finger.
  25967. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  25968. @see getMouseSource
  25969. */
  25970. int getNumMouseSources() const throw() { return mouseSources.size(); }
  25971. /** Returns one of the system's MouseInputSource objects.
  25972. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  25973. a null pointer.
  25974. In a traditional single-mouse system, there might be only one object. On a multi-touch
  25975. system, there could be one input source per potential finger.
  25976. */
  25977. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  25978. /** Returns the main mouse input device that the system is using.
  25979. @see getNumMouseSources()
  25980. */
  25981. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  25982. /** Returns the number of mouse-sources that are currently being dragged.
  25983. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  25984. juce component has the button down on it. In a multi-touch system, this could
  25985. be any number from 0 to the number of simultaneous touches that can be detected.
  25986. */
  25987. int getNumDraggingMouseSources() const throw();
  25988. /** Returns one of the mouse sources that's currently being dragged.
  25989. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  25990. out of range, or if no mice or fingers are down, this will return a null pointer.
  25991. */
  25992. MouseInputSource* getDraggingMouseSource (int index) const throw();
  25993. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  25994. current mouse-drag operation.
  25995. This allows you to make sure that mouseDrag() events are sent continuously, even
  25996. when the mouse isn't moving. This can be useful for things like auto-scrolling
  25997. components when the mouse is near an edge.
  25998. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  25999. minimum interval between consecutive mouse drag callbacks. The callbacks
  26000. will continue until the mouse is released, and then the interval will be reset,
  26001. so you need to make sure it's called every time you begin a drag event.
  26002. Passing an interval of 0 or less will cancel the auto-repeat.
  26003. @see mouseDrag
  26004. */
  26005. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  26006. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  26007. enum DisplayOrientation
  26008. {
  26009. upright = 1, /**< Indicates that the display is the normal way up. */
  26010. upsideDown = 2, /**< Indicates that the display is upside-down. */
  26011. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  26012. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  26013. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  26014. };
  26015. /** In a tablet device which can be turned around, this returns the current orientation. */
  26016. DisplayOrientation getCurrentOrientation() const;
  26017. /** Sets which orientations the display is allowed to auto-rotate to.
  26018. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  26019. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  26020. set bit.
  26021. */
  26022. void setOrientationsEnabled (int allowedOrientations);
  26023. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  26024. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  26025. */
  26026. bool isOrientationEnabled (DisplayOrientation orientation) const throw();
  26027. /** Tells this object to refresh its idea of what the screen resolution is.
  26028. (Called internally by the native code).
  26029. */
  26030. void refreshMonitorSizes();
  26031. /** True if the OS supports semitransparent windows */
  26032. static bool canUseSemiTransparentWindows() throw();
  26033. private:
  26034. static Desktop* instance;
  26035. friend class Component;
  26036. friend class ComponentPeer;
  26037. friend class MouseInputSource;
  26038. friend class MouseInputSourceInternal;
  26039. friend class DeletedAtShutdown;
  26040. friend class TopLevelWindowManager;
  26041. OwnedArray <MouseInputSource> mouseSources;
  26042. void createMouseInputSources();
  26043. ListenerList <MouseListener> mouseListeners;
  26044. ListenerList <FocusChangeListener> focusListeners;
  26045. Array <Component*> desktopComponents;
  26046. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  26047. Point<int> lastFakeMouseMove;
  26048. void sendMouseMove();
  26049. int mouseClickCounter;
  26050. void incrementMouseClickCounter() throw();
  26051. ScopedPointer<Timer> dragRepeater;
  26052. Component* kioskModeComponent;
  26053. Rectangle<int> kioskComponentOriginalBounds;
  26054. int allowedOrientations;
  26055. ComponentAnimator animator;
  26056. void timerCallback();
  26057. void resetTimer();
  26058. int getNumDisplayMonitors() const throw();
  26059. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  26060. static void getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea);
  26061. void addDesktopComponent (Component* c);
  26062. void removeDesktopComponent (Component* c);
  26063. void componentBroughtToFront (Component* c);
  26064. static void setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  26065. void triggerFocusCallback();
  26066. void handleAsyncUpdate();
  26067. Desktop();
  26068. ~Desktop();
  26069. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  26070. };
  26071. #endif // __JUCE_DESKTOP_JUCEHEADER__
  26072. /*** End of inlined file: juce_Desktop.h ***/
  26073. class KeyPressMappingSet;
  26074. class ApplicationCommandManagerListener;
  26075. /**
  26076. One of these objects holds a list of all the commands your app can perform,
  26077. and despatches these commands when needed.
  26078. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  26079. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  26080. to invoke automatically, which means you don't have to handle the result of a menu
  26081. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  26082. which can choose which events they want to handle.
  26083. This architecture also allows for nested ApplicationCommandTargets, so that for example
  26084. you could have two different objects, one inside the other, both of which can respond to
  26085. a "delete" command. Depending on which one has focus, the command will be sent to the
  26086. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  26087. method.
  26088. To set up your app to use commands, you'll need to do the following:
  26089. - Create a global ApplicationCommandManager to hold the list of all possible
  26090. commands. (This will also manage a set of key-mappings for them).
  26091. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  26092. This allows the object to provide a list of commands that it can perform, and
  26093. to handle them.
  26094. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  26095. or ApplicationCommandManager::registerCommand().
  26096. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  26097. method to access the key-mapper object, which you will need to register as a key-listener
  26098. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  26099. about setting this up.
  26100. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  26101. cause these commands to be invoked automatically.
  26102. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  26103. When a command is invoked, the ApplicationCommandManager will try to choose the best
  26104. ApplicationCommandTarget to receive the specified command. To do this it will use the
  26105. current keyboard focus to see which component might be interested, and will search the
  26106. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  26107. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  26108. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  26109. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  26110. point if the command still hasn't been performed, it will be passed to the current
  26111. JUCEApplication object (which is itself an ApplicationCommandTarget).
  26112. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  26113. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  26114. the object yourself.
  26115. @see ApplicationCommandTarget, ApplicationCommandInfo
  26116. */
  26117. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  26118. private FocusChangeListener
  26119. {
  26120. public:
  26121. /** Creates an ApplicationCommandManager.
  26122. Once created, you'll need to register all your app's commands with it, using
  26123. ApplicationCommandManager::registerAllCommandsForTarget() or
  26124. ApplicationCommandManager::registerCommand().
  26125. */
  26126. ApplicationCommandManager();
  26127. /** Destructor.
  26128. Make sure that you don't delete this if pointers to it are still being used by
  26129. objects such as PopupMenus or Buttons.
  26130. */
  26131. virtual ~ApplicationCommandManager();
  26132. /** Clears the current list of all commands.
  26133. Note that this will also clear the contents of the KeyPressMappingSet.
  26134. */
  26135. void clearCommands();
  26136. /** Adds a command to the list of registered commands.
  26137. @see registerAllCommandsForTarget
  26138. */
  26139. void registerCommand (const ApplicationCommandInfo& newCommand);
  26140. /** Adds all the commands that this target publishes to the manager's list.
  26141. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  26142. to get details about all the commands that this target can do, and will call
  26143. registerCommand() to add each one to the manger's list.
  26144. @see registerCommand
  26145. */
  26146. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  26147. /** Removes the command with a specified ID.
  26148. Note that this will also remove any key mappings that are mapped to the command.
  26149. */
  26150. void removeCommand (CommandID commandID);
  26151. /** This should be called to tell the manager that one of its registered commands may have changed
  26152. its active status.
  26153. Because the command manager only finds out whether a command is active or inactive by querying
  26154. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  26155. allows things like buttons to update their enablement, etc.
  26156. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  26157. for any registered listeners.
  26158. */
  26159. void commandStatusChanged();
  26160. /** Returns the number of commands that have been registered.
  26161. @see registerCommand
  26162. */
  26163. int getNumCommands() const throw() { return commands.size(); }
  26164. /** Returns the details about one of the registered commands.
  26165. The index is between 0 and (getNumCommands() - 1).
  26166. */
  26167. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  26168. /** Returns the details about a given command ID.
  26169. This will search the list of registered commands for one with the given command
  26170. ID number, and return its associated info. If no matching command is found, this
  26171. will return 0.
  26172. */
  26173. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  26174. /** Returns the name field for a command.
  26175. An empty string is returned if no command with this ID has been registered.
  26176. @see getDescriptionOfCommand
  26177. */
  26178. const String getNameOfCommand (CommandID commandID) const throw();
  26179. /** Returns the description field for a command.
  26180. An empty string is returned if no command with this ID has been registered. If the
  26181. command has no description, this will return its short name field instead.
  26182. @see getNameOfCommand
  26183. */
  26184. const String getDescriptionOfCommand (CommandID commandID) const throw();
  26185. /** Returns the list of categories.
  26186. This will go through all registered commands, and return a list of all the distict
  26187. categoryName values from their ApplicationCommandInfo structure.
  26188. @see getCommandsInCategory()
  26189. */
  26190. const StringArray getCommandCategories() const;
  26191. /** Returns a list of all the command UIDs in a particular category.
  26192. @see getCommandCategories()
  26193. */
  26194. const Array <CommandID> getCommandsInCategory (const String& categoryName) const;
  26195. /** Returns the manager's internal set of key mappings.
  26196. This object can be used to edit the keypresses. To actually link this object up
  26197. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  26198. class.
  26199. @see KeyPressMappingSet
  26200. */
  26201. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  26202. /** Invokes the given command directly, sending it to the default target.
  26203. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  26204. structure.
  26205. */
  26206. bool invokeDirectly (CommandID commandID, bool asynchronously);
  26207. /** Sends a command to the default target.
  26208. This will choose a target using getFirstCommandTarget(), and send the specified command
  26209. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  26210. first target can't handle the command, it will be passed on to targets further down the
  26211. chain (see ApplicationCommandTarget::invoke() for more info).
  26212. @param invocationInfo this must be correctly filled-in, describing the context for
  26213. the invocation.
  26214. @param asynchronously if false, the command will be performed before this method returns.
  26215. If true, a message will be posted so that the command will be performed
  26216. later on the message thread, and this method will return immediately.
  26217. @see ApplicationCommandTarget::invoke
  26218. */
  26219. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  26220. bool asynchronously);
  26221. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  26222. Whenever the manager needs to know which target a command should be sent to, it calls
  26223. this method to determine the first one to try.
  26224. By default, this method will return the target that was set by calling setFirstCommandTarget().
  26225. If no target is set, it will return the result of findDefaultComponentTarget().
  26226. If you need to make sure all commands go via your own custom target, then you can
  26227. either use setFirstCommandTarget() to specify a single target, or override this method
  26228. if you need more complex logic to choose one.
  26229. It may return 0 if no targets are available.
  26230. @see getTargetForCommand, invoke, invokeDirectly
  26231. */
  26232. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  26233. /** Sets a target to be returned by getFirstCommandTarget().
  26234. If this is set to 0, then getFirstCommandTarget() will by default return the
  26235. result of findDefaultComponentTarget().
  26236. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  26237. deleting the target object.
  26238. */
  26239. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  26240. /** Tries to find the best target to use to perform a given command.
  26241. This will call getFirstCommandTarget() to find the preferred target, and will
  26242. check whether that target can handle the given command. If it can't, then it'll use
  26243. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  26244. so on until no more are available.
  26245. If no targets are found that can perform the command, this method will return 0.
  26246. If a target is found, then it will get the target to fill-in the upToDateInfo
  26247. structure with the latest info about that command, so that the caller can see
  26248. whether the command is disabled, ticked, etc.
  26249. */
  26250. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  26251. ApplicationCommandInfo& upToDateInfo);
  26252. /** Registers a listener that will be called when various events occur. */
  26253. void addListener (ApplicationCommandManagerListener* listener);
  26254. /** Deregisters a previously-added listener. */
  26255. void removeListener (ApplicationCommandManagerListener* listener);
  26256. /** Looks for a suitable command target based on which Components have the keyboard focus.
  26257. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  26258. but is exposed here in case it's useful.
  26259. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  26260. windows, etc., and using the findTargetForComponent() method.
  26261. */
  26262. static ApplicationCommandTarget* findDefaultComponentTarget();
  26263. /** Examines this component and all its parents in turn, looking for the first one
  26264. which is a ApplicationCommandTarget.
  26265. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  26266. that class.
  26267. */
  26268. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  26269. private:
  26270. OwnedArray <ApplicationCommandInfo> commands;
  26271. ListenerList <ApplicationCommandManagerListener> listeners;
  26272. ScopedPointer <KeyPressMappingSet> keyMappings;
  26273. ApplicationCommandTarget* firstTarget;
  26274. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  26275. void handleAsyncUpdate();
  26276. void globalFocusChanged (Component*);
  26277. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  26278. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  26279. // version of this method.
  26280. virtual short getFirstCommandTarget() { return 0; }
  26281. #endif
  26282. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  26283. };
  26284. /**
  26285. A listener that receives callbacks from an ApplicationCommandManager when
  26286. commands are invoked or the command list is changed.
  26287. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  26288. */
  26289. class JUCE_API ApplicationCommandManagerListener
  26290. {
  26291. public:
  26292. /** Destructor. */
  26293. virtual ~ApplicationCommandManagerListener() {}
  26294. /** Called when an app command is about to be invoked. */
  26295. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  26296. /** Called when commands are registered or deregistered from the
  26297. command manager, or when commands are made active or inactive.
  26298. Note that if you're using this to watch for changes to whether a command is disabled,
  26299. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  26300. whenever the status of your command might have changed.
  26301. */
  26302. virtual void applicationCommandListChanged() = 0;
  26303. };
  26304. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  26305. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  26306. #endif
  26307. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  26308. #endif
  26309. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26310. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  26311. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26312. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26313. /*** Start of inlined file: juce_PropertiesFile.h ***/
  26314. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  26315. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  26316. /** Wrapper on a file that stores a list of key/value data pairs.
  26317. Useful for storing application settings, etc. See the PropertySet class for
  26318. the interfaces that read and write values.
  26319. Not designed for very large amounts of data, as it keeps all the values in
  26320. memory and writes them out to disk lazily when they are changed.
  26321. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  26322. with it, and these will be signalled when a value changes.
  26323. @see PropertySet
  26324. */
  26325. class JUCE_API PropertiesFile : public PropertySet,
  26326. public ChangeBroadcaster,
  26327. private Timer
  26328. {
  26329. public:
  26330. enum FileFormatOptions
  26331. {
  26332. ignoreCaseOfKeyNames = 1,
  26333. storeAsBinary = 2,
  26334. storeAsCompressedBinary = 4,
  26335. storeAsXML = 8
  26336. };
  26337. /**
  26338. Creates a PropertiesFile object.
  26339. @param file the file to use
  26340. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  26341. is changed, the object will wait for this amount
  26342. of time and then save the file. If zero, the file
  26343. will be written to disk immediately on being changed
  26344. (which might be slow, as it'll re-write synchronously
  26345. each time a value-change method is called). If it is
  26346. less than zero, the file won't be saved until
  26347. save() or saveIfNeeded() are explicitly called.
  26348. @param optionFlags a combination of the flags in the FileFormatOptions
  26349. enum, which specify the type of file to save, and other
  26350. options.
  26351. @param processLock an optional InterprocessLock object that will be used to
  26352. prevent multiple threads or processes from writing to the file
  26353. at the same time. The PropertiesFile will keep a pointer to
  26354. this object but will not take ownership of it - the caller is
  26355. responsible for making sure that the lock doesn't get deleted
  26356. before the PropertiesFile has been deleted.
  26357. */
  26358. PropertiesFile (const File& file,
  26359. int millisecondsBeforeSaving,
  26360. int optionFlags,
  26361. InterProcessLock* processLock = 0);
  26362. /** Destructor.
  26363. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  26364. */
  26365. ~PropertiesFile();
  26366. /** Returns true if this file was created from a valid (or non-existent) file.
  26367. If the file failed to load correctly because it was corrupt or had insufficient
  26368. access, this will be false.
  26369. */
  26370. bool isValidFile() const throw() { return loadedOk; }
  26371. /** This will flush all the values to disk if they've changed since the last
  26372. time they were saved.
  26373. Returns false if it fails to write to the file for some reason (maybe because
  26374. it's read-only or the directory doesn't exist or something).
  26375. @see save
  26376. */
  26377. bool saveIfNeeded();
  26378. /** This will force a write-to-disk of the current values, regardless of whether
  26379. anything has changed since the last save.
  26380. Returns false if it fails to write to the file for some reason (maybe because
  26381. it's read-only or the directory doesn't exist or something).
  26382. @see saveIfNeeded
  26383. */
  26384. bool save();
  26385. /** Returns true if the properties have been altered since the last time they were saved.
  26386. The file is flagged as needing to be saved when you change a value, but you can
  26387. explicitly set this flag with setNeedsToBeSaved().
  26388. */
  26389. bool needsToBeSaved() const;
  26390. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  26391. @see needsToBeSaved
  26392. */
  26393. void setNeedsToBeSaved (bool needsToBeSaved);
  26394. /** Returns the file that's being used. */
  26395. const File getFile() const { return file; }
  26396. /** Handy utility to create a properties file in whatever the standard OS-specific
  26397. location is for these things.
  26398. This uses getDefaultAppSettingsFile() to decide what file to create, then
  26399. creates a PropertiesFile object with the specified properties. See
  26400. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  26401. what the parameters do.
  26402. @see getDefaultAppSettingsFile
  26403. */
  26404. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  26405. const String& fileNameSuffix,
  26406. const String& folderName,
  26407. bool commonToAllUsers,
  26408. int millisecondsBeforeSaving,
  26409. int propertiesFileOptions,
  26410. InterProcessLock* processLock = 0);
  26411. /** Handy utility to choose a file in the standard OS-dependent location for application
  26412. settings files.
  26413. So on a Mac, this will return a file called:
  26414. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  26415. On Windows it'll return something like:
  26416. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  26417. On Linux it'll return
  26418. ~/.[folderName]/[applicationName].[fileNameSuffix]
  26419. If you pass an empty string as the folder name, it'll use the app name for this (or
  26420. omit the folder name on the Mac).
  26421. If commonToAllUsers is true, then this will return the same file for all users of the
  26422. computer, regardless of the current user. If it is false, the file will be specific to
  26423. only the current user. Use this to choose whether you're saving settings that are common
  26424. or user-specific.
  26425. */
  26426. static const File getDefaultAppSettingsFile (const String& applicationName,
  26427. const String& fileNameSuffix,
  26428. const String& folderName,
  26429. bool commonToAllUsers);
  26430. protected:
  26431. virtual void propertyChanged();
  26432. private:
  26433. File file;
  26434. int timerInterval;
  26435. const int options;
  26436. bool loadedOk, needsWriting;
  26437. InterProcessLock* processLock;
  26438. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  26439. InterProcessLock::ScopedLockType* createProcessLock() const;
  26440. void timerCallback();
  26441. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  26442. };
  26443. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  26444. /*** End of inlined file: juce_PropertiesFile.h ***/
  26445. /**
  26446. Manages a collection of properties.
  26447. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  26448. as a singleton.
  26449. It holds two different PropertiesFile objects internally, one for user-specific
  26450. settings (stored in your user directory), and one for settings that are common to
  26451. all users (stored in a folder accessible to all users).
  26452. The class manages the creation of these files on-demand, allowing access via the
  26453. getUserSettings() and getCommonSettings() methods. It also has a few handy
  26454. methods like testWriteAccess() to check that the files can be saved.
  26455. If you're using one of these as a singleton, then your app's start-up code should
  26456. first of all call setStorageParameters() to tell it the parameters to use to create
  26457. the properties files.
  26458. @see PropertiesFile
  26459. */
  26460. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  26461. {
  26462. public:
  26463. /**
  26464. Creates an ApplicationProperties object.
  26465. Before using it, you must call setStorageParameters() to give it the info
  26466. it needs to create the property files.
  26467. */
  26468. ApplicationProperties();
  26469. /** Destructor. */
  26470. ~ApplicationProperties();
  26471. juce_DeclareSingleton (ApplicationProperties, false)
  26472. /** Gives the object the information it needs to create the appropriate properties files.
  26473. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  26474. info about how these parameters are used.
  26475. */
  26476. void setStorageParameters (const String& applicationName,
  26477. const String& fileNameSuffix,
  26478. const String& folderName,
  26479. int millisecondsBeforeSaving,
  26480. int propertiesFileOptions,
  26481. InterProcessLock* processLock = 0);
  26482. /** Tests whether the files can be successfully written to, and can show
  26483. an error message if not.
  26484. Returns true if none of the tests fail.
  26485. @param testUserSettings if true, the user settings file will be tested
  26486. @param testCommonSettings if true, the common settings file will be tested
  26487. @param showWarningDialogOnFailure if true, the method will show a helpful error
  26488. message box if either of the tests fail
  26489. */
  26490. bool testWriteAccess (bool testUserSettings,
  26491. bool testCommonSettings,
  26492. bool showWarningDialogOnFailure);
  26493. /** Returns the user settings file.
  26494. The first time this is called, it will create and load the properties file.
  26495. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  26496. the common settings are used as a second-chance place to look. This is done via the
  26497. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  26498. to the fallback for the user settings.
  26499. @see getCommonSettings
  26500. */
  26501. PropertiesFile* getUserSettings();
  26502. /** Returns the common settings file.
  26503. The first time this is called, it will create and load the properties file.
  26504. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  26505. read-only (e.g. because the user doesn't have permission to write
  26506. to shared files), then this will return the user settings instead,
  26507. (like getUserSettings() would do). This is handy if you'd like to
  26508. write a value to the common settings, but if that's no possible,
  26509. then you'd rather write to the user settings than none at all.
  26510. If returnUserPropsIfReadOnly is false, this method will always return
  26511. the common settings, even if any changes to them can't be saved.
  26512. @see getUserSettings
  26513. */
  26514. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  26515. /** Saves both files if they need to be saved.
  26516. @see PropertiesFile::saveIfNeeded
  26517. */
  26518. bool saveIfNeeded();
  26519. /** Flushes and closes both files if they are open.
  26520. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  26521. and closes both files. They will then be re-opened the next time getUserSettings()
  26522. or getCommonSettings() is called.
  26523. */
  26524. void closeFiles();
  26525. private:
  26526. ScopedPointer <PropertiesFile> userProps, commonProps;
  26527. String appName, fileSuffix, folderName;
  26528. int msBeforeSaving, options;
  26529. int commonSettingsAreReadOnly;
  26530. InterProcessLock* processLock;
  26531. void openFiles();
  26532. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  26533. };
  26534. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26535. /*** End of inlined file: juce_ApplicationProperties.h ***/
  26536. #endif
  26537. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26538. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  26539. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26540. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26541. /*** Start of inlined file: juce_AudioFormat.h ***/
  26542. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26543. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26544. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  26545. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26546. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26547. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  26548. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26549. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26550. /**
  26551. This class a container which holds all the classes pertaining to the AudioData::Pointer
  26552. audio sample format class.
  26553. @see AudioData::Pointer.
  26554. */
  26555. class JUCE_API AudioData
  26556. {
  26557. public:
  26558. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  26559. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  26560. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  26561. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  26562. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  26563. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  26564. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  26565. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  26566. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  26567. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  26568. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  26569. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  26570. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  26571. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  26572. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  26573. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  26574. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  26575. #ifndef DOXYGEN
  26576. class BigEndian
  26577. {
  26578. public:
  26579. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatBE(); }
  26580. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatBE (newValue); }
  26581. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32BE(); }
  26582. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32BE (newValue); }
  26583. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromBE (source); }
  26584. enum { isBigEndian = 1 };
  26585. };
  26586. class LittleEndian
  26587. {
  26588. public:
  26589. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatLE(); }
  26590. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatLE (newValue); }
  26591. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32LE(); }
  26592. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32LE (newValue); }
  26593. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromLE (source); }
  26594. enum { isBigEndian = 0 };
  26595. };
  26596. #if JUCE_BIG_ENDIAN
  26597. class NativeEndian : public BigEndian {};
  26598. #else
  26599. class NativeEndian : public LittleEndian {};
  26600. #endif
  26601. class Int8
  26602. {
  26603. public:
  26604. inline Int8 (void* data_) throw() : data (static_cast <int8*> (data_)) {}
  26605. inline void advance() throw() { ++data; }
  26606. inline void skip (int numSamples) throw() { data += numSamples; }
  26607. inline float getAsFloatLE() const throw() { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  26608. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  26609. inline void setAsFloatLE (float newValue) throw() { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  26610. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  26611. inline int32 getAsInt32LE() const throw() { return (int) (*data << 24); }
  26612. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  26613. inline void setAsInt32LE (int newValue) throw() { *data = (int8) (newValue >> 24); }
  26614. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  26615. inline void clear() throw() { *data = 0; }
  26616. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26617. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26618. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26619. inline void copyFromSameType (Int8& source) throw() { *data = *source.data; }
  26620. int8* data;
  26621. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26622. };
  26623. class UInt8
  26624. {
  26625. public:
  26626. inline UInt8 (void* data_) throw() : data (static_cast <uint8*> (data_)) {}
  26627. inline void advance() throw() { ++data; }
  26628. inline void skip (int numSamples) throw() { data += numSamples; }
  26629. inline float getAsFloatLE() const throw() { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  26630. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  26631. inline void setAsFloatLE (float newValue) throw() { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  26632. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  26633. inline int32 getAsInt32LE() const throw() { return (int) ((*data - 128) << 24); }
  26634. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  26635. inline void setAsInt32LE (int newValue) throw() { *data = (uint8) (128 + (newValue >> 24)); }
  26636. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  26637. inline void clear() throw() { *data = 128; }
  26638. inline void clearMultiple (int num) throw() { memset (data, 128, num) ;}
  26639. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26640. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26641. inline void copyFromSameType (UInt8& source) throw() { *data = *source.data; }
  26642. uint8* data;
  26643. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26644. };
  26645. class Int16
  26646. {
  26647. public:
  26648. inline Int16 (void* data_) throw() : data (static_cast <uint16*> (data_)) {}
  26649. inline void advance() throw() { ++data; }
  26650. inline void skip (int numSamples) throw() { data += numSamples; }
  26651. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  26652. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  26653. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26654. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26655. inline int32 getAsInt32LE() const throw() { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  26656. inline int32 getAsInt32BE() const throw() { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  26657. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  26658. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  26659. inline void clear() throw() { *data = 0; }
  26660. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26661. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26662. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26663. inline void copyFromSameType (Int16& source) throw() { *data = *source.data; }
  26664. uint16* data;
  26665. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  26666. };
  26667. class Int24
  26668. {
  26669. public:
  26670. inline Int24 (void* data_) throw() : data (static_cast <char*> (data_)) {}
  26671. inline void advance() throw() { data += 3; }
  26672. inline void skip (int numSamples) throw() { data += 3 * numSamples; }
  26673. inline float getAsFloatLE() const throw() { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26674. inline float getAsFloatBE() const throw() { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26675. inline void setAsFloatLE (float newValue) throw() { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26676. inline void setAsFloatBE (float newValue) throw() { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26677. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  26678. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  26679. inline void setAsInt32LE (int32 newValue) throw() { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  26680. inline void setAsInt32BE (int32 newValue) throw() { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  26681. inline void clear() throw() { data[0] = 0; data[1] = 0; data[2] = 0; }
  26682. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26683. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26684. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26685. inline void copyFromSameType (Int24& source) throw() { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  26686. char* data;
  26687. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  26688. };
  26689. class Int32
  26690. {
  26691. public:
  26692. inline Int32 (void* data_) throw() : data (static_cast <uint32*> (data_)) {}
  26693. inline void advance() throw() { ++data; }
  26694. inline void skip (int numSamples) throw() { data += numSamples; }
  26695. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  26696. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  26697. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  26698. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) (maxValue * jlimit (-1.0, 1.0, (double) newValue))); }
  26699. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::swapIfBigEndian (*data); }
  26700. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  26701. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  26702. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  26703. inline void clear() throw() { *data = 0; }
  26704. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26705. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26706. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26707. inline void copyFromSameType (Int32& source) throw() { *data = *source.data; }
  26708. uint32* data;
  26709. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  26710. };
  26711. class Float32
  26712. {
  26713. public:
  26714. inline Float32 (void* data_) throw() : data (static_cast <float*> (data_)) {}
  26715. inline void advance() throw() { ++data; }
  26716. inline void skip (int numSamples) throw() { data += numSamples; }
  26717. #if JUCE_BIG_ENDIAN
  26718. inline float getAsFloatBE() const throw() { return *data; }
  26719. inline void setAsFloatBE (float newValue) throw() { *data = newValue; }
  26720. inline float getAsFloatLE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26721. inline void setAsFloatLE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26722. #else
  26723. inline float getAsFloatLE() const throw() { return *data; }
  26724. inline void setAsFloatLE (float newValue) throw() { *data = newValue; }
  26725. inline float getAsFloatBE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26726. inline void setAsFloatBE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26727. #endif
  26728. inline int32 getAsInt32LE() const throw() { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatLE()) * (double) maxValue); }
  26729. inline int32 getAsInt32BE() const throw() { return (int32) roundToInt (jlimit (-1.0, 1.0, (double) getAsFloatBE()) * (double) maxValue); }
  26730. inline void setAsInt32LE (int32 newValue) throw() { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26731. inline void setAsInt32BE (int32 newValue) throw() { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26732. inline void clear() throw() { *data = 0; }
  26733. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26734. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsFloatLE (source.getAsFloat()); }
  26735. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsFloatBE (source.getAsFloat()); }
  26736. inline void copyFromSameType (Float32& source) throw() { *data = *source.data; }
  26737. float* data;
  26738. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  26739. };
  26740. class NonInterleaved
  26741. {
  26742. public:
  26743. inline NonInterleaved() throw() {}
  26744. inline NonInterleaved (const NonInterleaved&) throw() {}
  26745. inline NonInterleaved (const int) throw() {}
  26746. inline void copyFrom (const NonInterleaved&) throw() {}
  26747. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.advance(); }
  26748. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numSamples); }
  26749. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { s.clearMultiple (numSamples); }
  26750. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) throw() { return SampleFormatType::bytesPerSample; }
  26751. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  26752. };
  26753. class Interleaved
  26754. {
  26755. public:
  26756. inline Interleaved() throw() : numInterleavedChannels (1) {}
  26757. inline Interleaved (const Interleaved& other) throw() : numInterleavedChannels (other.numInterleavedChannels) {}
  26758. inline Interleaved (const int numInterleavedChannels_) throw() : numInterleavedChannels (numInterleavedChannels_) {}
  26759. inline void copyFrom (const Interleaved& other) throw() { numInterleavedChannels = other.numInterleavedChannels; }
  26760. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.skip (numInterleavedChannels); }
  26761. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numInterleavedChannels * numSamples); }
  26762. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  26763. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const throw() { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  26764. int numInterleavedChannels;
  26765. enum { isInterleavedType = 1 };
  26766. };
  26767. class NonConst
  26768. {
  26769. public:
  26770. typedef void VoidType;
  26771. static inline void* toVoidPtr (VoidType* v) throw() { return v; }
  26772. enum { isConst = 0 };
  26773. };
  26774. class Const
  26775. {
  26776. public:
  26777. typedef const void VoidType;
  26778. static inline void* toVoidPtr (VoidType* v) throw() { return const_cast<void*> (v); }
  26779. enum { isConst = 1 };
  26780. };
  26781. #endif
  26782. /**
  26783. A pointer to a block of audio data with a particular encoding.
  26784. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  26785. the audio format as a series of template parameters, e.g.
  26786. @code
  26787. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  26788. AudioData::Pointer <AudioData::Int16,
  26789. AudioData::LittleEndian,
  26790. AudioData::NonInterleaved,
  26791. AudioData::Const> pointer (someRawAudioData);
  26792. // These methods read the sample that is being pointed to
  26793. float firstSampleAsFloat = pointer.getAsFloat();
  26794. int32 firstSampleAsInt = pointer.getAsInt32();
  26795. ++pointer; // moves the pointer to the next sample.
  26796. pointer += 3; // skips the next 3 samples.
  26797. @endcode
  26798. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  26799. converting its format.
  26800. @see AudioData::Converter
  26801. */
  26802. template <typename SampleFormat,
  26803. typename Endianness,
  26804. typename InterleavingType,
  26805. typename Constness>
  26806. class Pointer
  26807. {
  26808. public:
  26809. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  26810. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  26811. for interleaved formats, use the constructor that also takes a number of channels.
  26812. */
  26813. Pointer (typename Constness::VoidType* sourceData) throw()
  26814. : data (Constness::toVoidPtr (sourceData))
  26815. {
  26816. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  26817. // you should pass NonInterleaved as the template parameter for the interleaving type!
  26818. static_jassert (InterleavingType::isInterleavedType == 0);
  26819. }
  26820. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  26821. For non-interleaved data, use the other constructor.
  26822. */
  26823. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) throw()
  26824. : data (Constness::toVoidPtr (sourceData)),
  26825. interleaving (numInterleavedChannels)
  26826. {
  26827. }
  26828. /** Creates a copy of another pointer. */
  26829. Pointer (const Pointer& other) throw()
  26830. : data (other.data),
  26831. interleaving (other.interleaving)
  26832. {
  26833. }
  26834. Pointer& operator= (const Pointer& other) throw()
  26835. {
  26836. data = other.data;
  26837. interleaving.copyFrom (other.interleaving);
  26838. return *this;
  26839. }
  26840. /** Returns the value of the first sample as a floating point value.
  26841. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  26842. formats, the value could be outside that range, although -1 to 1 is the standard range.
  26843. */
  26844. inline float getAsFloat() const throw() { return Endianness::getAsFloat (data); }
  26845. /** Sets the value of the first sample as a floating point value.
  26846. (This method can only be used if the AudioData::NonConst option was used).
  26847. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  26848. range will be clipped. For floating point formats, any value passed in here will be
  26849. written directly, although -1 to 1 is the standard range.
  26850. */
  26851. inline void setAsFloat (float newValue) throw()
  26852. {
  26853. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26854. Endianness::setAsFloat (data, newValue);
  26855. }
  26856. /** Returns the value of the first sample as a 32-bit integer.
  26857. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  26858. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  26859. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  26860. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  26861. */
  26862. inline int32 getAsInt32() const throw() { return Endianness::getAsInt32 (data); }
  26863. /** Sets the value of the first sample as a 32-bit integer.
  26864. This will be mapped to the range of the format that is being written - see getAsInt32().
  26865. */
  26866. inline void setAsInt32 (int32 newValue) throw()
  26867. {
  26868. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26869. Endianness::setAsInt32 (data, newValue);
  26870. }
  26871. /** Moves the pointer along to the next sample. */
  26872. inline Pointer& operator++() throw() { advance(); return *this; }
  26873. /** Moves the pointer back to the previous sample. */
  26874. inline Pointer& operator--() throw() { interleaving.advanceDataBy (data, -1); return *this; }
  26875. /** Adds a number of samples to the pointer's position. */
  26876. Pointer& operator+= (int samplesToJump) throw() { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  26877. /** Writes a stream of samples into this pointer from another pointer.
  26878. This will copy the specified number of samples, converting between formats appropriately.
  26879. */
  26880. void convertSamples (Pointer source, int numSamples) const throw()
  26881. {
  26882. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26883. Pointer dest (*this);
  26884. while (--numSamples >= 0)
  26885. {
  26886. dest.data.copyFromSameType (source.data);
  26887. dest.advance();
  26888. source.advance();
  26889. }
  26890. }
  26891. /** Writes a stream of samples into this pointer from another pointer.
  26892. This will copy the specified number of samples, converting between formats appropriately.
  26893. */
  26894. template <class OtherPointerType>
  26895. void convertSamples (OtherPointerType source, int numSamples) const throw()
  26896. {
  26897. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26898. Pointer dest (*this);
  26899. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  26900. {
  26901. while (--numSamples >= 0)
  26902. {
  26903. Endianness::copyFrom (dest.data, source);
  26904. dest.advance();
  26905. ++source;
  26906. }
  26907. }
  26908. else // copy backwards if we're increasing the sample width..
  26909. {
  26910. dest += numSamples;
  26911. source += numSamples;
  26912. while (--numSamples >= 0)
  26913. Endianness::copyFrom ((--dest).data, --source);
  26914. }
  26915. }
  26916. /** Sets a number of samples to zero. */
  26917. void clearSamples (int numSamples) const throw()
  26918. {
  26919. Pointer dest (*this);
  26920. dest.interleaving.clear (dest.data, numSamples);
  26921. }
  26922. /** Returns true if the pointer is using a floating-point format. */
  26923. static bool isFloatingPoint() throw() { return (bool) SampleFormat::isFloat; }
  26924. /** Returns true if the format is big-endian. */
  26925. static bool isBigEndian() throw() { return (bool) Endianness::isBigEndian; }
  26926. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  26927. static int getBytesPerSample() throw() { return (int) SampleFormat::bytesPerSample; }
  26928. /** Returns the number of interleaved channels in the format. */
  26929. int getNumInterleavedChannels() const throw() { return (int) this->numInterleavedChannels; }
  26930. /** Returns the number of bytes between the start address of each sample. */
  26931. int getNumBytesBetweenSamples() const throw() { return interleaving.getNumBytesBetweenSamples (data); }
  26932. /** Returns the accuracy of this format when represented as a 32-bit integer.
  26933. This is the smallest number above 0 that can be represented in the sample format, converted to
  26934. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  26935. its resolution is 0x100.
  26936. */
  26937. static int get32BitResolution() throw() { return (int) SampleFormat::resolution; }
  26938. /** Returns a pointer to the underlying data. */
  26939. const void* getRawData() const throw() { return data.data; }
  26940. private:
  26941. SampleFormat data;
  26942. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  26943. // advantage of EBCO causes an internal compiler error in VC6..
  26944. inline void advance() throw() { interleaving.advanceData (data); }
  26945. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  26946. Pointer operator-- (int);
  26947. };
  26948. /** A base class for objects that are used to convert between two different sample formats.
  26949. The AudioData::ConverterInstance implements this base class and can be templated, so
  26950. you can create an instance that converts between two particular formats, and then
  26951. store this in the abstract base class.
  26952. @see AudioData::ConverterInstance
  26953. */
  26954. class Converter
  26955. {
  26956. public:
  26957. virtual ~Converter() {}
  26958. /** Converts a sequence of samples from the converter's source format into the dest format. */
  26959. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  26960. /** Converts a sequence of samples from the converter's source format into the dest format.
  26961. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  26962. particular sub-channel of the data to be used.
  26963. */
  26964. virtual void convertSamples (void* destSamples, int destSubChannel,
  26965. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  26966. };
  26967. /**
  26968. A class that converts between two templated AudioData::Pointer types, and which
  26969. implements the AudioData::Converter interface.
  26970. This can be used as a concrete instance of the AudioData::Converter abstract class.
  26971. @see AudioData::Converter
  26972. */
  26973. template <class SourceSampleType, class DestSampleType>
  26974. class ConverterInstance : public Converter
  26975. {
  26976. public:
  26977. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  26978. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  26979. {}
  26980. ~ConverterInstance() {}
  26981. void convertSamples (void* dest, const void* source, int numSamples) const
  26982. {
  26983. SourceSampleType s (source, sourceChannels);
  26984. DestSampleType d (dest, destChannels);
  26985. d.convertSamples (s, numSamples);
  26986. }
  26987. void convertSamples (void* dest, int destSubChannel,
  26988. const void* source, int sourceSubChannel, int numSamples) const
  26989. {
  26990. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  26991. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  26992. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  26993. d.convertSamples (s, numSamples);
  26994. }
  26995. private:
  26996. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  26997. const int sourceChannels, destChannels;
  26998. };
  26999. };
  27000. /**
  27001. A set of routines to convert buffers of 32-bit floating point data to and from
  27002. various integer formats.
  27003. Note that these functions are deprecated - the AudioData class provides a much more
  27004. flexible set of conversion classes now.
  27005. */
  27006. class JUCE_API AudioDataConverters
  27007. {
  27008. public:
  27009. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27010. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27011. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27012. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27013. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27014. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27015. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27016. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27017. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27018. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27019. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27020. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27021. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27022. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27023. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27024. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27025. enum DataFormat
  27026. {
  27027. int16LE,
  27028. int16BE,
  27029. int24LE,
  27030. int24BE,
  27031. int32LE,
  27032. int32BE,
  27033. float32LE,
  27034. float32BE,
  27035. };
  27036. static void convertFloatToFormat (DataFormat destFormat,
  27037. const float* source, void* dest, int numSamples);
  27038. static void convertFormatToFloat (DataFormat sourceFormat,
  27039. const void* source, float* dest, int numSamples);
  27040. static void interleaveSamples (const float** source, float* dest,
  27041. int numSamples, int numChannels);
  27042. static void deinterleaveSamples (const float* source, float** dest,
  27043. int numSamples, int numChannels);
  27044. private:
  27045. AudioDataConverters();
  27046. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  27047. };
  27048. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27049. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27050. class AudioFormat;
  27051. /**
  27052. Reads samples from an audio file stream.
  27053. A subclass that reads a specific type of audio format will be created by
  27054. an AudioFormat object.
  27055. @see AudioFormat, AudioFormatWriter
  27056. */
  27057. class JUCE_API AudioFormatReader
  27058. {
  27059. protected:
  27060. /** Creates an AudioFormatReader object.
  27061. @param sourceStream the stream to read from - this will be deleted
  27062. by this object when it is no longer needed. (Some
  27063. specialised readers might not use this parameter and
  27064. can leave it as 0).
  27065. @param formatName the description that will be returned by the getFormatName()
  27066. method
  27067. */
  27068. AudioFormatReader (InputStream* sourceStream,
  27069. const String& formatName);
  27070. public:
  27071. /** Destructor. */
  27072. virtual ~AudioFormatReader();
  27073. /** Returns a description of what type of format this is.
  27074. E.g. "AIFF"
  27075. */
  27076. const String getFormatName() const throw() { return formatName; }
  27077. /** Reads samples from the stream.
  27078. @param destSamples an array of buffers into which the sample data for each
  27079. channel will be written.
  27080. If the format is fixed-point, each channel will be written
  27081. as an array of 32-bit signed integers using the full
  27082. range -0x80000000 to 0x7fffffff, regardless of the source's
  27083. bit-depth. If it is a floating-point format, you should cast
  27084. the resulting array to a (float**) to get the values (in the
  27085. range -1.0 to 1.0 or beyond)
  27086. If the format is stereo, then destSamples[0] is the left channel
  27087. data, and destSamples[1] is the right channel.
  27088. The numDestChannels parameter indicates how many pointers this array
  27089. contains, but some of these pointers can be null if you don't want to
  27090. read data for some of the channels
  27091. @param numDestChannels the number of array elements in the destChannels array
  27092. @param startSampleInSource the position in the audio file or stream at which the samples
  27093. should be read, as a number of samples from the start of the
  27094. stream. It's ok for this to be beyond the start or end of the
  27095. available data - any samples that are out-of-range will be returned
  27096. as zeros.
  27097. @param numSamplesToRead the number of samples to read. If this is greater than the number
  27098. of samples that the file or stream contains. the result will be padded
  27099. with zeros
  27100. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  27101. for some of the channels that you pass in, then they should be filled with
  27102. copies of valid source channels.
  27103. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  27104. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  27105. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  27106. was false, then only the first channel would be filled with the file's contents, and
  27107. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  27108. from a stereo file, then the last 3 would all end up with copies of the same data.
  27109. @returns true if the operation succeeded, false if there was an error. Note
  27110. that reading sections of data beyond the extent of the stream isn't an
  27111. error - the reader should just return zeros for these regions
  27112. @see readMaxLevels
  27113. */
  27114. bool read (int* const* destSamples,
  27115. int numDestChannels,
  27116. int64 startSampleInSource,
  27117. int numSamplesToRead,
  27118. bool fillLeftoverChannelsWithCopies);
  27119. /** Finds the highest and lowest sample levels from a section of the audio stream.
  27120. This will read a block of samples from the stream, and measure the
  27121. highest and lowest sample levels from the channels in that section, returning
  27122. these as normalised floating-point levels.
  27123. @param startSample the offset into the audio stream to start reading from. It's
  27124. ok for this to be beyond the start or end of the stream.
  27125. @param numSamples how many samples to read
  27126. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  27127. @param highestLeft on return, this is the highest absolute sample from the left channel
  27128. @param lowestRight on return, this is the lowest absolute sample from the right
  27129. channel (if there is one)
  27130. @param highestRight on return, this is the highest absolute sample from the right
  27131. channel (if there is one)
  27132. @see read
  27133. */
  27134. virtual void readMaxLevels (int64 startSample,
  27135. int64 numSamples,
  27136. float& lowestLeft,
  27137. float& highestLeft,
  27138. float& lowestRight,
  27139. float& highestRight);
  27140. /** Scans the source looking for a sample whose magnitude is in a specified range.
  27141. This will read from the source, either forwards or backwards between two sample
  27142. positions, until it finds a sample whose magnitude lies between two specified levels.
  27143. If it finds a suitable sample, it returns its position; if not, it will return -1.
  27144. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  27145. points when you're searching for a continuous range of samples
  27146. @param startSample the first sample to look at
  27147. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  27148. the search will go backwards
  27149. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27150. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  27151. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  27152. of this many consecutive samples, all of which lie
  27153. within the target range. When it finds such a sequence,
  27154. it returns the position of the first in-range sample
  27155. it found (i.e. the earliest one if scanning forwards, the
  27156. latest one if scanning backwards)
  27157. */
  27158. int64 searchForLevel (int64 startSample,
  27159. int64 numSamplesToSearch,
  27160. double magnitudeRangeMinimum,
  27161. double magnitudeRangeMaximum,
  27162. int minimumConsecutiveSamples);
  27163. /** The sample-rate of the stream. */
  27164. double sampleRate;
  27165. /** The number of bits per sample, e.g. 16, 24, 32. */
  27166. unsigned int bitsPerSample;
  27167. /** The total number of samples in the audio stream. */
  27168. int64 lengthInSamples;
  27169. /** The total number of channels in the audio stream. */
  27170. unsigned int numChannels;
  27171. /** Indicates whether the data is floating-point or fixed. */
  27172. bool usesFloatingPointData;
  27173. /** A set of metadata values that the reader has pulled out of the stream.
  27174. Exactly what these values are depends on the format, so you can
  27175. check out the format implementation code to see what kind of stuff
  27176. they understand.
  27177. */
  27178. StringPairArray metadataValues;
  27179. /** The input stream, for use by subclasses. */
  27180. InputStream* input;
  27181. /** Subclasses must implement this method to perform the low-level read operation.
  27182. Callers should use read() instead of calling this directly.
  27183. @param destSamples the array of destination buffers to fill. Some of these
  27184. pointers may be null
  27185. @param numDestChannels the number of items in the destSamples array. This
  27186. value is guaranteed not to be greater than the number of
  27187. channels that this reader object contains
  27188. @param startOffsetInDestBuffer the number of samples from the start of the
  27189. dest data at which to begin writing
  27190. @param startSampleInFile the number of samples into the source data at which
  27191. to begin reading. This value is guaranteed to be >= 0.
  27192. @param numSamples the number of samples to read
  27193. */
  27194. virtual bool readSamples (int** destSamples,
  27195. int numDestChannels,
  27196. int startOffsetInDestBuffer,
  27197. int64 startSampleInFile,
  27198. int numSamples) = 0;
  27199. protected:
  27200. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  27201. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  27202. struct ReadHelper
  27203. {
  27204. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  27205. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  27206. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) throw()
  27207. {
  27208. for (int i = 0; i < numDestChannels; ++i)
  27209. {
  27210. if (destData[i] != 0)
  27211. {
  27212. DestType dest (destData[i]);
  27213. dest += destOffset;
  27214. if (i < numSourceChannels)
  27215. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  27216. else
  27217. dest.clearSamples (numSamples);
  27218. }
  27219. }
  27220. }
  27221. };
  27222. private:
  27223. String formatName;
  27224. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  27225. };
  27226. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27227. /*** End of inlined file: juce_AudioFormatReader.h ***/
  27228. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  27229. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27230. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27231. /*** Start of inlined file: juce_AudioSource.h ***/
  27232. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  27233. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  27234. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  27235. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27236. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27237. class AudioFormatReader;
  27238. class AudioFormatWriter;
  27239. /**
  27240. A multi-channel buffer of 32-bit floating point audio samples.
  27241. */
  27242. class JUCE_API AudioSampleBuffer
  27243. {
  27244. public:
  27245. /** Creates a buffer with a specified number of channels and samples.
  27246. The contents of the buffer will initially be undefined, so use clear() to
  27247. set all the samples to zero.
  27248. The buffer will allocate its memory internally, and this will be released
  27249. when the buffer is deleted.
  27250. */
  27251. AudioSampleBuffer (int numChannels,
  27252. int numSamples) throw();
  27253. /** Creates a buffer using a pre-allocated block of memory.
  27254. Note that if the buffer is resized or its number of channels is changed, it
  27255. will re-allocate memory internally and copy the existing data to this new area,
  27256. so it will then stop directly addressing this memory.
  27257. @param dataToReferTo a pre-allocated array containing pointers to the data
  27258. for each channel that should be used by this buffer. The
  27259. buffer will only refer to this memory, it won't try to delete
  27260. it when the buffer is deleted or resized.
  27261. @param numChannels the number of channels to use - this must correspond to the
  27262. number of elements in the array passed in
  27263. @param numSamples the number of samples to use - this must correspond to the
  27264. size of the arrays passed in
  27265. */
  27266. AudioSampleBuffer (float** dataToReferTo,
  27267. int numChannels,
  27268. int numSamples) throw();
  27269. /** Creates a buffer using a pre-allocated block of memory.
  27270. Note that if the buffer is resized or its number of channels is changed, it
  27271. will re-allocate memory internally and copy the existing data to this new area,
  27272. so it will then stop directly addressing this memory.
  27273. @param dataToReferTo a pre-allocated array containing pointers to the data
  27274. for each channel that should be used by this buffer. The
  27275. buffer will only refer to this memory, it won't try to delete
  27276. it when the buffer is deleted or resized.
  27277. @param numChannels the number of channels to use - this must correspond to the
  27278. number of elements in the array passed in
  27279. @param startSample the offset within the arrays at which the data begins
  27280. @param numSamples the number of samples to use - this must correspond to the
  27281. size of the arrays passed in
  27282. */
  27283. AudioSampleBuffer (float** dataToReferTo,
  27284. int numChannels,
  27285. int startSample,
  27286. int numSamples) throw();
  27287. /** Copies another buffer.
  27288. This buffer will make its own copy of the other's data, unless the buffer was created
  27289. using an external data buffer, in which case boths buffers will just point to the same
  27290. shared block of data.
  27291. */
  27292. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  27293. /** Copies another buffer onto this one.
  27294. This buffer's size will be changed to that of the other buffer.
  27295. */
  27296. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  27297. /** Destructor.
  27298. This will free any memory allocated by the buffer.
  27299. */
  27300. virtual ~AudioSampleBuffer() throw();
  27301. /** Returns the number of channels of audio data that this buffer contains.
  27302. @see getSampleData
  27303. */
  27304. int getNumChannels() const throw() { return numChannels; }
  27305. /** Returns the number of samples allocated in each of the buffer's channels.
  27306. @see getSampleData
  27307. */
  27308. int getNumSamples() const throw() { return size; }
  27309. /** Returns a pointer one of the buffer's channels.
  27310. For speed, this doesn't check whether the channel number is out of range,
  27311. so be careful when using it!
  27312. */
  27313. float* getSampleData (const int channelNumber) const throw()
  27314. {
  27315. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27316. return channels [channelNumber];
  27317. }
  27318. /** Returns a pointer to a sample in one of the buffer's channels.
  27319. For speed, this doesn't check whether the channel and sample number
  27320. are out-of-range, so be careful when using it!
  27321. */
  27322. float* getSampleData (const int channelNumber,
  27323. const int sampleOffset) const throw()
  27324. {
  27325. jassert (isPositiveAndBelow (channelNumber, numChannels));
  27326. jassert (isPositiveAndBelow (sampleOffset, size));
  27327. return channels [channelNumber] + sampleOffset;
  27328. }
  27329. /** Returns an array of pointers to the channels in the buffer.
  27330. Don't modify any of the pointers that are returned, and bear in mind that
  27331. these will become invalid if the buffer is resized.
  27332. */
  27333. float** getArrayOfChannels() const throw() { return channels; }
  27334. /** Changes the buffer's size or number of channels.
  27335. This can expand or contract the buffer's length, and add or remove channels.
  27336. If keepExistingContent is true, it will try to preserve as much of the
  27337. old data as it can in the new buffer.
  27338. If clearExtraSpace is true, then any extra channels or space that is
  27339. allocated will be also be cleared. If false, then this space is left
  27340. uninitialised.
  27341. If avoidReallocating is true, then changing the buffer's size won't reduce the
  27342. amount of memory that is currently allocated (but it will still increase it if
  27343. the new size is bigger than the amount it currently has). If this is false, then
  27344. a new allocation will be done so that the buffer uses takes up the minimum amount
  27345. of memory that it needs.
  27346. */
  27347. void setSize (int newNumChannels,
  27348. int newNumSamples,
  27349. bool keepExistingContent = false,
  27350. bool clearExtraSpace = false,
  27351. bool avoidReallocating = false) throw();
  27352. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  27353. There's also a constructor that lets you specify arrays like this, but this
  27354. lets you change the channels dynamically.
  27355. Note that if the buffer is resized or its number of channels is changed, it
  27356. will re-allocate memory internally and copy the existing data to this new area,
  27357. so it will then stop directly addressing this memory.
  27358. @param dataToReferTo a pre-allocated array containing pointers to the data
  27359. for each channel that should be used by this buffer. The
  27360. buffer will only refer to this memory, it won't try to delete
  27361. it when the buffer is deleted or resized.
  27362. @param numChannels the number of channels to use - this must correspond to the
  27363. number of elements in the array passed in
  27364. @param numSamples the number of samples to use - this must correspond to the
  27365. size of the arrays passed in
  27366. */
  27367. void setDataToReferTo (float** dataToReferTo,
  27368. int numChannels,
  27369. int numSamples) throw();
  27370. /** Clears all the samples in all channels. */
  27371. void clear() throw();
  27372. /** Clears a specified region of all the channels.
  27373. For speed, this doesn't check whether the channel and sample number
  27374. are in-range, so be careful!
  27375. */
  27376. void clear (int startSample,
  27377. int numSamples) throw();
  27378. /** Clears a specified region of just one channel.
  27379. For speed, this doesn't check whether the channel and sample number
  27380. are in-range, so be careful!
  27381. */
  27382. void clear (int channel,
  27383. int startSample,
  27384. int numSamples) throw();
  27385. /** Applies a gain multiple to a region of one channel.
  27386. For speed, this doesn't check whether the channel and sample number
  27387. are in-range, so be careful!
  27388. */
  27389. void applyGain (int channel,
  27390. int startSample,
  27391. int numSamples,
  27392. float gain) throw();
  27393. /** Applies a gain multiple to a region of all the channels.
  27394. For speed, this doesn't check whether the sample numbers
  27395. are in-range, so be careful!
  27396. */
  27397. void applyGain (int startSample,
  27398. int numSamples,
  27399. float gain) throw();
  27400. /** Applies a range of gains to a region of a channel.
  27401. The gain that is applied to each sample will vary from
  27402. startGain on the first sample to endGain on the last Sample,
  27403. so it can be used to do basic fades.
  27404. For speed, this doesn't check whether the sample numbers
  27405. are in-range, so be careful!
  27406. */
  27407. void applyGainRamp (int channel,
  27408. int startSample,
  27409. int numSamples,
  27410. float startGain,
  27411. float endGain) throw();
  27412. /** Adds samples from another buffer to this one.
  27413. @param destChannel the channel within this buffer to add the samples to
  27414. @param destStartSample the start sample within this buffer's channel
  27415. @param source the source buffer to add from
  27416. @param sourceChannel the channel within the source buffer to read from
  27417. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27418. @param numSamples the number of samples to process
  27419. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27420. added to this buffer's samples
  27421. @see copyFrom
  27422. */
  27423. void addFrom (int destChannel,
  27424. int destStartSample,
  27425. const AudioSampleBuffer& source,
  27426. int sourceChannel,
  27427. int sourceStartSample,
  27428. int numSamples,
  27429. float gainToApplyToSource = 1.0f) throw();
  27430. /** Adds samples from an array of floats to one of the channels.
  27431. @param destChannel the channel within this buffer to add the samples to
  27432. @param destStartSample the start sample within this buffer's channel
  27433. @param source the source data to use
  27434. @param numSamples the number of samples to process
  27435. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  27436. added to this buffer's samples
  27437. @see copyFrom
  27438. */
  27439. void addFrom (int destChannel,
  27440. int destStartSample,
  27441. const float* source,
  27442. int numSamples,
  27443. float gainToApplyToSource = 1.0f) throw();
  27444. /** Adds samples from an array of floats, applying a gain ramp to them.
  27445. @param destChannel the channel within this buffer to add the samples to
  27446. @param destStartSample the start sample within this buffer's channel
  27447. @param source the source data to use
  27448. @param numSamples the number of samples to process
  27449. @param startGain the gain to apply to the first sample (this is multiplied with
  27450. the source samples before they are added to this buffer)
  27451. @param endGain the gain to apply to the final sample. The gain is linearly
  27452. interpolated between the first and last samples.
  27453. */
  27454. void addFromWithRamp (int destChannel,
  27455. int destStartSample,
  27456. const float* source,
  27457. int numSamples,
  27458. float startGain,
  27459. float endGain) throw();
  27460. /** Copies samples from another buffer to this one.
  27461. @param destChannel the channel within this buffer to copy the samples to
  27462. @param destStartSample the start sample within this buffer's channel
  27463. @param source the source buffer to read from
  27464. @param sourceChannel the channel within the source buffer to read from
  27465. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27466. @param numSamples the number of samples to process
  27467. @see addFrom
  27468. */
  27469. void copyFrom (int destChannel,
  27470. int destStartSample,
  27471. const AudioSampleBuffer& source,
  27472. int sourceChannel,
  27473. int sourceStartSample,
  27474. int numSamples) throw();
  27475. /** Copies samples from an array of floats into one of the channels.
  27476. @param destChannel the channel within this buffer to copy the samples to
  27477. @param destStartSample the start sample within this buffer's channel
  27478. @param source the source buffer to read from
  27479. @param numSamples the number of samples to process
  27480. @see addFrom
  27481. */
  27482. void copyFrom (int destChannel,
  27483. int destStartSample,
  27484. const float* source,
  27485. int numSamples) throw();
  27486. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  27487. @param destChannel the channel within this buffer to copy the samples to
  27488. @param destStartSample the start sample within this buffer's channel
  27489. @param source the source buffer to read from
  27490. @param numSamples the number of samples to process
  27491. @param gain the gain to apply
  27492. @see addFrom
  27493. */
  27494. void copyFrom (int destChannel,
  27495. int destStartSample,
  27496. const float* source,
  27497. int numSamples,
  27498. float gain) throw();
  27499. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  27500. @param destChannel the channel within this buffer to copy the samples to
  27501. @param destStartSample the start sample within this buffer's channel
  27502. @param source the source buffer to read from
  27503. @param numSamples the number of samples to process
  27504. @param startGain the gain to apply to the first sample (this is multiplied with
  27505. the source samples before they are copied to this buffer)
  27506. @param endGain the gain to apply to the final sample. The gain is linearly
  27507. interpolated between the first and last samples.
  27508. @see addFrom
  27509. */
  27510. void copyFromWithRamp (int destChannel,
  27511. int destStartSample,
  27512. const float* source,
  27513. int numSamples,
  27514. float startGain,
  27515. float endGain) throw();
  27516. /** Finds the highest and lowest sample values in a given range.
  27517. @param channel the channel to read from
  27518. @param startSample the start sample within the channel
  27519. @param numSamples the number of samples to check
  27520. @param minVal on return, the lowest value that was found
  27521. @param maxVal on return, the highest value that was found
  27522. */
  27523. void findMinMax (int channel,
  27524. int startSample,
  27525. int numSamples,
  27526. float& minVal,
  27527. float& maxVal) const throw();
  27528. /** Finds the highest absolute sample value within a region of a channel.
  27529. */
  27530. float getMagnitude (int channel,
  27531. int startSample,
  27532. int numSamples) const throw();
  27533. /** Finds the highest absolute sample value within a region on all channels.
  27534. */
  27535. float getMagnitude (int startSample,
  27536. int numSamples) const throw();
  27537. /** Returns the root mean squared level for a region of a channel.
  27538. */
  27539. float getRMSLevel (int channel,
  27540. int startSample,
  27541. int numSamples) const throw();
  27542. /** Fills a section of the buffer using an AudioReader as its source.
  27543. This will convert the reader's fixed- or floating-point data to
  27544. the buffer's floating-point format, and will try to intelligently
  27545. cope with mismatches between the number of channels in the reader
  27546. and the buffer.
  27547. @see writeToAudioWriter
  27548. */
  27549. void readFromAudioReader (AudioFormatReader* reader,
  27550. int startSample,
  27551. int numSamples,
  27552. int64 readerStartSample,
  27553. bool useReaderLeftChan,
  27554. bool useReaderRightChan);
  27555. /** Writes a section of this buffer to an audio writer.
  27556. This saves you having to mess about with channels or floating/fixed
  27557. point conversion.
  27558. @see readFromAudioReader
  27559. */
  27560. void writeToAudioWriter (AudioFormatWriter* writer,
  27561. int startSample,
  27562. int numSamples) const;
  27563. private:
  27564. int numChannels, size;
  27565. size_t allocatedBytes;
  27566. float** channels;
  27567. HeapBlock <char> allocatedData;
  27568. float* preallocatedChannelSpace [32];
  27569. void allocateData();
  27570. void allocateChannels (float** dataToReferTo, int offset);
  27571. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  27572. };
  27573. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27574. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  27575. /**
  27576. Used by AudioSource::getNextAudioBlock().
  27577. */
  27578. struct JUCE_API AudioSourceChannelInfo
  27579. {
  27580. /** The destination buffer to fill with audio data.
  27581. When the AudioSource::getNextAudioBlock() method is called, the active section
  27582. of this buffer should be filled with whatever output the source produces.
  27583. Only the samples specified by the startSample and numSamples members of this structure
  27584. should be affected by the call.
  27585. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  27586. method can be treated as the input if the source is performing some kind of filter operation,
  27587. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  27588. a handy way of doing this.
  27589. The number of channels in the buffer could be anything, so the AudioSource
  27590. must cope with this in whatever way is appropriate for its function.
  27591. */
  27592. AudioSampleBuffer* buffer;
  27593. /** The first sample in the buffer from which the callback is expected
  27594. to write data. */
  27595. int startSample;
  27596. /** The number of samples in the buffer which the callback is expected to
  27597. fill with data. */
  27598. int numSamples;
  27599. /** Convenient method to clear the buffer if the source is not producing any data. */
  27600. void clearActiveBufferRegion() const
  27601. {
  27602. if (buffer != 0)
  27603. buffer->clear (startSample, numSamples);
  27604. }
  27605. };
  27606. /**
  27607. Base class for objects that can produce a continuous stream of audio.
  27608. An AudioSource has two states: 'prepared' and 'unprepared'.
  27609. When a source needs to be played, it is first put into a 'prepared' state by a call to
  27610. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  27611. process the audio data.
  27612. Once playback has finished, the releaseResources() method is called to put the stream
  27613. back into an 'unprepared' state.
  27614. @see AudioFormatReaderSource, ResamplingAudioSource
  27615. */
  27616. class JUCE_API AudioSource
  27617. {
  27618. protected:
  27619. /** Creates an AudioSource. */
  27620. AudioSource() throw() {}
  27621. public:
  27622. /** Destructor. */
  27623. virtual ~AudioSource() {}
  27624. /** Tells the source to prepare for playing.
  27625. An AudioSource has two states: prepared and unprepared.
  27626. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  27627. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  27628. This callback allows the source to initialise any resources it might need when playing.
  27629. Once playback has finished, the releaseResources() method is called to put the stream
  27630. back into an 'unprepared' state.
  27631. Note that this method could be called more than once in succession without
  27632. a matching call to releaseResources(), so make sure your code is robust and
  27633. can handle that kind of situation.
  27634. @param samplesPerBlockExpected the number of samples that the source
  27635. will be expected to supply each time its
  27636. getNextAudioBlock() method is called. This
  27637. number may vary slightly, because it will be dependent
  27638. on audio hardware callbacks, and these aren't
  27639. guaranteed to always use a constant block size, so
  27640. the source should be able to cope with small variations.
  27641. @param sampleRate the sample rate that the output will be used at - this
  27642. is needed by sources such as tone generators.
  27643. @see releaseResources, getNextAudioBlock
  27644. */
  27645. virtual void prepareToPlay (int samplesPerBlockExpected,
  27646. double sampleRate) = 0;
  27647. /** Allows the source to release anything it no longer needs after playback has stopped.
  27648. This will be called when the source is no longer going to have its getNextAudioBlock()
  27649. method called, so it should release any spare memory, etc. that it might have
  27650. allocated during the prepareToPlay() call.
  27651. Note that there's no guarantee that prepareToPlay() will actually have been called before
  27652. releaseResources(), and it may be called more than once in succession, so make sure your
  27653. code is robust and doesn't make any assumptions about when it will be called.
  27654. @see prepareToPlay, getNextAudioBlock
  27655. */
  27656. virtual void releaseResources() = 0;
  27657. /** Called repeatedly to fetch subsequent blocks of audio data.
  27658. After calling the prepareToPlay() method, this callback will be made each
  27659. time the audio playback hardware (or whatever other destination the audio
  27660. data is going to) needs another block of data.
  27661. It will generally be called on a high-priority system thread, or possibly even
  27662. an interrupt, so be careful not to do too much work here, as that will cause
  27663. audio glitches!
  27664. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  27665. */
  27666. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  27667. };
  27668. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  27669. /*** End of inlined file: juce_AudioSource.h ***/
  27670. class AudioThumbnail;
  27671. /**
  27672. Writes samples to an audio file stream.
  27673. A subclass that writes a specific type of audio format will be created by
  27674. an AudioFormat object.
  27675. After creating one of these with the AudioFormat::createWriterFor() method
  27676. you can call its write() method to store the samples, and then delete it.
  27677. @see AudioFormat, AudioFormatReader
  27678. */
  27679. class JUCE_API AudioFormatWriter
  27680. {
  27681. protected:
  27682. /** Creates an AudioFormatWriter object.
  27683. @param destStream the stream to write to - this will be deleted
  27684. by this object when it is no longer needed
  27685. @param formatName the description that will be returned by the getFormatName()
  27686. method
  27687. @param sampleRate the sample rate to use - the base class just stores
  27688. this value, it doesn't do anything with it
  27689. @param numberOfChannels the number of channels to write - the base class just stores
  27690. this value, it doesn't do anything with it
  27691. @param bitsPerSample the bit depth of the stream - the base class just stores
  27692. this value, it doesn't do anything with it
  27693. */
  27694. AudioFormatWriter (OutputStream* destStream,
  27695. const String& formatName,
  27696. double sampleRate,
  27697. unsigned int numberOfChannels,
  27698. unsigned int bitsPerSample);
  27699. public:
  27700. /** Destructor. */
  27701. virtual ~AudioFormatWriter();
  27702. /** Returns a description of what type of format this is.
  27703. E.g. "AIFF file"
  27704. */
  27705. const String getFormatName() const throw() { return formatName; }
  27706. /** Writes a set of samples to the audio stream.
  27707. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27708. can use AudioSampleBuffer::writeToAudioWriter().
  27709. @param samplesToWrite an array of arrays containing the sample data for
  27710. each channel to write. This is a zero-terminated
  27711. array of arrays, and can contain a different number
  27712. of channels than the actual stream uses, and the
  27713. writer should do its best to cope with this.
  27714. If the format is fixed-point, each channel will be formatted
  27715. as an array of signed integers using the full 32-bit
  27716. range -0x80000000 to 0x7fffffff, regardless of the source's
  27717. bit-depth. If it is a floating-point format, you should treat
  27718. the arrays as arrays of floats, and just cast it to an (int**)
  27719. to pass it into the method.
  27720. @param numSamples the number of samples to write
  27721. */
  27722. virtual bool write (const int** samplesToWrite,
  27723. int numSamples) = 0;
  27724. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27725. the output.
  27726. This will take care of any floating-point conversion that's required to convert
  27727. between the two formats. It won't deal with sample-rate conversion, though.
  27728. If numSamplesToRead < 0, it will write the entire length of the reader.
  27729. @returns false if it can't read or write properly during the operation
  27730. */
  27731. bool writeFromAudioReader (AudioFormatReader& reader,
  27732. int64 startSample,
  27733. int64 numSamplesToRead);
  27734. /** Reads some samples from an AudioSource, and writes these to the output.
  27735. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27736. @param source the source to read from
  27737. @param numSamplesToRead total number of samples to read and write
  27738. @param samplesPerBlock the maximum number of samples to fetch from the source
  27739. @returns false if it can't read or write properly during the operation
  27740. */
  27741. bool writeFromAudioSource (AudioSource& source,
  27742. int numSamplesToRead,
  27743. int samplesPerBlock = 2048);
  27744. /** Writes some samples from an AudioSampleBuffer.
  27745. */
  27746. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  27747. int startSample, int numSamples);
  27748. /** Returns the sample rate being used. */
  27749. double getSampleRate() const throw() { return sampleRate; }
  27750. /** Returns the number of channels being written. */
  27751. int getNumChannels() const throw() { return numChannels; }
  27752. /** Returns the bit-depth of the data being written. */
  27753. int getBitsPerSample() const throw() { return bitsPerSample; }
  27754. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27755. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  27756. /**
  27757. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  27758. data into a buffer which will be flushed to disk by a background thread.
  27759. */
  27760. class ThreadedWriter
  27761. {
  27762. public:
  27763. /** Creates a ThreadedWriter for a given writer and a thread.
  27764. The writer object which is passed in here will be owned and deleted by
  27765. the ThreadedWriter when it is no longer needed.
  27766. To stop the writer and flush the buffer to disk, simply delete this object.
  27767. */
  27768. ThreadedWriter (AudioFormatWriter* writer,
  27769. TimeSliceThread& backgroundThread,
  27770. int numSamplesToBuffer);
  27771. /** Destructor. */
  27772. ~ThreadedWriter();
  27773. /** Pushes some incoming audio data into the FIFO.
  27774. If there's enough free space in the buffer, this will add the data to it,
  27775. If the FIFO is too full to accept this many samples, the method will return
  27776. false - then you could either wait until the background thread has had time to
  27777. consume some of the buffered data and try again, or you can give up
  27778. and lost this block.
  27779. The data must be an array containing the same number of channels as the
  27780. AudioFormatWriter object is using. None of these channels can be null.
  27781. */
  27782. bool write (const float** data, int numSamples);
  27783. /** Allows you to specify a thumbnail that this writer should update with the
  27784. incoming data.
  27785. The thumbnail will be cleared and will the writer will begin adding data to
  27786. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  27787. */
  27788. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  27789. /** @internal */
  27790. class Buffer; // (only public for VC6 compatibility)
  27791. private:
  27792. friend class ScopedPointer<Buffer>;
  27793. ScopedPointer<Buffer> buffer;
  27794. };
  27795. protected:
  27796. /** The sample rate of the stream. */
  27797. double sampleRate;
  27798. /** The number of channels being written to the stream. */
  27799. unsigned int numChannels;
  27800. /** The bit depth of the file. */
  27801. unsigned int bitsPerSample;
  27802. /** True if it's a floating-point format, false if it's fixed-point. */
  27803. bool usesFloatingPointData;
  27804. /** The output stream for Use by subclasses. */
  27805. OutputStream* output;
  27806. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  27807. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  27808. struct WriteHelper
  27809. {
  27810. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  27811. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  27812. static void write (void* destData, int numDestChannels, const int** source,
  27813. int numSamples, const int sourceOffset = 0) throw()
  27814. {
  27815. for (int i = 0; i < numDestChannels; ++i)
  27816. {
  27817. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  27818. if (*source != 0)
  27819. {
  27820. dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
  27821. ++source;
  27822. }
  27823. else
  27824. {
  27825. dest.clearSamples (numSamples);
  27826. }
  27827. }
  27828. }
  27829. };
  27830. private:
  27831. String formatName;
  27832. friend class ThreadedWriter;
  27833. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  27834. };
  27835. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27836. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  27837. /**
  27838. Subclasses of AudioFormat are used to read and write different audio
  27839. file formats.
  27840. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27841. */
  27842. class JUCE_API AudioFormat
  27843. {
  27844. public:
  27845. /** Destructor. */
  27846. virtual ~AudioFormat();
  27847. /** Returns the name of this format.
  27848. e.g. "WAV file" or "AIFF file"
  27849. */
  27850. const String& getFormatName() const;
  27851. /** Returns all the file extensions that might apply to a file of this format.
  27852. The first item will be the one that's preferred when creating a new file.
  27853. So for a wav file this might just return ".wav"; for an AIFF file it might
  27854. return two items, ".aif" and ".aiff"
  27855. */
  27856. const StringArray& getFileExtensions() const;
  27857. /** Returns true if this the given file can be read by this format.
  27858. Subclasses shouldn't do too much work here, just check the extension or
  27859. file type. The base class implementation just checks the file's extension
  27860. against one of the ones that was registered in the constructor.
  27861. */
  27862. virtual bool canHandleFile (const File& fileToTest);
  27863. /** Returns a set of sample rates that the format can read and write. */
  27864. virtual const Array <int> getPossibleSampleRates() = 0;
  27865. /** Returns a set of bit depths that the format can read and write. */
  27866. virtual const Array <int> getPossibleBitDepths() = 0;
  27867. /** Returns true if the format can do 2-channel audio. */
  27868. virtual bool canDoStereo() = 0;
  27869. /** Returns true if the format can do 1-channel audio. */
  27870. virtual bool canDoMono() = 0;
  27871. /** Returns true if the format uses compressed data. */
  27872. virtual bool isCompressed();
  27873. /** Returns a list of different qualities that can be used when writing.
  27874. Non-compressed formats will just return an empty array, but for something
  27875. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27876. When calling createWriterFor(), an index from this array is passed in to
  27877. tell the format which option is required.
  27878. */
  27879. virtual const StringArray getQualityOptions();
  27880. /** Tries to create an object that can read from a stream containing audio
  27881. data in this format.
  27882. The reader object that is returned can be used to read from the stream, and
  27883. should then be deleted by the caller.
  27884. @param sourceStream the stream to read from - the AudioFormatReader object
  27885. that is returned will delete this stream when it no longer
  27886. needs it.
  27887. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27888. should delete the stream object that was passed-in. (If a valid
  27889. reader is returned, it will always be in charge of deleting the
  27890. stream, so this parameter is ignored)
  27891. @see AudioFormatReader
  27892. */
  27893. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27894. bool deleteStreamIfOpeningFails) = 0;
  27895. /** Tries to create an object that can write to a stream with this audio format.
  27896. The writer object that is returned can be used to write to the stream, and
  27897. should then be deleted by the caller.
  27898. If the stream can't be created for some reason (e.g. the parameters passed in
  27899. here aren't suitable), this will return 0.
  27900. @param streamToWriteTo the stream that the data will go to - this will be
  27901. deleted by the AudioFormatWriter object when it's no longer
  27902. needed. If no AudioFormatWriter can be created by this method,
  27903. the stream will NOT be deleted, so that the caller can re-use it
  27904. to try to open a different format, etc
  27905. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27906. returned by getPossibleSampleRates()
  27907. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27908. the choice will depend on the results of canDoMono() and
  27909. canDoStereo()
  27910. @param bitsPerSample the bits per sample to use - this must be one of the values
  27911. returned by getPossibleBitDepths()
  27912. @param metadataValues a set of metadata values that the writer should try to write
  27913. to the stream. Exactly what these are depends on the format,
  27914. and the subclass doesn't actually have to do anything with
  27915. them if it doesn't want to. Have a look at the specific format
  27916. implementation classes to see possible values that can be
  27917. used
  27918. @param qualityOptionIndex the index of one of compression qualities returned by the
  27919. getQualityOptions() method. If there aren't any quality options
  27920. for this format, just pass 0 in this parameter, as it'll be
  27921. ignored
  27922. @see AudioFormatWriter
  27923. */
  27924. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27925. double sampleRateToUse,
  27926. unsigned int numberOfChannels,
  27927. int bitsPerSample,
  27928. const StringPairArray& metadataValues,
  27929. int qualityOptionIndex) = 0;
  27930. protected:
  27931. /** Creates an AudioFormat object.
  27932. @param formatName this sets the value that will be returned by getFormatName()
  27933. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27934. be returned by getFileExtension()
  27935. */
  27936. AudioFormat (const String& formatName,
  27937. const StringArray& fileExtensions);
  27938. private:
  27939. String formatName;
  27940. StringArray fileExtensions;
  27941. };
  27942. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27943. /*** End of inlined file: juce_AudioFormat.h ***/
  27944. /**
  27945. Reads and Writes AIFF format audio files.
  27946. @see AudioFormat
  27947. */
  27948. class JUCE_API AiffAudioFormat : public AudioFormat
  27949. {
  27950. public:
  27951. /** Creates an format object. */
  27952. AiffAudioFormat();
  27953. /** Destructor. */
  27954. ~AiffAudioFormat();
  27955. const Array <int> getPossibleSampleRates();
  27956. const Array <int> getPossibleBitDepths();
  27957. bool canDoStereo();
  27958. bool canDoMono();
  27959. #if JUCE_MAC
  27960. bool canHandleFile (const File& fileToTest);
  27961. #endif
  27962. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27963. bool deleteStreamIfOpeningFails);
  27964. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27965. double sampleRateToUse,
  27966. unsigned int numberOfChannels,
  27967. int bitsPerSample,
  27968. const StringPairArray& metadataValues,
  27969. int qualityOptionIndex);
  27970. private:
  27971. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  27972. };
  27973. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27974. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  27975. #endif
  27976. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27977. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  27978. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27979. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27980. #if JUCE_USE_CDBURNER || DOXYGEN
  27981. /**
  27982. */
  27983. class AudioCDBurner : public ChangeBroadcaster
  27984. {
  27985. public:
  27986. /** Returns a list of available optical drives.
  27987. Use openDevice() to open one of the items from this list.
  27988. */
  27989. static const StringArray findAvailableDevices();
  27990. /** Tries to open one of the optical drives.
  27991. The deviceIndex is an index into the array returned by findAvailableDevices().
  27992. */
  27993. static AudioCDBurner* openDevice (const int deviceIndex);
  27994. /** Destructor. */
  27995. ~AudioCDBurner();
  27996. enum DiskState
  27997. {
  27998. unknown, /**< An error condition, if the device isn't responding. */
  27999. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  28000. may seem to be permanently open. */
  28001. noDisc, /**< The drive has no disk in it. */
  28002. writableDiskPresent, /**< The drive contains a writeable disk. */
  28003. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  28004. };
  28005. /** Returns the current status of the device.
  28006. To get informed when the drive's status changes, attach a ChangeListener to
  28007. the AudioCDBurner.
  28008. */
  28009. DiskState getDiskState() const;
  28010. /** Returns true if there's a writable disk in the drive. */
  28011. bool isDiskPresent() const;
  28012. /** Sends an eject signal to the drive.
  28013. The eject will happen asynchronously, so you can use getDiskState() and
  28014. waitUntilStateChange() to monitor its progress.
  28015. */
  28016. bool openTray();
  28017. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  28018. @returns the device's new state
  28019. */
  28020. DiskState waitUntilStateChange (int timeOutMilliseconds);
  28021. /** Returns the set of possible write speeds that the device can handle.
  28022. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  28023. Note that if there's no media present in the drive, this value may be unavailable!
  28024. @see setWriteSpeed, getWriteSpeed
  28025. */
  28026. const Array<int> getAvailableWriteSpeeds() const;
  28027. /** Tries to enable or disable buffer underrun safety on devices that support it.
  28028. @returns true if it's now enabled. If the device doesn't support it, this
  28029. will always return false.
  28030. */
  28031. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  28032. /** Returns the number of free blocks on the disk.
  28033. There are 75 blocks per second, at 44100Hz.
  28034. */
  28035. int getNumAvailableAudioBlocks() const;
  28036. /** Adds a track to be written.
  28037. The source passed-in here will be kept by this object, and it will
  28038. be used and deleted at some point in the future, either during the
  28039. burn() method or when this AudioCDBurner object is deleted. Your caller
  28040. method shouldn't keep a reference to it or use it again after passing
  28041. it in here.
  28042. */
  28043. bool addAudioTrack (AudioSource* source, int numSamples);
  28044. /** Receives progress callbacks during a cd-burn operation.
  28045. @see AudioCDBurner::burn()
  28046. */
  28047. class BurnProgressListener
  28048. {
  28049. public:
  28050. BurnProgressListener() throw() {}
  28051. virtual ~BurnProgressListener() {}
  28052. /** Called at intervals to report on the progress of the AudioCDBurner.
  28053. To cancel the burn, return true from this method.
  28054. */
  28055. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  28056. };
  28057. /** Runs the burn process.
  28058. This method will block until the operation is complete.
  28059. @param listener the object to receive callbacks about progress
  28060. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  28061. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  28062. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  28063. 0 or less to mean the fastest speed.
  28064. */
  28065. const String burn (BurnProgressListener* listener,
  28066. bool ejectDiscAfterwards,
  28067. bool performFakeBurnForTesting,
  28068. int writeSpeed);
  28069. /** If a burn operation is currently in progress, this tells it to stop
  28070. as soon as possible.
  28071. It's also possible to stop the burn process by returning true from
  28072. BurnProgressListener::audioCDBurnProgress()
  28073. */
  28074. void abortBurn();
  28075. private:
  28076. AudioCDBurner (const int deviceIndex);
  28077. class Pimpl;
  28078. friend class ScopedPointer<Pimpl>;
  28079. ScopedPointer<Pimpl> pimpl;
  28080. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  28081. };
  28082. #endif
  28083. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  28084. /*** End of inlined file: juce_AudioCDBurner.h ***/
  28085. #endif
  28086. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28087. /*** Start of inlined file: juce_AudioCDReader.h ***/
  28088. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  28089. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  28090. #if JUCE_USE_CDREADER || DOXYGEN
  28091. #if JUCE_MAC
  28092. #endif
  28093. /**
  28094. A type of AudioFormatReader that reads from an audio CD.
  28095. One of these can be used to read a CD as if it's one big audio stream. Use the
  28096. getPositionOfTrackStart() method to find where the individual tracks are
  28097. within the stream.
  28098. @see AudioFormatReader
  28099. */
  28100. class JUCE_API AudioCDReader : public AudioFormatReader
  28101. {
  28102. public:
  28103. /** Returns a list of names of Audio CDs currently available for reading.
  28104. If there's a CD drive but no CD in it, this might return an empty list, or
  28105. possibly a device that can be opened but which has no tracks, depending
  28106. on the platform.
  28107. @see createReaderForCD
  28108. */
  28109. static const StringArray getAvailableCDNames();
  28110. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  28111. @param index the index of one of the available CDs - use getAvailableCDNames()
  28112. to find out how many there are.
  28113. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  28114. caller will be responsible for deleting the object returned.
  28115. */
  28116. static AudioCDReader* createReaderForCD (const int index);
  28117. /** Destructor. */
  28118. ~AudioCDReader();
  28119. /** Implementation of the AudioFormatReader method. */
  28120. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28121. int64 startSampleInFile, int numSamples);
  28122. /** Checks whether the CD has been removed from the drive.
  28123. */
  28124. bool isCDStillPresent() const;
  28125. /** Returns the total number of tracks (audio + data).
  28126. */
  28127. int getNumTracks() const;
  28128. /** Finds the sample offset of the start of a track.
  28129. @param trackNum the track number, where trackNum = 0 is the first track
  28130. and trackNum = getNumTracks() means the end of the CD.
  28131. */
  28132. int getPositionOfTrackStart (int trackNum) const;
  28133. /** Returns true if a given track is an audio track.
  28134. @param trackNum the track number, where 0 is the first track.
  28135. */
  28136. bool isTrackAudio (int trackNum) const;
  28137. /** Returns an array of sample offsets for the start of each track, followed by
  28138. the sample position of the end of the CD.
  28139. */
  28140. const Array<int>& getTrackOffsets() const;
  28141. /** Refreshes the object's table of contents.
  28142. If the disc has been ejected and a different one put in since this
  28143. object was created, this will cause it to update its idea of how many tracks
  28144. there are, etc.
  28145. */
  28146. void refreshTrackLengths();
  28147. /** Enables scanning for indexes within tracks.
  28148. @see getLastIndex
  28149. */
  28150. void enableIndexScanning (bool enabled);
  28151. /** Returns the index number found during the last read() call.
  28152. Index scanning is turned off by default - turn it on with enableIndexScanning().
  28153. Then when the read() method is called, if it comes across an index within that
  28154. block, the index number is stored and returned by this method.
  28155. Some devices might not support indexes, of course.
  28156. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  28157. @see enableIndexScanning
  28158. */
  28159. int getLastIndex() const;
  28160. /** Scans a track to find the position of any indexes within it.
  28161. @param trackNumber the track to look in, where 0 is the first track on the disc
  28162. @returns an array of sample positions of any index points found (not including
  28163. the index that marks the start of the track)
  28164. */
  28165. const Array <int> findIndexesInTrack (const int trackNumber);
  28166. /** Returns the CDDB id number for the CD.
  28167. It's not a great way of identifying a disc, but it's traditional.
  28168. */
  28169. int getCDDBId();
  28170. /** Tries to eject the disk.
  28171. Of course this might not be possible, if some other process is using it.
  28172. */
  28173. void ejectDisk();
  28174. enum
  28175. {
  28176. framesPerSecond = 75,
  28177. samplesPerFrame = 44100 / framesPerSecond
  28178. };
  28179. private:
  28180. Array<int> trackStartSamples;
  28181. #if JUCE_MAC
  28182. File volumeDir;
  28183. Array<File> tracks;
  28184. int currentReaderTrack;
  28185. ScopedPointer <AudioFormatReader> reader;
  28186. AudioCDReader (const File& volume);
  28187. #elif JUCE_WINDOWS
  28188. bool audioTracks [100];
  28189. void* handle;
  28190. bool indexingEnabled;
  28191. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  28192. MemoryBlock buffer;
  28193. AudioCDReader (void* handle);
  28194. int getIndexAt (int samplePos);
  28195. #elif JUCE_LINUX
  28196. AudioCDReader();
  28197. #endif
  28198. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  28199. };
  28200. #endif
  28201. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  28202. /*** End of inlined file: juce_AudioCDReader.h ***/
  28203. #endif
  28204. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  28205. #endif
  28206. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28207. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  28208. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28209. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28210. /**
  28211. A class for keeping a list of available audio formats, and for deciding which
  28212. one to use to open a given file.
  28213. You can either use this class as a singleton object, or create instances of it
  28214. yourself. Once created, use its registerFormat() method to tell it which
  28215. formats it should use.
  28216. @see AudioFormat
  28217. */
  28218. class JUCE_API AudioFormatManager
  28219. {
  28220. public:
  28221. /** Creates an empty format manager.
  28222. Before it'll be any use, you'll need to call registerFormat() with all the
  28223. formats you want it to be able to recognise.
  28224. */
  28225. AudioFormatManager();
  28226. /** Destructor. */
  28227. ~AudioFormatManager();
  28228. /** Adds a format to the manager's list of available file types.
  28229. The object passed-in will be deleted by this object, so don't keep a pointer
  28230. to it!
  28231. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  28232. return this one when called.
  28233. */
  28234. void registerFormat (AudioFormat* newFormat,
  28235. bool makeThisTheDefaultFormat);
  28236. /** Handy method to make it easy to register the formats that come with Juce.
  28237. Currently, this will add WAV and AIFF to the list.
  28238. */
  28239. void registerBasicFormats();
  28240. /** Clears the list of known formats. */
  28241. void clearFormats();
  28242. /** Returns the number of currently registered file formats. */
  28243. int getNumKnownFormats() const;
  28244. /** Returns one of the registered file formats. */
  28245. AudioFormat* getKnownFormat (int index) const;
  28246. /** Looks for which of the known formats is listed as being for a given file
  28247. extension.
  28248. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  28249. */
  28250. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  28251. /** Returns the format which has been set as the default one.
  28252. You can set a format as being the default when it is registered. It's useful
  28253. when you want to write to a file, because the best format may change between
  28254. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  28255. If none has been set as the default, this method will just return the first
  28256. one in the list.
  28257. */
  28258. AudioFormat* getDefaultFormat() const;
  28259. /** Returns a set of wildcards for file-matching that contains the extensions for
  28260. all known formats.
  28261. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  28262. */
  28263. const String getWildcardForAllFormats() const;
  28264. /** Searches through the known formats to try to create a suitable reader for
  28265. this file.
  28266. If none of the registered formats can open the file, it'll return 0. If it
  28267. returns a reader, it's the caller's responsibility to delete the reader.
  28268. */
  28269. AudioFormatReader* createReaderFor (const File& audioFile);
  28270. /** Searches through the known formats to try to create a suitable reader for
  28271. this stream.
  28272. The stream object that is passed-in will be deleted by this method or by the
  28273. reader that is returned, so the caller should not keep any references to it.
  28274. The stream that is passed-in must be capable of being repositioned so
  28275. that all the formats can have a go at opening it.
  28276. If none of the registered formats can open the stream, it'll return 0. If it
  28277. returns a reader, it's the caller's responsibility to delete the reader.
  28278. */
  28279. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  28280. private:
  28281. OwnedArray<AudioFormat> knownFormats;
  28282. int defaultFormatIndex;
  28283. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  28284. };
  28285. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  28286. /*** End of inlined file: juce_AudioFormatManager.h ***/
  28287. #endif
  28288. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  28289. #endif
  28290. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  28291. #endif
  28292. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28293. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  28294. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28295. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28296. /**
  28297. This class is used to wrap an AudioFormatReader and only read from a
  28298. subsection of the file.
  28299. So if you have a reader which can read a 1000 sample file, you could wrap it
  28300. in one of these to only access, e.g. samples 100 to 200, and any samples
  28301. outside that will come back as 0. Accessing sample 0 from this reader will
  28302. actually read the first sample from the other's subsection, which might
  28303. be at a non-zero position.
  28304. @see AudioFormatReader
  28305. */
  28306. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28307. {
  28308. public:
  28309. /** Creates a AudioSubsectionReader for a given data source.
  28310. @param sourceReader the source reader from which we'll be taking data
  28311. @param subsectionStartSample the sample within the source reader which will be
  28312. mapped onto sample 0 for this reader.
  28313. @param subsectionLength the number of samples from the source that will
  28314. make up the subsection. If this reader is asked for
  28315. any samples beyond this region, it will return zero.
  28316. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28317. this object is deleted.
  28318. */
  28319. AudioSubsectionReader (AudioFormatReader* sourceReader,
  28320. int64 subsectionStartSample,
  28321. int64 subsectionLength,
  28322. bool deleteSourceWhenDeleted);
  28323. /** Destructor. */
  28324. ~AudioSubsectionReader();
  28325. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28326. int64 startSampleInFile, int numSamples);
  28327. void readMaxLevels (int64 startSample,
  28328. int64 numSamples,
  28329. float& lowestLeft,
  28330. float& highestLeft,
  28331. float& lowestRight,
  28332. float& highestRight);
  28333. private:
  28334. AudioFormatReader* const source;
  28335. int64 startSample, length;
  28336. const bool deleteSourceWhenDeleted;
  28337. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  28338. };
  28339. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28340. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  28341. #endif
  28342. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28343. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  28344. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28345. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28346. class AudioThumbnailCache;
  28347. /**
  28348. Makes it easy to quickly draw scaled views of the waveform shape of an
  28349. audio file.
  28350. To use this class, just create an AudioThumbNail class for the file you want
  28351. to draw, call setSource to tell it which file or resource to use, then call
  28352. drawChannel() to draw it.
  28353. The class will asynchronously scan the wavefile to create its scaled-down view,
  28354. so you should make your UI repaint itself as this data comes in. To do this, the
  28355. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  28356. listeners should repaint themselves.
  28357. The thumbnail stores an internal low-res version of the wave data, and this can
  28358. be loaded and saved to avoid having to scan the file again.
  28359. @see AudioThumbnailCache
  28360. */
  28361. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  28362. {
  28363. public:
  28364. /** Creates an audio thumbnail.
  28365. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  28366. of the audio data, this is the scale at which it should be done. (This
  28367. number is the number of original samples that will be averaged for each
  28368. low-res sample)
  28369. @param formatManagerToUse the audio format manager that is used to open the file
  28370. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  28371. thread and storage that is used to by the thumbnail, and the cache
  28372. object can be shared between multiple thumbnails
  28373. */
  28374. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  28375. AudioFormatManager& formatManagerToUse,
  28376. AudioThumbnailCache& cacheToUse);
  28377. /** Destructor. */
  28378. ~AudioThumbnail();
  28379. /** Clears and resets the thumbnail. */
  28380. void clear();
  28381. /** Specifies the file or stream that contains the audio file.
  28382. For a file, just call
  28383. @code
  28384. setSource (new FileInputSource (file))
  28385. @endcode
  28386. You can pass a zero in here to clear the thumbnail.
  28387. The source that is passed in will be deleted by this object when it is no longer needed.
  28388. @returns true if the source could be opened as a valid audio file, false if this failed for
  28389. some reason.
  28390. */
  28391. bool setSource (InputSource* newSource);
  28392. /** Gives the thumbnail an AudioFormatReader to use directly.
  28393. This will start parsing the audio in a background thread (unless the hash code
  28394. can be looked-up successfully in the thumbnail cache). Note that the reader
  28395. object will be held by the thumbnail and deleted later when no longer needed.
  28396. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  28397. or change the input source, so the file will be held open for all this time. If
  28398. you don't want the thumbnail to keep a file handle open continuously, you
  28399. should use the setSource() method instead, which will only open the file when
  28400. it needs to.
  28401. */
  28402. void setReader (AudioFormatReader* newReader, int64 hashCode);
  28403. /** Resets the thumbnail, ready for adding data with the specified format.
  28404. If you're going to generate a thumbnail yourself, call this before using addBlock()
  28405. to add the data.
  28406. */
  28407. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  28408. /** Adds a block of level data to the thumbnail.
  28409. Call reset() before using this, to tell the thumbnail about the data format.
  28410. */
  28411. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  28412. int startOffsetInBuffer, int numSamples);
  28413. /** Reloads the low res thumbnail data from an input stream.
  28414. This is not an audio file stream! It takes a stream of thumbnail data that would
  28415. previously have been created by the saveTo() method.
  28416. @see saveTo
  28417. */
  28418. void loadFrom (InputStream& input);
  28419. /** Saves the low res thumbnail data to an output stream.
  28420. The data that is written can later be reloaded using loadFrom().
  28421. @see loadFrom
  28422. */
  28423. void saveTo (OutputStream& output) const;
  28424. /** Returns the number of channels in the file. */
  28425. int getNumChannels() const throw();
  28426. /** Returns the length of the audio file, in seconds. */
  28427. double getTotalLength() const throw();
  28428. /** Draws the waveform for a channel.
  28429. The waveform will be drawn within the specified rectangle, where startTime
  28430. and endTime specify the times within the audio file that should be positioned
  28431. at the left and right edges of the rectangle.
  28432. The waveform will be scaled vertically so that a full-volume sample will fill
  28433. the rectangle vertically, but you can also specify an extra vertical scale factor
  28434. with the verticalZoomFactor parameter.
  28435. */
  28436. void drawChannel (Graphics& g,
  28437. const Rectangle<int>& area,
  28438. double startTimeSeconds,
  28439. double endTimeSeconds,
  28440. int channelNum,
  28441. float verticalZoomFactor);
  28442. /** Draws the waveforms for all channels in the thumbnail.
  28443. This will call drawChannel() to render each of the thumbnail's channels, stacked
  28444. above each other within the specified area.
  28445. @see drawChannel
  28446. */
  28447. void drawChannels (Graphics& g,
  28448. const Rectangle<int>& area,
  28449. double startTimeSeconds,
  28450. double endTimeSeconds,
  28451. float verticalZoomFactor);
  28452. /** Returns true if the low res preview is fully generated. */
  28453. bool isFullyLoaded() const throw();
  28454. /** Returns the number of samples that have been set in the thumbnail. */
  28455. int64 getNumSamplesFinished() const throw();
  28456. /** Returns the highest level in the thumbnail.
  28457. Note that because the thumb only stores low-resolution data, this isn't
  28458. an accurate representation of the highest value, it's only a rough approximation.
  28459. */
  28460. float getApproximatePeak() const;
  28461. /** Returns the hash code that was set by setSource() or setReader(). */
  28462. int64 getHashCode() const;
  28463. #ifndef DOXYGEN
  28464. // (this is only public to avoid a VC6 bug)
  28465. class LevelDataSource;
  28466. #endif
  28467. private:
  28468. AudioFormatManager& formatManagerToUse;
  28469. AudioThumbnailCache& cache;
  28470. struct MinMaxValue;
  28471. class ThumbData;
  28472. class CachedWindow;
  28473. friend class LevelDataSource;
  28474. friend class ScopedPointer<LevelDataSource>;
  28475. friend class ThumbData;
  28476. friend class OwnedArray<ThumbData>;
  28477. friend class CachedWindow;
  28478. friend class ScopedPointer<CachedWindow>;
  28479. ScopedPointer<LevelDataSource> source;
  28480. ScopedPointer<CachedWindow> window;
  28481. OwnedArray<ThumbData> channels;
  28482. int32 samplesPerThumbSample;
  28483. int64 totalSamples, numSamplesFinished;
  28484. int32 numChannels;
  28485. double sampleRate;
  28486. CriticalSection lock;
  28487. bool setDataSource (LevelDataSource* newSource);
  28488. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  28489. void createChannels (int length);
  28490. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  28491. };
  28492. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28493. /*** End of inlined file: juce_AudioThumbnail.h ***/
  28494. #endif
  28495. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28496. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  28497. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28498. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28499. struct ThumbnailCacheEntry;
  28500. /**
  28501. An instance of this class is used to manage multiple AudioThumbnail objects.
  28502. The cache runs a single background thread that is shared by all the thumbnails
  28503. that need it, and it maintains a set of low-res previews in memory, to avoid
  28504. having to re-scan audio files too often.
  28505. @see AudioThumbnail
  28506. */
  28507. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28508. {
  28509. public:
  28510. /** Creates a cache object.
  28511. The maxNumThumbsToStore parameter lets you specify how many previews should
  28512. be kept in memory at once.
  28513. */
  28514. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  28515. /** Destructor. */
  28516. ~AudioThumbnailCache();
  28517. /** Clears out any stored thumbnails.
  28518. */
  28519. void clear();
  28520. /** Reloads the specified thumb if this cache contains the appropriate stored
  28521. data.
  28522. This is called automatically by the AudioThumbnail class, so you shouldn't
  28523. normally need to call it directly.
  28524. */
  28525. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  28526. /** Stores the cachable data from the specified thumb in this cache.
  28527. This is called automatically by the AudioThumbnail class, so you shouldn't
  28528. normally need to call it directly.
  28529. */
  28530. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  28531. private:
  28532. OwnedArray <ThumbnailCacheEntry> thumbs;
  28533. int maxNumThumbsToStore;
  28534. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  28535. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  28536. };
  28537. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28538. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  28539. #endif
  28540. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28541. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  28542. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28543. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28544. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28545. /**
  28546. Reads and writes the lossless-compression FLAC audio format.
  28547. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28548. and make sure your include search path and library search path are set up to find
  28549. the FLAC header files and static libraries.
  28550. @see AudioFormat
  28551. */
  28552. class JUCE_API FlacAudioFormat : public AudioFormat
  28553. {
  28554. public:
  28555. FlacAudioFormat();
  28556. ~FlacAudioFormat();
  28557. const Array <int> getPossibleSampleRates();
  28558. const Array <int> getPossibleBitDepths();
  28559. bool canDoStereo();
  28560. bool canDoMono();
  28561. bool isCompressed();
  28562. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28563. bool deleteStreamIfOpeningFails);
  28564. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28565. double sampleRateToUse,
  28566. unsigned int numberOfChannels,
  28567. int bitsPerSample,
  28568. const StringPairArray& metadataValues,
  28569. int qualityOptionIndex);
  28570. private:
  28571. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  28572. };
  28573. #endif
  28574. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28575. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  28576. #endif
  28577. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28578. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  28579. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28580. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28581. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28582. /**
  28583. Reads and writes the Ogg-Vorbis audio format.
  28584. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28585. and make sure your include search path and library search path are set up to find
  28586. the Vorbis and Ogg header files and static libraries.
  28587. @see AudioFormat,
  28588. */
  28589. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28590. {
  28591. public:
  28592. OggVorbisAudioFormat();
  28593. ~OggVorbisAudioFormat();
  28594. const Array <int> getPossibleSampleRates();
  28595. const Array <int> getPossibleBitDepths();
  28596. bool canDoStereo();
  28597. bool canDoMono();
  28598. bool isCompressed();
  28599. const StringArray getQualityOptions();
  28600. /** Tries to estimate the quality level of an ogg file based on its size.
  28601. If it can't read the file for some reason, this will just return 1 (medium quality),
  28602. otherwise it will return the approximate quality setting that would have been used
  28603. to create the file.
  28604. @see getQualityOptions
  28605. */
  28606. int estimateOggFileQuality (const File& source);
  28607. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28608. bool deleteStreamIfOpeningFails);
  28609. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28610. double sampleRateToUse,
  28611. unsigned int numberOfChannels,
  28612. int bitsPerSample,
  28613. const StringPairArray& metadataValues,
  28614. int qualityOptionIndex);
  28615. private:
  28616. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  28617. };
  28618. #endif
  28619. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28620. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  28621. #endif
  28622. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28623. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  28624. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28625. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28626. #if JUCE_QUICKTIME
  28627. /**
  28628. Uses QuickTime to read the audio track a movie or media file.
  28629. As well as QuickTime movies, this should also manage to open other audio
  28630. files that quicktime can understand, like mp3, m4a, etc.
  28631. @see AudioFormat
  28632. */
  28633. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28634. {
  28635. public:
  28636. /** Creates a format object. */
  28637. QuickTimeAudioFormat();
  28638. /** Destructor. */
  28639. ~QuickTimeAudioFormat();
  28640. const Array <int> getPossibleSampleRates();
  28641. const Array <int> getPossibleBitDepths();
  28642. bool canDoStereo();
  28643. bool canDoMono();
  28644. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28645. bool deleteStreamIfOpeningFails);
  28646. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28647. double sampleRateToUse,
  28648. unsigned int numberOfChannels,
  28649. int bitsPerSample,
  28650. const StringPairArray& metadataValues,
  28651. int qualityOptionIndex);
  28652. private:
  28653. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  28654. };
  28655. #endif
  28656. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28657. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  28658. #endif
  28659. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28660. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  28661. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28662. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28663. /**
  28664. Reads and Writes WAV format audio files.
  28665. @see AudioFormat
  28666. */
  28667. class JUCE_API WavAudioFormat : public AudioFormat
  28668. {
  28669. public:
  28670. /** Creates a format object. */
  28671. WavAudioFormat();
  28672. /** Destructor. */
  28673. ~WavAudioFormat();
  28674. /** Metadata property name used by wav readers and writers for adding
  28675. a BWAV chunk to the file.
  28676. @see AudioFormatReader::metadataValues, createWriterFor
  28677. */
  28678. static const char* const bwavDescription;
  28679. /** Metadata property name used by wav readers and writers for adding
  28680. a BWAV chunk to the file.
  28681. @see AudioFormatReader::metadataValues, createWriterFor
  28682. */
  28683. static const char* const bwavOriginator;
  28684. /** Metadata property name used by wav readers and writers for adding
  28685. a BWAV chunk to the file.
  28686. @see AudioFormatReader::metadataValues, createWriterFor
  28687. */
  28688. static const char* const bwavOriginatorRef;
  28689. /** Metadata property name used by wav readers and writers for adding
  28690. a BWAV chunk to the file.
  28691. Date format is: yyyy-mm-dd
  28692. @see AudioFormatReader::metadataValues, createWriterFor
  28693. */
  28694. static const char* const bwavOriginationDate;
  28695. /** Metadata property name used by wav readers and writers for adding
  28696. a BWAV chunk to the file.
  28697. Time format is: hh-mm-ss
  28698. @see AudioFormatReader::metadataValues, createWriterFor
  28699. */
  28700. static const char* const bwavOriginationTime;
  28701. /** Metadata property name used by wav readers and writers for adding
  28702. a BWAV chunk to the file.
  28703. This is the number of samples from the start of an edit that the
  28704. file is supposed to begin at. Seems like an obvious mistake to
  28705. only allow a file to occur in an edit once, but that's the way
  28706. it is..
  28707. @see AudioFormatReader::metadataValues, createWriterFor
  28708. */
  28709. static const char* const bwavTimeReference;
  28710. /** Metadata property name used by wav readers and writers for adding
  28711. a BWAV chunk to the file.
  28712. This is a
  28713. @see AudioFormatReader::metadataValues, createWriterFor
  28714. */
  28715. static const char* const bwavCodingHistory;
  28716. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28717. This just makes it easier than using the property names directly, and it
  28718. fills out the time and date in the right format.
  28719. */
  28720. static const StringPairArray createBWAVMetadata (const String& description,
  28721. const String& originator,
  28722. const String& originatorRef,
  28723. const Time& dateAndTime,
  28724. const int64 timeReferenceSamples,
  28725. const String& codingHistory);
  28726. const Array <int> getPossibleSampleRates();
  28727. const Array <int> getPossibleBitDepths();
  28728. bool canDoStereo();
  28729. bool canDoMono();
  28730. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28731. bool deleteStreamIfOpeningFails);
  28732. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28733. double sampleRateToUse,
  28734. unsigned int numberOfChannels,
  28735. int bitsPerSample,
  28736. const StringPairArray& metadataValues,
  28737. int qualityOptionIndex);
  28738. /** Utility function to replace the metadata in a wav file with a new set of values.
  28739. If possible, this cheats by overwriting just the metadata region of the file, rather
  28740. than by copying the whole file again.
  28741. */
  28742. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28743. private:
  28744. JUCE_LEAK_DETECTOR (WavAudioFormat);
  28745. };
  28746. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28747. /*** End of inlined file: juce_WavAudioFormat.h ***/
  28748. #endif
  28749. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28750. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  28751. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28752. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28753. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  28754. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28755. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28756. /**
  28757. A type of AudioSource which can be repositioned.
  28758. The basic AudioSource just streams continuously with no idea of a current
  28759. time or length, so the PositionableAudioSource is used for a finite stream
  28760. that has a current read position.
  28761. @see AudioSource, AudioTransportSource
  28762. */
  28763. class JUCE_API PositionableAudioSource : public AudioSource
  28764. {
  28765. protected:
  28766. /** Creates the PositionableAudioSource. */
  28767. PositionableAudioSource() throw() {}
  28768. public:
  28769. /** Destructor */
  28770. ~PositionableAudioSource() {}
  28771. /** Tells the stream to move to a new position.
  28772. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  28773. should return samples from this position.
  28774. Note that this may be called on a different thread to getNextAudioBlock(),
  28775. so the subclass should make sure it's synchronised.
  28776. */
  28777. virtual void setNextReadPosition (int64 newPosition) = 0;
  28778. /** Returns the position from which the next block will be returned.
  28779. @see setNextReadPosition
  28780. */
  28781. virtual int64 getNextReadPosition() const = 0;
  28782. /** Returns the total length of the stream (in samples). */
  28783. virtual int64 getTotalLength() const = 0;
  28784. /** Returns true if this source is actually playing in a loop. */
  28785. virtual bool isLooping() const = 0;
  28786. /** Tells the source whether you'd like it to play in a loop. */
  28787. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  28788. };
  28789. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28790. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  28791. /**
  28792. A type of AudioSource that will read from an AudioFormatReader.
  28793. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  28794. */
  28795. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  28796. {
  28797. public:
  28798. /** Creates an AudioFormatReaderSource for a given reader.
  28799. @param sourceReader the reader to use as the data source
  28800. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  28801. when this object is deleted; if false it will be
  28802. left up to the caller to manage its lifetime
  28803. */
  28804. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  28805. bool deleteReaderWhenThisIsDeleted);
  28806. /** Destructor. */
  28807. ~AudioFormatReaderSource();
  28808. /** Toggles loop-mode.
  28809. If set to true, it will continuously loop the input source. If false,
  28810. it will just emit silence after the source has finished.
  28811. @see isLooping
  28812. */
  28813. void setLooping (bool shouldLoop);
  28814. /** Returns whether loop-mode is turned on or not. */
  28815. bool isLooping() const { return looping; }
  28816. /** Returns the reader that's being used. */
  28817. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  28818. /** Implementation of the AudioSource method. */
  28819. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28820. /** Implementation of the AudioSource method. */
  28821. void releaseResources();
  28822. /** Implementation of the AudioSource method. */
  28823. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28824. /** Implements the PositionableAudioSource method. */
  28825. void setNextReadPosition (int64 newPosition);
  28826. /** Implements the PositionableAudioSource method. */
  28827. int64 getNextReadPosition() const;
  28828. /** Implements the PositionableAudioSource method. */
  28829. int64 getTotalLength() const;
  28830. private:
  28831. AudioFormatReader* reader;
  28832. bool deleteReader;
  28833. int64 volatile nextPlayPos;
  28834. bool volatile looping;
  28835. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  28836. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  28837. };
  28838. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28839. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  28840. #endif
  28841. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  28842. #endif
  28843. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28844. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  28845. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28846. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28847. /*** Start of inlined file: juce_AudioIODevice.h ***/
  28848. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28849. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28850. class AudioIODevice;
  28851. /**
  28852. One of these is passed to an AudioIODevice object to stream the audio data
  28853. in and out.
  28854. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  28855. method on its own high-priority audio thread, when it needs to send or receive
  28856. the next block of data.
  28857. @see AudioIODevice, AudioDeviceManager
  28858. */
  28859. class JUCE_API AudioIODeviceCallback
  28860. {
  28861. public:
  28862. /** Destructor. */
  28863. virtual ~AudioIODeviceCallback() {}
  28864. /** Processes a block of incoming and outgoing audio data.
  28865. The subclass's implementation should use the incoming audio for whatever
  28866. purposes it needs to, and must fill all the output channels with the next
  28867. block of output data before returning.
  28868. The channel data is arranged with the same array indices as the channel name
  28869. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  28870. that aren't specified in AudioIODevice::open() will have a null pointer for their
  28871. associated channel, so remember to check for this.
  28872. @param inputChannelData a set of arrays containing the audio data for each
  28873. incoming channel - this data is valid until the function
  28874. returns. There will be one channel of data for each input
  28875. channel that was enabled when the audio device was opened
  28876. (see AudioIODevice::open())
  28877. @param numInputChannels the number of pointers to channel data in the
  28878. inputChannelData array.
  28879. @param outputChannelData a set of arrays which need to be filled with the data
  28880. that should be sent to each outgoing channel of the device.
  28881. There will be one channel of data for each output channel
  28882. that was enabled when the audio device was opened (see
  28883. AudioIODevice::open())
  28884. The initial contents of the array is undefined, so the
  28885. callback function must fill all the channels with zeros if
  28886. its output is silence. Failing to do this could cause quite
  28887. an unpleasant noise!
  28888. @param numOutputChannels the number of pointers to channel data in the
  28889. outputChannelData array.
  28890. @param numSamples the number of samples in each channel of the input and
  28891. output arrays. The number of samples will depend on the
  28892. audio device's buffer size and will usually remain constant,
  28893. although this isn't guaranteed, so make sure your code can
  28894. cope with reasonable changes in the buffer size from one
  28895. callback to the next.
  28896. */
  28897. virtual void audioDeviceIOCallback (const float** inputChannelData,
  28898. int numInputChannels,
  28899. float** outputChannelData,
  28900. int numOutputChannels,
  28901. int numSamples) = 0;
  28902. /** Called to indicate that the device is about to start calling back.
  28903. This will be called just before the audio callbacks begin, either when this
  28904. callback has just been added to an audio device, or after the device has been
  28905. restarted because of a sample-rate or block-size change.
  28906. You can use this opportunity to find out the sample rate and block size
  28907. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  28908. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  28909. @param device the audio IO device that will be used to drive the callback.
  28910. Note that if you're going to store this this pointer, it is
  28911. only valid until the next time that audioDeviceStopped is called.
  28912. */
  28913. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  28914. /** Called to indicate that the device has stopped.
  28915. */
  28916. virtual void audioDeviceStopped() = 0;
  28917. };
  28918. /**
  28919. Base class for an audio device with synchronised input and output channels.
  28920. Subclasses of this are used to implement different protocols such as DirectSound,
  28921. ASIO, CoreAudio, etc.
  28922. To create one of these, you'll need to use the AudioIODeviceType class - see the
  28923. documentation for that class for more info.
  28924. For an easier way of managing audio devices and their settings, have a look at the
  28925. AudioDeviceManager class.
  28926. @see AudioIODeviceType, AudioDeviceManager
  28927. */
  28928. class JUCE_API AudioIODevice
  28929. {
  28930. public:
  28931. /** Destructor. */
  28932. virtual ~AudioIODevice();
  28933. /** Returns the device's name, (as set in the constructor). */
  28934. const String& getName() const throw() { return name; }
  28935. /** Returns the type of the device.
  28936. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  28937. */
  28938. const String& getTypeName() const throw() { return typeName; }
  28939. /** Returns the names of all the available output channels on this device.
  28940. To find out which of these are currently in use, call getActiveOutputChannels().
  28941. */
  28942. virtual const StringArray getOutputChannelNames() = 0;
  28943. /** Returns the names of all the available input channels on this device.
  28944. To find out which of these are currently in use, call getActiveInputChannels().
  28945. */
  28946. virtual const StringArray getInputChannelNames() = 0;
  28947. /** Returns the number of sample-rates this device supports.
  28948. To find out which rates are available on this device, use this method to
  28949. find out how many there are, and getSampleRate() to get the rates.
  28950. @see getSampleRate
  28951. */
  28952. virtual int getNumSampleRates() = 0;
  28953. /** Returns one of the sample-rates this device supports.
  28954. To find out which rates are available on this device, use getNumSampleRates() to
  28955. find out how many there are, and getSampleRate() to get the individual rates.
  28956. The sample rate is set by the open() method.
  28957. (Note that for DirectSound some rates might not work, depending on combinations
  28958. of i/o channels that are being opened).
  28959. @see getNumSampleRates
  28960. */
  28961. virtual double getSampleRate (int index) = 0;
  28962. /** Returns the number of sizes of buffer that are available.
  28963. @see getBufferSizeSamples, getDefaultBufferSize
  28964. */
  28965. virtual int getNumBufferSizesAvailable() = 0;
  28966. /** Returns one of the possible buffer-sizes.
  28967. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  28968. @returns a number of samples
  28969. @see getNumBufferSizesAvailable, getDefaultBufferSize
  28970. */
  28971. virtual int getBufferSizeSamples (int index) = 0;
  28972. /** Returns the default buffer-size to use.
  28973. @returns a number of samples
  28974. @see getNumBufferSizesAvailable, getBufferSizeSamples
  28975. */
  28976. virtual int getDefaultBufferSize() = 0;
  28977. /** Tries to open the device ready to play.
  28978. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  28979. input channel should be enabled
  28980. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  28981. output channel should be enabled
  28982. @param sampleRate the sample rate to try to use - to find out which rates are
  28983. available, see getNumSampleRates() and getSampleRate()
  28984. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  28985. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  28986. @returns an error description if there's a problem, or an empty string if it succeeds in
  28987. opening the device
  28988. @see close
  28989. */
  28990. virtual const String open (const BigInteger& inputChannels,
  28991. const BigInteger& outputChannels,
  28992. double sampleRate,
  28993. int bufferSizeSamples) = 0;
  28994. /** Closes and releases the device if it's open. */
  28995. virtual void close() = 0;
  28996. /** Returns true if the device is still open.
  28997. A device might spontaneously close itself if something goes wrong, so this checks if
  28998. it's still open.
  28999. */
  29000. virtual bool isOpen() = 0;
  29001. /** Starts the device actually playing.
  29002. This must be called after the device has been opened.
  29003. @param callback the callback to use for streaming the data.
  29004. @see AudioIODeviceCallback, open
  29005. */
  29006. virtual void start (AudioIODeviceCallback* callback) = 0;
  29007. /** Stops the device playing.
  29008. Once a device has been started, this will stop it. Any pending calls to the
  29009. callback class will be flushed before this method returns.
  29010. */
  29011. virtual void stop() = 0;
  29012. /** Returns true if the device is still calling back.
  29013. The device might mysteriously stop, so this checks whether it's
  29014. still playing.
  29015. */
  29016. virtual bool isPlaying() = 0;
  29017. /** Returns the last error that happened if anything went wrong. */
  29018. virtual const String getLastError() = 0;
  29019. /** Returns the buffer size that the device is currently using.
  29020. If the device isn't actually open, this value doesn't really mean much.
  29021. */
  29022. virtual int getCurrentBufferSizeSamples() = 0;
  29023. /** Returns the sample rate that the device is currently using.
  29024. If the device isn't actually open, this value doesn't really mean much.
  29025. */
  29026. virtual double getCurrentSampleRate() = 0;
  29027. /** Returns the device's current physical bit-depth.
  29028. If the device isn't actually open, this value doesn't really mean much.
  29029. */
  29030. virtual int getCurrentBitDepth() = 0;
  29031. /** Returns a mask showing which of the available output channels are currently
  29032. enabled.
  29033. @see getOutputChannelNames
  29034. */
  29035. virtual const BigInteger getActiveOutputChannels() const = 0;
  29036. /** Returns a mask showing which of the available input channels are currently
  29037. enabled.
  29038. @see getInputChannelNames
  29039. */
  29040. virtual const BigInteger getActiveInputChannels() const = 0;
  29041. /** Returns the device's output latency.
  29042. This is the delay in samples between a callback getting a block of data, and
  29043. that data actually getting played.
  29044. */
  29045. virtual int getOutputLatencyInSamples() = 0;
  29046. /** Returns the device's input latency.
  29047. This is the delay in samples between some audio actually arriving at the soundcard,
  29048. and the callback getting passed this block of data.
  29049. */
  29050. virtual int getInputLatencyInSamples() = 0;
  29051. /** True if this device can show a pop-up control panel for editing its settings.
  29052. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  29053. to display it.
  29054. */
  29055. virtual bool hasControlPanel() const;
  29056. /** Shows a device-specific control panel if there is one.
  29057. This should only be called for devices which return true from hasControlPanel().
  29058. */
  29059. virtual bool showControlPanel();
  29060. protected:
  29061. /** Creates a device, setting its name and type member variables. */
  29062. AudioIODevice (const String& deviceName,
  29063. const String& typeName);
  29064. /** @internal */
  29065. String name, typeName;
  29066. };
  29067. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  29068. /*** End of inlined file: juce_AudioIODevice.h ***/
  29069. /**
  29070. Wrapper class to continuously stream audio from an audio source to an
  29071. AudioIODevice.
  29072. This object acts as an AudioIODeviceCallback, so can be attached to an
  29073. output device, and will stream audio from an AudioSource.
  29074. */
  29075. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  29076. {
  29077. public:
  29078. /** Creates an empty AudioSourcePlayer. */
  29079. AudioSourcePlayer();
  29080. /** Destructor.
  29081. Make sure this object isn't still being used by an AudioIODevice before
  29082. deleting it!
  29083. */
  29084. virtual ~AudioSourcePlayer();
  29085. /** Changes the current audio source to play from.
  29086. If the source passed in is already being used, this method will do nothing.
  29087. If the source is not null, its prepareToPlay() method will be called
  29088. before it starts being used for playback.
  29089. If there's another source currently playing, its releaseResources() method
  29090. will be called after it has been swapped for the new one.
  29091. @param newSource the new source to use - this will NOT be deleted
  29092. by this object when no longer needed, so it's the
  29093. caller's responsibility to manage it.
  29094. */
  29095. void setSource (AudioSource* newSource);
  29096. /** Returns the source that's playing.
  29097. May return 0 if there's no source.
  29098. */
  29099. AudioSource* getCurrentSource() const throw() { return source; }
  29100. /** Sets a gain to apply to the audio data.
  29101. @see getGain
  29102. */
  29103. void setGain (float newGain) throw();
  29104. /** Returns the current gain.
  29105. @see setGain
  29106. */
  29107. float getGain() const throw() { return gain; }
  29108. /** Implementation of the AudioIODeviceCallback method. */
  29109. void audioDeviceIOCallback (const float** inputChannelData,
  29110. int totalNumInputChannels,
  29111. float** outputChannelData,
  29112. int totalNumOutputChannels,
  29113. int numSamples);
  29114. /** Implementation of the AudioIODeviceCallback method. */
  29115. void audioDeviceAboutToStart (AudioIODevice* device);
  29116. /** Implementation of the AudioIODeviceCallback method. */
  29117. void audioDeviceStopped();
  29118. private:
  29119. CriticalSection readLock;
  29120. AudioSource* source;
  29121. double sampleRate;
  29122. int bufferSize;
  29123. float* channels [128];
  29124. float* outputChans [128];
  29125. const float* inputChans [128];
  29126. AudioSampleBuffer tempBuffer;
  29127. float lastGain, gain;
  29128. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  29129. };
  29130. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  29131. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  29132. #endif
  29133. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29134. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  29135. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29136. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29137. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  29138. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29139. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29140. /**
  29141. An AudioSource which takes another source as input, and buffers it using a thread.
  29142. Create this as a wrapper around another thread, and it will read-ahead with
  29143. a background thread to smooth out playback. You can either create one of these
  29144. directly, or use it indirectly using an AudioTransportSource.
  29145. @see PositionableAudioSource, AudioTransportSource
  29146. */
  29147. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  29148. {
  29149. public:
  29150. /** Creates a BufferingAudioSource.
  29151. @param source the input source to read from
  29152. @param deleteSourceWhenDeleted if true, then the input source object will
  29153. be deleted when this object is deleted
  29154. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  29155. */
  29156. BufferingAudioSource (PositionableAudioSource* source,
  29157. bool deleteSourceWhenDeleted,
  29158. int numberOfSamplesToBuffer);
  29159. /** Destructor.
  29160. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  29161. flag was set in the constructor.
  29162. */
  29163. ~BufferingAudioSource();
  29164. /** Implementation of the AudioSource method. */
  29165. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29166. /** Implementation of the AudioSource method. */
  29167. void releaseResources();
  29168. /** Implementation of the AudioSource method. */
  29169. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29170. /** Implements the PositionableAudioSource method. */
  29171. void setNextReadPosition (int64 newPosition);
  29172. /** Implements the PositionableAudioSource method. */
  29173. int64 getNextReadPosition() const;
  29174. /** Implements the PositionableAudioSource method. */
  29175. int64 getTotalLength() const { return source->getTotalLength(); }
  29176. /** Implements the PositionableAudioSource method. */
  29177. bool isLooping() const { return source->isLooping(); }
  29178. private:
  29179. PositionableAudioSource* source;
  29180. bool deleteSourceWhenDeleted;
  29181. int numberOfSamplesToBuffer;
  29182. AudioSampleBuffer buffer;
  29183. CriticalSection bufferStartPosLock;
  29184. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  29185. bool wasSourceLooping;
  29186. double volatile sampleRate;
  29187. friend class SharedBufferingAudioSourceThread;
  29188. bool readNextBufferChunk();
  29189. void readBufferSection (int64 start, int length, int bufferOffset);
  29190. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  29191. };
  29192. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29193. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  29194. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  29195. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29196. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29197. /**
  29198. A type of AudioSource that takes an input source and changes its sample rate.
  29199. @see AudioSource
  29200. */
  29201. class JUCE_API ResamplingAudioSource : public AudioSource
  29202. {
  29203. public:
  29204. /** Creates a ResamplingAudioSource for a given input source.
  29205. @param inputSource the input source to read from
  29206. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29207. this object is deleted
  29208. @param numChannels the number of channels to process
  29209. */
  29210. ResamplingAudioSource (AudioSource* inputSource,
  29211. bool deleteInputWhenDeleted,
  29212. int numChannels = 2);
  29213. /** Destructor. */
  29214. ~ResamplingAudioSource();
  29215. /** Changes the resampling ratio.
  29216. (This value can be changed at any time, even while the source is running).
  29217. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  29218. values will speed it up; lower values will slow it
  29219. down. The ratio must be greater than 0
  29220. */
  29221. void setResamplingRatio (double samplesInPerOutputSample);
  29222. /** Returns the current resampling ratio.
  29223. This is the value that was set by setResamplingRatio().
  29224. */
  29225. double getResamplingRatio() const throw() { return ratio; }
  29226. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29227. void releaseResources();
  29228. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29229. private:
  29230. AudioSource* const input;
  29231. const bool deleteInputWhenDeleted;
  29232. double ratio, lastRatio;
  29233. AudioSampleBuffer buffer;
  29234. int bufferPos, sampsInBuffer;
  29235. double subSampleOffset;
  29236. double coefficients[6];
  29237. SpinLock ratioLock;
  29238. const int numChannels;
  29239. HeapBlock<float*> destBuffers, srcBuffers;
  29240. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  29241. void createLowPass (double proportionalRate);
  29242. struct FilterState
  29243. {
  29244. double x1, x2, y1, y2;
  29245. };
  29246. HeapBlock<FilterState> filterStates;
  29247. void resetFilters();
  29248. void applyFilter (float* samples, int num, FilterState& fs);
  29249. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  29250. };
  29251. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29252. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  29253. /**
  29254. An AudioSource that takes a PositionableAudioSource and allows it to be
  29255. played, stopped, started, etc.
  29256. This can also be told use a buffer and background thread to read ahead, and
  29257. if can correct for different sample-rates.
  29258. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  29259. to control playback of an audio file.
  29260. @see AudioSource, AudioSourcePlayer
  29261. */
  29262. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  29263. public ChangeBroadcaster
  29264. {
  29265. public:
  29266. /** Creates an AudioTransportSource.
  29267. After creating one of these, use the setSource() method to select an input source.
  29268. */
  29269. AudioTransportSource();
  29270. /** Destructor. */
  29271. ~AudioTransportSource();
  29272. /** Sets the reader that is being used as the input source.
  29273. This will stop playback, reset the position to 0 and change to the new reader.
  29274. The source passed in will not be deleted by this object, so must be managed by
  29275. the caller.
  29276. @param newSource the new input source to use. This may be zero
  29277. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  29278. is zero, no reading ahead will be done; if it's
  29279. greater than zero, a BufferingAudioSource will be used
  29280. to do the reading-ahead
  29281. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  29282. rate of the source, and playback will be sample-rate
  29283. adjusted to maintain playback at the correct pitch. If
  29284. this is 0, no sample-rate adjustment will be performed
  29285. @param maxNumChannels the maximum number of channels that may need to be played
  29286. */
  29287. void setSource (PositionableAudioSource* newSource,
  29288. int readAheadBufferSize = 0,
  29289. double sourceSampleRateToCorrectFor = 0.0,
  29290. int maxNumChannels = 2);
  29291. /** Changes the current playback position in the source stream.
  29292. The next time the getNextAudioBlock() method is called, this
  29293. is the time from which it'll read data.
  29294. @see getPosition
  29295. */
  29296. void setPosition (double newPosition);
  29297. /** Returns the position that the next data block will be read from
  29298. This is a time in seconds.
  29299. */
  29300. double getCurrentPosition() const;
  29301. /** Returns the stream's length in seconds. */
  29302. double getLengthInSeconds() const;
  29303. /** Returns true if the player has stopped because its input stream ran out of data.
  29304. */
  29305. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  29306. /** Starts playing (if a source has been selected).
  29307. If it starts playing, this will send a message to any ChangeListeners
  29308. that are registered with this object.
  29309. */
  29310. void start();
  29311. /** Stops playing.
  29312. If it's actually playing, this will send a message to any ChangeListeners
  29313. that are registered with this object.
  29314. */
  29315. void stop();
  29316. /** Returns true if it's currently playing. */
  29317. bool isPlaying() const throw() { return playing; }
  29318. /** Changes the gain to apply to the output.
  29319. @param newGain a factor by which to multiply the outgoing samples,
  29320. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  29321. */
  29322. void setGain (float newGain) throw();
  29323. /** Returns the current gain setting.
  29324. @see setGain
  29325. */
  29326. float getGain() const throw() { return gain; }
  29327. /** Implementation of the AudioSource method. */
  29328. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29329. /** Implementation of the AudioSource method. */
  29330. void releaseResources();
  29331. /** Implementation of the AudioSource method. */
  29332. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29333. /** Implements the PositionableAudioSource method. */
  29334. void setNextReadPosition (int64 newPosition);
  29335. /** Implements the PositionableAudioSource method. */
  29336. int64 getNextReadPosition() const;
  29337. /** Implements the PositionableAudioSource method. */
  29338. int64 getTotalLength() const;
  29339. /** Implements the PositionableAudioSource method. */
  29340. bool isLooping() const;
  29341. private:
  29342. PositionableAudioSource* source;
  29343. ResamplingAudioSource* resamplerSource;
  29344. BufferingAudioSource* bufferingSource;
  29345. PositionableAudioSource* positionableSource;
  29346. AudioSource* masterSource;
  29347. CriticalSection callbackLock;
  29348. float volatile gain, lastGain;
  29349. bool volatile playing, stopped;
  29350. double sampleRate, sourceSampleRate;
  29351. int blockSize, readAheadBufferSize;
  29352. bool isPrepared, inputStreamEOF;
  29353. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  29354. };
  29355. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  29356. /*** End of inlined file: juce_AudioTransportSource.h ***/
  29357. #endif
  29358. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  29359. #endif
  29360. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29361. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29362. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29363. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29364. /**
  29365. An AudioSource that takes the audio from another source, and re-maps its
  29366. input and output channels to a different arrangement.
  29367. You can use this to increase or decrease the number of channels that an
  29368. audio source uses, or to re-order those channels.
  29369. Call the reset() method before using it to set up a default mapping, and then
  29370. the setInputChannelMapping() and setOutputChannelMapping() methods to
  29371. create an appropriate mapping, otherwise no channels will be connected and
  29372. it'll produce silence.
  29373. @see AudioSource
  29374. */
  29375. class ChannelRemappingAudioSource : public AudioSource
  29376. {
  29377. public:
  29378. /** Creates a remapping source that will pass on audio from the given input.
  29379. @param source the input source to use. Make sure that this doesn't
  29380. get deleted before the ChannelRemappingAudioSource object
  29381. @param deleteSourceWhenDeleted if true, the input source will be deleted
  29382. when this object is deleted, if false, the caller is
  29383. responsible for its deletion
  29384. */
  29385. ChannelRemappingAudioSource (AudioSource* source,
  29386. bool deleteSourceWhenDeleted);
  29387. /** Destructor. */
  29388. ~ChannelRemappingAudioSource();
  29389. /** Specifies a number of channels that this audio source must produce from its
  29390. getNextAudioBlock() callback.
  29391. */
  29392. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  29393. /** Clears any mapped channels.
  29394. After this, no channels are mapped, so this object will produce silence. Create
  29395. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  29396. */
  29397. void clearAllMappings();
  29398. /** Creates an input channel mapping.
  29399. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  29400. data will be sent to destChannelIndex of our input source.
  29401. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  29402. source specified when this object was created).
  29403. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  29404. during our getNextAudioBlock() callback
  29405. */
  29406. void setInputChannelMapping (int destChannelIndex,
  29407. int sourceChannelIndex);
  29408. /** Creates an output channel mapping.
  29409. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  29410. our input audio source will be copied to channel destChannelIndex of the final buffer.
  29411. @param sourceChannelIndex the index of an output channel coming from our input audio source
  29412. (i.e. the source specified when this object was created).
  29413. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  29414. during our getNextAudioBlock() callback
  29415. */
  29416. void setOutputChannelMapping (int sourceChannelIndex,
  29417. int destChannelIndex);
  29418. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  29419. our input audio source.
  29420. */
  29421. int getRemappedInputChannel (int inputChannelIndex) const;
  29422. /** Returns the output channel to which channel outputChannelIndex of our input audio
  29423. source will be sent to.
  29424. */
  29425. int getRemappedOutputChannel (int outputChannelIndex) const;
  29426. /** Returns an XML object to encapsulate the state of the mappings.
  29427. @see restoreFromXml
  29428. */
  29429. XmlElement* createXml() const;
  29430. /** Restores the mappings from an XML object created by createXML().
  29431. @see createXml
  29432. */
  29433. void restoreFromXml (const XmlElement& e);
  29434. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29435. void releaseResources();
  29436. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29437. private:
  29438. int requiredNumberOfChannels;
  29439. Array <int> remappedInputs, remappedOutputs;
  29440. AudioSource* const source;
  29441. const bool deleteSourceWhenDeleted;
  29442. AudioSampleBuffer buffer;
  29443. AudioSourceChannelInfo remappedInfo;
  29444. CriticalSection lock;
  29445. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  29446. };
  29447. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  29448. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  29449. #endif
  29450. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29451. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  29452. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29453. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29454. /*** Start of inlined file: juce_IIRFilter.h ***/
  29455. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  29456. #define __JUCE_IIRFILTER_JUCEHEADER__
  29457. /**
  29458. An IIR filter that can perform low, high, or band-pass filtering on an
  29459. audio signal.
  29460. @see IIRFilterAudioSource
  29461. */
  29462. class JUCE_API IIRFilter
  29463. {
  29464. public:
  29465. /** Creates a filter.
  29466. Initially the filter is inactive, so will have no effect on samples that
  29467. you process with it. Use the appropriate method to turn it into the type
  29468. of filter needed.
  29469. */
  29470. IIRFilter();
  29471. /** Creates a copy of another filter. */
  29472. IIRFilter (const IIRFilter& other);
  29473. /** Destructor. */
  29474. ~IIRFilter();
  29475. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  29476. Note that this clears the processing state, but the type of filter and
  29477. its coefficients aren't changed. To put a filter into an inactive state, use
  29478. the makeInactive() method.
  29479. */
  29480. void reset() throw();
  29481. /** Performs the filter operation on the given set of samples.
  29482. */
  29483. void processSamples (float* samples,
  29484. int numSamples) throw();
  29485. /** Processes a single sample, without any locking or checking.
  29486. Use this if you need fast processing of a single value, but be aware that
  29487. this isn't thread-safe in the way that processSamples() is.
  29488. */
  29489. float processSingleSampleRaw (float sample) throw();
  29490. /** Sets the filter up to act as a low-pass filter.
  29491. */
  29492. void makeLowPass (double sampleRate,
  29493. double frequency) throw();
  29494. /** Sets the filter up to act as a high-pass filter.
  29495. */
  29496. void makeHighPass (double sampleRate,
  29497. double frequency) throw();
  29498. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  29499. The gain is a scale factor that the low frequencies are multiplied by, so values
  29500. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  29501. attenuate them.
  29502. */
  29503. void makeLowShelf (double sampleRate,
  29504. double cutOffFrequency,
  29505. double Q,
  29506. float gainFactor) throw();
  29507. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  29508. The gain is a scale factor that the high frequencies are multiplied by, so values
  29509. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  29510. attenuate them.
  29511. */
  29512. void makeHighShelf (double sampleRate,
  29513. double cutOffFrequency,
  29514. double Q,
  29515. float gainFactor) throw();
  29516. /** Sets the filter up to act as a band pass filter centred around a
  29517. frequency, with a variable Q and gain.
  29518. The gain is a scale factor that the centre frequencies are multiplied by, so
  29519. values greater than 1.0 will boost the centre frequencies, values less than
  29520. 1.0 will attenuate them.
  29521. */
  29522. void makeBandPass (double sampleRate,
  29523. double centreFrequency,
  29524. double Q,
  29525. float gainFactor) throw();
  29526. /** Clears the filter's coefficients so that it becomes inactive.
  29527. */
  29528. void makeInactive() throw();
  29529. /** Makes this filter duplicate the set-up of another one.
  29530. */
  29531. void copyCoefficientsFrom (const IIRFilter& other) throw();
  29532. protected:
  29533. CriticalSection processLock;
  29534. void setCoefficients (double c1, double c2, double c3,
  29535. double c4, double c5, double c6) throw();
  29536. bool active;
  29537. float coefficients[6];
  29538. float x1, x2, y1, y2;
  29539. // (use the copyCoefficientsFrom() method instead of this operator)
  29540. IIRFilter& operator= (const IIRFilter&);
  29541. JUCE_LEAK_DETECTOR (IIRFilter);
  29542. };
  29543. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  29544. /*** End of inlined file: juce_IIRFilter.h ***/
  29545. /**
  29546. An AudioSource that performs an IIR filter on another source.
  29547. */
  29548. class JUCE_API IIRFilterAudioSource : public AudioSource
  29549. {
  29550. public:
  29551. /** Creates a IIRFilterAudioSource for a given input source.
  29552. @param inputSource the input source to read from
  29553. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29554. this object is deleted
  29555. */
  29556. IIRFilterAudioSource (AudioSource* inputSource,
  29557. bool deleteInputWhenDeleted);
  29558. /** Destructor. */
  29559. ~IIRFilterAudioSource();
  29560. /** Changes the filter to use the same parameters as the one being passed in.
  29561. */
  29562. void setFilterParameters (const IIRFilter& newSettings);
  29563. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29564. void releaseResources();
  29565. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29566. private:
  29567. AudioSource* const input;
  29568. const bool deleteInputWhenDeleted;
  29569. OwnedArray <IIRFilter> iirFilters;
  29570. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  29571. };
  29572. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29573. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  29574. #endif
  29575. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29576. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  29577. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29578. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29579. /**
  29580. An AudioSource that mixes together the output of a set of other AudioSources.
  29581. Input sources can be added and removed while the mixer is running as long as their
  29582. prepareToPlay() and releaseResources() methods are called before and after adding
  29583. them to the mixer.
  29584. */
  29585. class JUCE_API MixerAudioSource : public AudioSource
  29586. {
  29587. public:
  29588. /** Creates a MixerAudioSource.
  29589. */
  29590. MixerAudioSource();
  29591. /** Destructor. */
  29592. ~MixerAudioSource();
  29593. /** Adds an input source to the mixer.
  29594. If the mixer is running you'll need to make sure that the input source
  29595. is ready to play by calling its prepareToPlay() method before adding it.
  29596. If the mixer is stopped, then its input sources will be automatically
  29597. prepared when the mixer's prepareToPlay() method is called.
  29598. @param newInput the source to add to the mixer
  29599. @param deleteWhenRemoved if true, then this source will be deleted when
  29600. the mixer is deleted or when removeAllInputs() is
  29601. called (unless the source is previously removed
  29602. with the removeInputSource method)
  29603. */
  29604. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  29605. /** Removes an input source.
  29606. If the mixer is running, this will remove the source but not call its
  29607. releaseResources() method, so the caller might want to do this manually.
  29608. @param input the source to remove
  29609. @param deleteSource whether to delete this source after it's been removed
  29610. */
  29611. void removeInputSource (AudioSource* input, bool deleteSource);
  29612. /** Removes all the input sources.
  29613. If the mixer is running, this will remove the sources but not call their
  29614. releaseResources() method, so the caller might want to do this manually.
  29615. Any sources which were added with the deleteWhenRemoved flag set will be
  29616. deleted by this method.
  29617. */
  29618. void removeAllInputs();
  29619. /** Implementation of the AudioSource method.
  29620. This will call prepareToPlay() on all its input sources.
  29621. */
  29622. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29623. /** Implementation of the AudioSource method.
  29624. This will call releaseResources() on all its input sources.
  29625. */
  29626. void releaseResources();
  29627. /** Implementation of the AudioSource method. */
  29628. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29629. private:
  29630. Array <AudioSource*> inputs;
  29631. BigInteger inputsToDelete;
  29632. CriticalSection lock;
  29633. AudioSampleBuffer tempBuffer;
  29634. double currentSampleRate;
  29635. int bufferSizeExpected;
  29636. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  29637. };
  29638. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29639. /*** End of inlined file: juce_MixerAudioSource.h ***/
  29640. #endif
  29641. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29642. #endif
  29643. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29644. #endif
  29645. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29646. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29647. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29648. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29649. /**
  29650. A simple AudioSource that generates a sine wave.
  29651. */
  29652. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  29653. {
  29654. public:
  29655. /** Creates a ToneGeneratorAudioSource. */
  29656. ToneGeneratorAudioSource();
  29657. /** Destructor. */
  29658. ~ToneGeneratorAudioSource();
  29659. /** Sets the signal's amplitude. */
  29660. void setAmplitude (float newAmplitude);
  29661. /** Sets the signal's frequency. */
  29662. void setFrequency (double newFrequencyHz);
  29663. /** Implementation of the AudioSource method. */
  29664. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29665. /** Implementation of the AudioSource method. */
  29666. void releaseResources();
  29667. /** Implementation of the AudioSource method. */
  29668. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29669. private:
  29670. double frequency, sampleRate;
  29671. double currentPhase, phasePerSample;
  29672. float amplitude;
  29673. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  29674. };
  29675. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29676. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29677. #endif
  29678. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29679. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  29680. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29681. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29682. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  29683. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29684. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29685. class AudioDeviceManager;
  29686. class Component;
  29687. /**
  29688. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  29689. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  29690. method. Each of the objects returned can then be used to list the available
  29691. devices of that type. E.g.
  29692. @code
  29693. OwnedArray <AudioIODeviceType> types;
  29694. myAudioDeviceManager.createAudioDeviceTypes (types);
  29695. for (int i = 0; i < types.size(); ++i)
  29696. {
  29697. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  29698. types[i]->scanForDevices(); // This must be called before getting the list of devices
  29699. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  29700. for (int j = 0; j < deviceNames.size(); ++j)
  29701. {
  29702. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  29703. ...
  29704. }
  29705. }
  29706. @endcode
  29707. For an easier way of managing audio devices and their settings, have a look at the
  29708. AudioDeviceManager class.
  29709. @see AudioIODevice, AudioDeviceManager
  29710. */
  29711. class JUCE_API AudioIODeviceType
  29712. {
  29713. public:
  29714. /** Returns the name of this type of driver that this object manages.
  29715. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  29716. */
  29717. const String& getTypeName() const throw() { return typeName; }
  29718. /** Refreshes the object's cached list of known devices.
  29719. This must be called at least once before calling getDeviceNames() or any of
  29720. the other device creation methods.
  29721. */
  29722. virtual void scanForDevices() = 0;
  29723. /** Returns the list of available devices of this type.
  29724. The scanForDevices() method must have been called to create this list.
  29725. @param wantInputNames only really used by DirectSound where devices are split up
  29726. into inputs and outputs, this indicates whether to use
  29727. the input or output name to refer to a pair of devices.
  29728. */
  29729. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  29730. /** Returns the name of the default device.
  29731. This will be one of the names from the getDeviceNames() list.
  29732. @param forInput if true, this means that a default input device should be
  29733. returned; if false, it should return the default output
  29734. */
  29735. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  29736. /** Returns the index of a given device in the list of device names.
  29737. If asInput is true, it shows the index in the inputs list, otherwise it
  29738. looks for it in the outputs list.
  29739. */
  29740. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  29741. /** Returns true if two different devices can be used for the input and output.
  29742. */
  29743. virtual bool hasSeparateInputsAndOutputs() const = 0;
  29744. /** Creates one of the devices of this type.
  29745. The deviceName must be one of the strings returned by getDeviceNames(), and
  29746. scanForDevices() must have been called before this method is used.
  29747. */
  29748. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  29749. const String& inputDeviceName) = 0;
  29750. struct DeviceSetupDetails
  29751. {
  29752. AudioDeviceManager* manager;
  29753. int minNumInputChannels, maxNumInputChannels;
  29754. int minNumOutputChannels, maxNumOutputChannels;
  29755. bool useStereoPairs;
  29756. };
  29757. /** Destructor. */
  29758. virtual ~AudioIODeviceType();
  29759. /** Creates a CoreAudio device type if it's available on this platform, or returns null. */
  29760. static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
  29761. /** Creates an iOS device type if it's available on this platform, or returns null. */
  29762. static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
  29763. /** Creates a WASAPI device type if it's available on this platform, or returns null. */
  29764. static AudioIODeviceType* createAudioIODeviceType_WASAPI();
  29765. /** Creates a DirectSound device type if it's available on this platform, or returns null. */
  29766. static AudioIODeviceType* createAudioIODeviceType_DirectSound();
  29767. /** Creates an ASIO device type if it's available on this platform, or returns null. */
  29768. static AudioIODeviceType* createAudioIODeviceType_ASIO();
  29769. /** Creates an ALSA device type if it's available on this platform, or returns null. */
  29770. static AudioIODeviceType* createAudioIODeviceType_ALSA();
  29771. /** Creates a JACK device type if it's available on this platform, or returns null. */
  29772. static AudioIODeviceType* createAudioIODeviceType_JACK();
  29773. /** Creates an Android device type if it's available on this platform, or returns null. */
  29774. static AudioIODeviceType* createAudioIODeviceType_Android();
  29775. protected:
  29776. explicit AudioIODeviceType (const String& typeName);
  29777. private:
  29778. String typeName;
  29779. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  29780. };
  29781. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29782. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  29783. /*** Start of inlined file: juce_MidiInput.h ***/
  29784. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  29785. #define __JUCE_MIDIINPUT_JUCEHEADER__
  29786. /*** Start of inlined file: juce_MidiMessage.h ***/
  29787. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  29788. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  29789. /**
  29790. Encapsulates a MIDI message.
  29791. @see MidiMessageSequence, MidiOutput, MidiInput
  29792. */
  29793. class JUCE_API MidiMessage
  29794. {
  29795. public:
  29796. /** Creates a 3-byte short midi message.
  29797. @param byte1 message byte 1
  29798. @param byte2 message byte 2
  29799. @param byte3 message byte 3
  29800. @param timeStamp the time to give the midi message - this value doesn't
  29801. use any particular units, so will be application-specific
  29802. */
  29803. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  29804. /** Creates a 2-byte short midi message.
  29805. @param byte1 message byte 1
  29806. @param byte2 message byte 2
  29807. @param timeStamp the time to give the midi message - this value doesn't
  29808. use any particular units, so will be application-specific
  29809. */
  29810. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  29811. /** Creates a 1-byte short midi message.
  29812. @param byte1 message byte 1
  29813. @param timeStamp the time to give the midi message - this value doesn't
  29814. use any particular units, so will be application-specific
  29815. */
  29816. MidiMessage (int byte1, double timeStamp = 0) throw();
  29817. /** Creates a midi message from a block of data. */
  29818. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  29819. /** Reads the next midi message from some data.
  29820. This will read as many bytes from a data stream as it needs to make a
  29821. complete message, and will return the number of bytes it used. This lets
  29822. you read a sequence of midi messages from a file or stream.
  29823. @param data the data to read from
  29824. @param maxBytesToUse the maximum number of bytes it's allowed to read
  29825. @param numBytesUsed returns the number of bytes that were actually needed
  29826. @param lastStatusByte in a sequence of midi messages, the initial byte
  29827. can be dropped from a message if it's the same as the
  29828. first byte of the previous message, so this lets you
  29829. supply the byte to use if the first byte of the message
  29830. has in fact been dropped.
  29831. @param timeStamp the time to give the midi message - this value doesn't
  29832. use any particular units, so will be application-specific
  29833. */
  29834. MidiMessage (const void* data, int maxBytesToUse,
  29835. int& numBytesUsed, uint8 lastStatusByte,
  29836. double timeStamp = 0);
  29837. /** Creates an active-sense message.
  29838. Since the MidiMessage has to contain a valid message, this default constructor
  29839. just initialises it with an empty sysex message.
  29840. */
  29841. MidiMessage() throw();
  29842. /** Creates a copy of another midi message. */
  29843. MidiMessage (const MidiMessage& other);
  29844. /** Creates a copy of another midi message, with a different timestamp. */
  29845. MidiMessage (const MidiMessage& other, double newTimeStamp);
  29846. /** Destructor. */
  29847. ~MidiMessage();
  29848. /** Copies this message from another one. */
  29849. MidiMessage& operator= (const MidiMessage& other);
  29850. /** Returns a pointer to the raw midi data.
  29851. @see getRawDataSize
  29852. */
  29853. uint8* getRawData() const throw() { return data; }
  29854. /** Returns the number of bytes of data in the message.
  29855. @see getRawData
  29856. */
  29857. int getRawDataSize() const throw() { return size; }
  29858. /** Returns the timestamp associated with this message.
  29859. The exact meaning of this time and its units will vary, as messages are used in
  29860. a variety of different contexts.
  29861. If you're getting the message from a midi file, this could be a time in seconds, or
  29862. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  29863. If the message is being used in a MidiBuffer, it might indicate the number of
  29864. audio samples from the start of the buffer.
  29865. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  29866. for details of the way that it initialises this value.
  29867. @see setTimeStamp, addToTimeStamp
  29868. */
  29869. double getTimeStamp() const throw() { return timeStamp; }
  29870. /** Changes the message's associated timestamp.
  29871. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  29872. @see addToTimeStamp, getTimeStamp
  29873. */
  29874. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  29875. /** Adds a value to the message's timestamp.
  29876. The units for the timestamp will be application-specific.
  29877. */
  29878. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  29879. /** Returns the midi channel associated with the message.
  29880. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  29881. if it's a sysex)
  29882. @see isForChannel, setChannel
  29883. */
  29884. int getChannel() const throw();
  29885. /** Returns true if the message applies to the given midi channel.
  29886. @param channelNumber the channel number to look for, in the range 1 to 16
  29887. @see getChannel, setChannel
  29888. */
  29889. bool isForChannel (int channelNumber) const throw();
  29890. /** Changes the message's midi channel.
  29891. This won't do anything for non-channel messages like sysexes.
  29892. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  29893. */
  29894. void setChannel (int newChannelNumber) throw();
  29895. /** Returns true if this is a system-exclusive message.
  29896. */
  29897. bool isSysEx() const throw();
  29898. /** Returns a pointer to the sysex data inside the message.
  29899. If this event isn't a sysex event, it'll return 0.
  29900. @see getSysExDataSize
  29901. */
  29902. const uint8* getSysExData() const throw();
  29903. /** Returns the size of the sysex data.
  29904. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  29905. @see getSysExData
  29906. */
  29907. int getSysExDataSize() const throw();
  29908. /** Returns true if this message is a 'key-down' event.
  29909. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  29910. velocity 0, it will still be considered to be a note-on and the
  29911. method will return true. If returnTrueForVelocity0 is false, then
  29912. if this is a note-on event with velocity 0, it'll be regarded as
  29913. a note-off, and the method will return false
  29914. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  29915. */
  29916. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  29917. /** Creates a key-down message (using a floating-point velocity).
  29918. @param channel the midi channel, in the range 1 to 16
  29919. @param noteNumber the key number, 0 to 127
  29920. @param velocity in the range 0 to 1.0
  29921. @see isNoteOn
  29922. */
  29923. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  29924. /** Creates a key-down message (using an integer velocity).
  29925. @param channel the midi channel, in the range 1 to 16
  29926. @param noteNumber the key number, 0 to 127
  29927. @param velocity in the range 0 to 127
  29928. @see isNoteOn
  29929. */
  29930. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  29931. /** Returns true if this message is a 'key-up' event.
  29932. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  29933. for a note-on event with a velocity of 0.
  29934. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  29935. */
  29936. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  29937. /** Creates a key-up message.
  29938. @param channel the midi channel, in the range 1 to 16
  29939. @param noteNumber the key number, 0 to 127
  29940. @param velocity in the range 0 to 127
  29941. @see isNoteOff
  29942. */
  29943. static const MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) throw();
  29944. /** Returns true if this message is a 'key-down' or 'key-up' event.
  29945. @see isNoteOn, isNoteOff
  29946. */
  29947. bool isNoteOnOrOff() const throw();
  29948. /** Returns the midi note number for note-on and note-off messages.
  29949. If the message isn't a note-on or off, the value returned will be
  29950. meaningless.
  29951. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  29952. */
  29953. int getNoteNumber() const throw();
  29954. /** Changes the midi note number of a note-on or note-off message.
  29955. If the message isn't a note on or off, this will do nothing.
  29956. */
  29957. void setNoteNumber (int newNoteNumber) throw();
  29958. /** Returns the velocity of a note-on or note-off message.
  29959. The value returned will be in the range 0 to 127.
  29960. If the message isn't a note-on or off event, it will return 0.
  29961. @see getFloatVelocity
  29962. */
  29963. uint8 getVelocity() const throw();
  29964. /** Returns the velocity of a note-on or note-off message.
  29965. The value returned will be in the range 0 to 1.0
  29966. If the message isn't a note-on or off event, it will return 0.
  29967. @see getVelocity, setVelocity
  29968. */
  29969. float getFloatVelocity() const throw();
  29970. /** Changes the velocity of a note-on or note-off message.
  29971. If the message isn't a note on or off, this will do nothing.
  29972. @param newVelocity the new velocity, in the range 0 to 1.0
  29973. @see getFloatVelocity, multiplyVelocity
  29974. */
  29975. void setVelocity (float newVelocity) throw();
  29976. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  29977. If the message isn't a note on or off, this will do nothing.
  29978. @param scaleFactor the value by which to multiply the velocity
  29979. @see setVelocity
  29980. */
  29981. void multiplyVelocity (float scaleFactor) throw();
  29982. /** Returns true if the message is a program (patch) change message.
  29983. @see getProgramChangeNumber, getGMInstrumentName
  29984. */
  29985. bool isProgramChange() const throw();
  29986. /** Returns the new program number of a program change message.
  29987. If the message isn't a program change, the value returned will be
  29988. nonsense.
  29989. @see isProgramChange, getGMInstrumentName
  29990. */
  29991. int getProgramChangeNumber() const throw();
  29992. /** Creates a program-change message.
  29993. @param channel the midi channel, in the range 1 to 16
  29994. @param programNumber the midi program number, 0 to 127
  29995. @see isProgramChange, getGMInstrumentName
  29996. */
  29997. static const MidiMessage programChange (int channel, int programNumber) throw();
  29998. /** Returns true if the message is a pitch-wheel move.
  29999. @see getPitchWheelValue, pitchWheel
  30000. */
  30001. bool isPitchWheel() const throw();
  30002. /** Returns the pitch wheel position from a pitch-wheel move message.
  30003. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  30004. If called for messages which aren't pitch wheel events, the number returned will be
  30005. nonsense.
  30006. @see isPitchWheel
  30007. */
  30008. int getPitchWheelValue() const throw();
  30009. /** Creates a pitch-wheel move message.
  30010. @param channel the midi channel, in the range 1 to 16
  30011. @param position the wheel position, in the range 0 to 16383
  30012. @see isPitchWheel
  30013. */
  30014. static const MidiMessage pitchWheel (int channel, int position) throw();
  30015. /** Returns true if the message is an aftertouch event.
  30016. For aftertouch events, use the getNoteNumber() method to find out the key
  30017. that it applies to, and getAftertouchValue() to find out the amount. Use
  30018. getChannel() to find out the channel.
  30019. @see getAftertouchValue, getNoteNumber
  30020. */
  30021. bool isAftertouch() const throw();
  30022. /** Returns the amount of aftertouch from an aftertouch messages.
  30023. The value returned is in the range 0 to 127, and will be nonsense for messages
  30024. other than aftertouch messages.
  30025. @see isAftertouch
  30026. */
  30027. int getAfterTouchValue() const throw();
  30028. /** Creates an aftertouch message.
  30029. @param channel the midi channel, in the range 1 to 16
  30030. @param noteNumber the key number, 0 to 127
  30031. @param aftertouchAmount the amount of aftertouch, 0 to 127
  30032. @see isAftertouch
  30033. */
  30034. static const MidiMessage aftertouchChange (int channel,
  30035. int noteNumber,
  30036. int aftertouchAmount) throw();
  30037. /** Returns true if the message is a channel-pressure change event.
  30038. This is like aftertouch, but common to the whole channel rather than a specific
  30039. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  30040. to find out the channel.
  30041. @see channelPressureChange
  30042. */
  30043. bool isChannelPressure() const throw();
  30044. /** Returns the pressure from a channel pressure change message.
  30045. @returns the pressure, in the range 0 to 127
  30046. @see isChannelPressure, channelPressureChange
  30047. */
  30048. int getChannelPressureValue() const throw();
  30049. /** Creates a channel-pressure change event.
  30050. @param channel the midi channel: 1 to 16
  30051. @param pressure the pressure, 0 to 127
  30052. @see isChannelPressure
  30053. */
  30054. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  30055. /** Returns true if this is a midi controller message.
  30056. @see getControllerNumber, getControllerValue, controllerEvent
  30057. */
  30058. bool isController() const throw();
  30059. /** Returns the controller number of a controller message.
  30060. The name of the controller can be looked up using the getControllerName() method.
  30061. Note that the value returned is invalid for messages that aren't controller changes.
  30062. @see isController, getControllerName, getControllerValue
  30063. */
  30064. int getControllerNumber() const throw();
  30065. /** Returns the controller value from a controller message.
  30066. A value 0 to 127 is returned to indicate the new controller position.
  30067. Note that the value returned is invalid for messages that aren't controller changes.
  30068. @see isController, getControllerNumber
  30069. */
  30070. int getControllerValue() const throw();
  30071. /** Creates a controller message.
  30072. @param channel the midi channel, in the range 1 to 16
  30073. @param controllerType the type of controller
  30074. @param value the controller value
  30075. @see isController
  30076. */
  30077. static const MidiMessage controllerEvent (int channel,
  30078. int controllerType,
  30079. int value) throw();
  30080. /** Checks whether this message is an all-notes-off message.
  30081. @see allNotesOff
  30082. */
  30083. bool isAllNotesOff() const throw();
  30084. /** Checks whether this message is an all-sound-off message.
  30085. @see allSoundOff
  30086. */
  30087. bool isAllSoundOff() const throw();
  30088. /** Creates an all-notes-off message.
  30089. @param channel the midi channel, in the range 1 to 16
  30090. @see isAllNotesOff
  30091. */
  30092. static const MidiMessage allNotesOff (int channel) throw();
  30093. /** Creates an all-sound-off message.
  30094. @param channel the midi channel, in the range 1 to 16
  30095. @see isAllSoundOff
  30096. */
  30097. static const MidiMessage allSoundOff (int channel) throw();
  30098. /** Creates an all-controllers-off message.
  30099. @param channel the midi channel, in the range 1 to 16
  30100. */
  30101. static const MidiMessage allControllersOff (int channel) throw();
  30102. /** Returns true if this event is a meta-event.
  30103. Meta-events are things like tempo changes, track names, etc.
  30104. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30105. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30106. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30107. */
  30108. bool isMetaEvent() const throw();
  30109. /** Returns a meta-event's type number.
  30110. If the message isn't a meta-event, this will return -1.
  30111. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  30112. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  30113. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  30114. */
  30115. int getMetaEventType() const throw();
  30116. /** Returns a pointer to the data in a meta-event.
  30117. @see isMetaEvent, getMetaEventLength
  30118. */
  30119. const uint8* getMetaEventData() const throw();
  30120. /** Returns the length of the data for a meta-event.
  30121. @see isMetaEvent, getMetaEventData
  30122. */
  30123. int getMetaEventLength() const throw();
  30124. /** Returns true if this is a 'track' meta-event. */
  30125. bool isTrackMetaEvent() const throw();
  30126. /** Returns true if this is an 'end-of-track' meta-event. */
  30127. bool isEndOfTrackMetaEvent() const throw();
  30128. /** Creates an end-of-track meta-event.
  30129. @see isEndOfTrackMetaEvent
  30130. */
  30131. static const MidiMessage endOfTrack() throw();
  30132. /** Returns true if this is an 'track name' meta-event.
  30133. You can use the getTextFromTextMetaEvent() method to get the track's name.
  30134. */
  30135. bool isTrackNameEvent() const throw();
  30136. /** Returns true if this is a 'text' meta-event.
  30137. @see getTextFromTextMetaEvent
  30138. */
  30139. bool isTextMetaEvent() const throw();
  30140. /** Returns the text from a text meta-event.
  30141. @see isTextMetaEvent
  30142. */
  30143. const String getTextFromTextMetaEvent() const;
  30144. /** Returns true if this is a 'tempo' meta-event.
  30145. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  30146. */
  30147. bool isTempoMetaEvent() const throw();
  30148. /** Returns the tick length from a tempo meta-event.
  30149. @param timeFormat the 16-bit time format value from the midi file's header.
  30150. @returns the tick length (in seconds).
  30151. @see isTempoMetaEvent
  30152. */
  30153. double getTempoMetaEventTickLength (short timeFormat) const throw();
  30154. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  30155. @see isTempoMetaEvent, getTempoMetaEventTickLength
  30156. */
  30157. double getTempoSecondsPerQuarterNote() const throw();
  30158. /** Creates a tempo meta-event.
  30159. @see isTempoMetaEvent
  30160. */
  30161. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  30162. /** Returns true if this is a 'time-signature' meta-event.
  30163. @see getTimeSignatureInfo
  30164. */
  30165. bool isTimeSignatureMetaEvent() const throw();
  30166. /** Returns the time-signature values from a time-signature meta-event.
  30167. @see isTimeSignatureMetaEvent
  30168. */
  30169. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  30170. /** Creates a time-signature meta-event.
  30171. @see isTimeSignatureMetaEvent
  30172. */
  30173. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  30174. /** Returns true if this is a 'key-signature' meta-event.
  30175. @see getKeySignatureNumberOfSharpsOrFlats
  30176. */
  30177. bool isKeySignatureMetaEvent() const throw();
  30178. /** Returns the key from a key-signature meta-event.
  30179. @see isKeySignatureMetaEvent
  30180. */
  30181. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  30182. /** Returns true if this is a 'channel' meta-event.
  30183. A channel meta-event specifies the midi channel that should be used
  30184. for subsequent meta-events.
  30185. @see getMidiChannelMetaEventChannel
  30186. */
  30187. bool isMidiChannelMetaEvent() const throw();
  30188. /** Returns the channel number from a channel meta-event.
  30189. @returns the channel, in the range 1 to 16.
  30190. @see isMidiChannelMetaEvent
  30191. */
  30192. int getMidiChannelMetaEventChannel() const throw();
  30193. /** Creates a midi channel meta-event.
  30194. @param channel the midi channel, in the range 1 to 16
  30195. @see isMidiChannelMetaEvent
  30196. */
  30197. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  30198. /** Returns true if this is an active-sense message. */
  30199. bool isActiveSense() const throw();
  30200. /** Returns true if this is a midi start event.
  30201. @see midiStart
  30202. */
  30203. bool isMidiStart() const throw();
  30204. /** Creates a midi start event. */
  30205. static const MidiMessage midiStart() throw();
  30206. /** Returns true if this is a midi continue event.
  30207. @see midiContinue
  30208. */
  30209. bool isMidiContinue() const throw();
  30210. /** Creates a midi continue event. */
  30211. static const MidiMessage midiContinue() throw();
  30212. /** Returns true if this is a midi stop event.
  30213. @see midiStop
  30214. */
  30215. bool isMidiStop() const throw();
  30216. /** Creates a midi stop event. */
  30217. static const MidiMessage midiStop() throw();
  30218. /** Returns true if this is a midi clock event.
  30219. @see midiClock, songPositionPointer
  30220. */
  30221. bool isMidiClock() const throw();
  30222. /** Creates a midi clock event. */
  30223. static const MidiMessage midiClock() throw();
  30224. /** Returns true if this is a song-position-pointer message.
  30225. @see getSongPositionPointerMidiBeat, songPositionPointer
  30226. */
  30227. bool isSongPositionPointer() const throw();
  30228. /** Returns the midi beat-number of a song-position-pointer message.
  30229. @see isSongPositionPointer, songPositionPointer
  30230. */
  30231. int getSongPositionPointerMidiBeat() const throw();
  30232. /** Creates a song-position-pointer message.
  30233. The position is a number of midi beats from the start of the song, where 1 midi
  30234. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  30235. are 4 midi beats in a quarter-note.
  30236. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  30237. */
  30238. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  30239. /** Returns true if this is a quarter-frame midi timecode message.
  30240. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  30241. */
  30242. bool isQuarterFrame() const throw();
  30243. /** Returns the sequence number of a quarter-frame midi timecode message.
  30244. This will be a value between 0 and 7.
  30245. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  30246. */
  30247. int getQuarterFrameSequenceNumber() const throw();
  30248. /** Returns the value from a quarter-frame message.
  30249. This will be the lower nybble of the message's data-byte, a value
  30250. between 0 and 15
  30251. */
  30252. int getQuarterFrameValue() const throw();
  30253. /** Creates a quarter-frame MTC message.
  30254. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  30255. @param value a value 0 to 15 for the lower nybble of the message's data byte
  30256. */
  30257. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  30258. /** SMPTE timecode types.
  30259. Used by the getFullFrameParameters() and fullFrame() methods.
  30260. */
  30261. enum SmpteTimecodeType
  30262. {
  30263. fps24 = 0,
  30264. fps25 = 1,
  30265. fps30drop = 2,
  30266. fps30 = 3
  30267. };
  30268. /** Returns true if this is a full-frame midi timecode message.
  30269. */
  30270. bool isFullFrame() const throw();
  30271. /** Extracts the timecode information from a full-frame midi timecode message.
  30272. You should only call this on messages where you've used isFullFrame() to
  30273. check that they're the right kind.
  30274. */
  30275. void getFullFrameParameters (int& hours,
  30276. int& minutes,
  30277. int& seconds,
  30278. int& frames,
  30279. SmpteTimecodeType& timecodeType) const throw();
  30280. /** Creates a full-frame MTC message.
  30281. */
  30282. static const MidiMessage fullFrame (int hours,
  30283. int minutes,
  30284. int seconds,
  30285. int frames,
  30286. SmpteTimecodeType timecodeType);
  30287. /** Types of MMC command.
  30288. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  30289. */
  30290. enum MidiMachineControlCommand
  30291. {
  30292. mmc_stop = 1,
  30293. mmc_play = 2,
  30294. mmc_deferredplay = 3,
  30295. mmc_fastforward = 4,
  30296. mmc_rewind = 5,
  30297. mmc_recordStart = 6,
  30298. mmc_recordStop = 7,
  30299. mmc_pause = 9
  30300. };
  30301. /** Checks whether this is an MMC message.
  30302. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  30303. */
  30304. bool isMidiMachineControlMessage() const throw();
  30305. /** For an MMC message, this returns its type.
  30306. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  30307. calling this method.
  30308. */
  30309. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  30310. /** Creates an MMC message.
  30311. */
  30312. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  30313. /** Checks whether this is an MMC "goto" message.
  30314. If it is, the parameters passed-in are set to the time that the message contains.
  30315. @see midiMachineControlGoto
  30316. */
  30317. bool isMidiMachineControlGoto (int& hours,
  30318. int& minutes,
  30319. int& seconds,
  30320. int& frames) const throw();
  30321. /** Creates an MMC "goto" message.
  30322. This messages tells the device to go to a specific frame.
  30323. @see isMidiMachineControlGoto
  30324. */
  30325. static const MidiMessage midiMachineControlGoto (int hours,
  30326. int minutes,
  30327. int seconds,
  30328. int frames);
  30329. /** Creates a master-volume change message.
  30330. @param volume the volume, 0 to 1.0
  30331. */
  30332. static const MidiMessage masterVolume (float volume);
  30333. /** Creates a system-exclusive message.
  30334. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  30335. */
  30336. static const MidiMessage createSysExMessage (const uint8* sysexData,
  30337. int dataSize);
  30338. /** Reads a midi variable-length integer.
  30339. @param data the data to read the number from
  30340. @param numBytesUsed on return, this will be set to the number of bytes that were read
  30341. */
  30342. static int readVariableLengthVal (const uint8* data,
  30343. int& numBytesUsed) throw();
  30344. /** Based on the first byte of a short midi message, this uses a lookup table
  30345. to return the message length (either 1, 2, or 3 bytes).
  30346. The value passed in must be 0x80 or higher.
  30347. */
  30348. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  30349. /** Returns the name of a midi note number.
  30350. E.g "C", "D#", etc.
  30351. @param noteNumber the midi note number, 0 to 127
  30352. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  30353. they'll be flattened, e.g. "Db"
  30354. @param includeOctaveNumber if true, the octave number will be appended to the string,
  30355. e.g. "C#4"
  30356. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  30357. number that will be used for middle C's octave
  30358. @see getMidiNoteInHertz
  30359. */
  30360. static const String getMidiNoteName (int noteNumber,
  30361. bool useSharps,
  30362. bool includeOctaveNumber,
  30363. int octaveNumForMiddleC);
  30364. /** Returns the frequency of a midi note number.
  30365. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  30366. @see getMidiNoteName
  30367. */
  30368. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) throw();
  30369. /** Returns the standard name of a GM instrument.
  30370. @param midiInstrumentNumber the program number 0 to 127
  30371. @see getProgramChangeNumber
  30372. */
  30373. static const String getGMInstrumentName (int midiInstrumentNumber);
  30374. /** Returns the name of a bank of GM instruments.
  30375. @param midiBankNumber the bank, 0 to 15
  30376. */
  30377. static const String getGMInstrumentBankName (int midiBankNumber);
  30378. /** Returns the standard name of a channel 10 percussion sound.
  30379. @param midiNoteNumber the key number, 35 to 81
  30380. */
  30381. static const String getRhythmInstrumentName (int midiNoteNumber);
  30382. /** Returns the name of a controller type number.
  30383. @see getControllerNumber
  30384. */
  30385. static const String getControllerName (int controllerNumber);
  30386. private:
  30387. double timeStamp;
  30388. uint8* data;
  30389. int size;
  30390. #ifndef DOXYGEN
  30391. union
  30392. {
  30393. uint8 asBytes[4];
  30394. uint32 asInt32;
  30395. } preallocatedData;
  30396. #endif
  30397. };
  30398. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  30399. /*** End of inlined file: juce_MidiMessage.h ***/
  30400. class MidiInput;
  30401. /**
  30402. Receives incoming messages from a physical MIDI input device.
  30403. This class is overridden to handle incoming midi messages. See the MidiInput
  30404. class for more details.
  30405. @see MidiInput
  30406. */
  30407. class JUCE_API MidiInputCallback
  30408. {
  30409. public:
  30410. /** Destructor. */
  30411. virtual ~MidiInputCallback() {}
  30412. /** Receives an incoming message.
  30413. A MidiInput object will call this method when a midi event arrives. It'll be
  30414. called on a high-priority system thread, so avoid doing anything time-consuming
  30415. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  30416. for queueing incoming messages for use later.
  30417. @param source the MidiInput object that generated the message
  30418. @param message the incoming message. The message's timestamp is set to a value
  30419. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  30420. time when the message arrived.
  30421. */
  30422. virtual void handleIncomingMidiMessage (MidiInput* source,
  30423. const MidiMessage& message) = 0;
  30424. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  30425. If a long sysex message is broken up into multiple packets, this callback is made
  30426. for each packet that arrives until the message is finished, at which point
  30427. the normal handleIncomingMidiMessage() callback will be made with the entire
  30428. message.
  30429. The message passed in will contain the start of a sysex, but won't be finished
  30430. with the terminating 0xf7 byte.
  30431. */
  30432. virtual void handlePartialSysexMessage (MidiInput* source,
  30433. const uint8* messageData,
  30434. const int numBytesSoFar,
  30435. const double timestamp)
  30436. {
  30437. // (this bit is just to avoid compiler warnings about unused variables)
  30438. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  30439. }
  30440. };
  30441. /**
  30442. Represents a midi input device.
  30443. To create one of these, use the static getDevices() method to find out what inputs are
  30444. available, and then use the openDevice() method to try to open one.
  30445. @see MidiOutput
  30446. */
  30447. class JUCE_API MidiInput
  30448. {
  30449. public:
  30450. /** Returns a list of the available midi input devices.
  30451. You can open one of the devices by passing its index into the
  30452. openDevice() method.
  30453. @see getDefaultDeviceIndex, openDevice
  30454. */
  30455. static const StringArray getDevices();
  30456. /** Returns the index of the default midi input device to use.
  30457. This refers to the index in the list returned by getDevices().
  30458. */
  30459. static int getDefaultDeviceIndex();
  30460. /** Tries to open one of the midi input devices.
  30461. This will return a MidiInput object if it manages to open it. You can then
  30462. call start() and stop() on this device, and delete it when no longer needed.
  30463. If the device can't be opened, this will return a null pointer.
  30464. @param deviceIndex the index of a device from the list returned by getDevices()
  30465. @param callback the object that will receive the midi messages from this device.
  30466. @see MidiInputCallback, getDevices
  30467. */
  30468. static MidiInput* openDevice (int deviceIndex,
  30469. MidiInputCallback* callback);
  30470. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30471. /** This will try to create a new midi input device (Not available on Windows).
  30472. This will attempt to create a new midi input device with the specified name,
  30473. for other apps to connect to.
  30474. Returns 0 if a device can't be created.
  30475. @param deviceName the name to use for the new device
  30476. @param callback the object that will receive the midi messages from this device.
  30477. */
  30478. static MidiInput* createNewDevice (const String& deviceName,
  30479. MidiInputCallback* callback);
  30480. #endif
  30481. /** Destructor. */
  30482. virtual ~MidiInput();
  30483. /** Returns the name of this device.
  30484. */
  30485. virtual const String getName() const throw() { return name; }
  30486. /** Allows you to set a custom name for the device, in case you don't like the name
  30487. it was given when created.
  30488. */
  30489. virtual void setName (const String& newName) throw() { name = newName; }
  30490. /** Starts the device running.
  30491. After calling this, the device will start sending midi messages to the
  30492. MidiInputCallback object that was specified when the openDevice() method
  30493. was called.
  30494. @see stop
  30495. */
  30496. virtual void start();
  30497. /** Stops the device running.
  30498. @see start
  30499. */
  30500. virtual void stop();
  30501. protected:
  30502. String name;
  30503. void* internal;
  30504. explicit MidiInput (const String& name);
  30505. private:
  30506. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  30507. };
  30508. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  30509. /*** End of inlined file: juce_MidiInput.h ***/
  30510. /*** Start of inlined file: juce_MidiOutput.h ***/
  30511. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  30512. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  30513. /*** Start of inlined file: juce_MidiBuffer.h ***/
  30514. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  30515. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  30516. /**
  30517. Holds a sequence of time-stamped midi events.
  30518. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  30519. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  30520. @see MidiMessage
  30521. */
  30522. class JUCE_API MidiBuffer
  30523. {
  30524. public:
  30525. /** Creates an empty MidiBuffer. */
  30526. MidiBuffer() throw();
  30527. /** Creates a MidiBuffer containing a single midi message. */
  30528. explicit MidiBuffer (const MidiMessage& message) throw();
  30529. /** Creates a copy of another MidiBuffer. */
  30530. MidiBuffer (const MidiBuffer& other) throw();
  30531. /** Makes a copy of another MidiBuffer. */
  30532. MidiBuffer& operator= (const MidiBuffer& other) throw();
  30533. /** Destructor */
  30534. ~MidiBuffer();
  30535. /** Removes all events from the buffer. */
  30536. void clear() throw();
  30537. /** Removes all events between two times from the buffer.
  30538. All events for which (start <= event position < start + numSamples) will
  30539. be removed.
  30540. */
  30541. void clear (int start, int numSamples);
  30542. /** Returns true if the buffer is empty.
  30543. To actually retrieve the events, use a MidiBuffer::Iterator object
  30544. */
  30545. bool isEmpty() const throw();
  30546. /** Counts the number of events in the buffer.
  30547. This is actually quite a slow operation, as it has to iterate through all
  30548. the events, so you might prefer to call isEmpty() if that's all you need
  30549. to know.
  30550. */
  30551. int getNumEvents() const throw();
  30552. /** Adds an event to the buffer.
  30553. The sample number will be used to determine the position of the event in
  30554. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  30555. ignored.
  30556. If an event is added whose sample position is the same as one or more events
  30557. already in the buffer, the new event will be placed after the existing ones.
  30558. To retrieve events, use a MidiBuffer::Iterator object
  30559. */
  30560. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  30561. /** Adds an event to the buffer from raw midi data.
  30562. The sample number will be used to determine the position of the event in
  30563. the buffer, which is always kept sorted.
  30564. If an event is added whose sample position is the same as one or more events
  30565. already in the buffer, the new event will be placed after the existing ones.
  30566. The event data will be inspected to calculate the number of bytes in length that
  30567. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  30568. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  30569. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  30570. add an event at all.
  30571. To retrieve events, use a MidiBuffer::Iterator object
  30572. */
  30573. void addEvent (const void* rawMidiData,
  30574. int maxBytesOfMidiData,
  30575. int sampleNumber);
  30576. /** Adds some events from another buffer to this one.
  30577. @param otherBuffer the buffer containing the events you want to add
  30578. @param startSample the lowest sample number in the source buffer for which
  30579. events should be added. Any source events whose timestamp is
  30580. less than this will be ignored
  30581. @param numSamples the valid range of samples from the source buffer for which
  30582. events should be added - i.e. events in the source buffer whose
  30583. timestamp is greater than or equal to (startSample + numSamples)
  30584. will be ignored. If this value is less than 0, all events after
  30585. startSample will be taken.
  30586. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  30587. that are added to this buffer
  30588. */
  30589. void addEvents (const MidiBuffer& otherBuffer,
  30590. int startSample,
  30591. int numSamples,
  30592. int sampleDeltaToAdd);
  30593. /** Returns the sample number of the first event in the buffer.
  30594. If the buffer's empty, this will just return 0.
  30595. */
  30596. int getFirstEventTime() const throw();
  30597. /** Returns the sample number of the last event in the buffer.
  30598. If the buffer's empty, this will just return 0.
  30599. */
  30600. int getLastEventTime() const throw();
  30601. /** Exchanges the contents of this buffer with another one.
  30602. This is a quick operation, because no memory allocating or copying is done, it
  30603. just swaps the internal state of the two buffers.
  30604. */
  30605. void swapWith (MidiBuffer& other) throw();
  30606. /** Preallocates some memory for the buffer to use.
  30607. This helps to avoid needing to reallocate space when the buffer has messages
  30608. added to it.
  30609. */
  30610. void ensureSize (size_t minimumNumBytes);
  30611. /**
  30612. Used to iterate through the events in a MidiBuffer.
  30613. Note that altering the buffer while an iterator is using it isn't a
  30614. safe operation.
  30615. @see MidiBuffer
  30616. */
  30617. class JUCE_API Iterator
  30618. {
  30619. public:
  30620. /** Creates an Iterator for this MidiBuffer. */
  30621. Iterator (const MidiBuffer& buffer) throw();
  30622. /** Destructor. */
  30623. ~Iterator() throw();
  30624. /** Repositions the iterator so that the next event retrieved will be the first
  30625. one whose sample position is at greater than or equal to the given position.
  30626. */
  30627. void setNextSamplePosition (int samplePosition) throw();
  30628. /** Retrieves a copy of the next event from the buffer.
  30629. @param result on return, this will be the message (the MidiMessage's timestamp
  30630. is not set)
  30631. @param samplePosition on return, this will be the position of the event
  30632. @returns true if an event was found, or false if the iterator has reached
  30633. the end of the buffer
  30634. */
  30635. bool getNextEvent (MidiMessage& result,
  30636. int& samplePosition) throw();
  30637. /** Retrieves the next event from the buffer.
  30638. @param midiData on return, this pointer will be set to a block of data containing
  30639. the midi message. Note that to make it fast, this is a pointer
  30640. directly into the MidiBuffer's internal data, so is only valid
  30641. temporarily until the MidiBuffer is altered.
  30642. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  30643. midi message
  30644. @param samplePosition on return, this will be the position of the event
  30645. @returns true if an event was found, or false if the iterator has reached
  30646. the end of the buffer
  30647. */
  30648. bool getNextEvent (const uint8* &midiData,
  30649. int& numBytesOfMidiData,
  30650. int& samplePosition) throw();
  30651. private:
  30652. const MidiBuffer& buffer;
  30653. const uint8* data;
  30654. JUCE_DECLARE_NON_COPYABLE (Iterator);
  30655. };
  30656. private:
  30657. friend class MidiBuffer::Iterator;
  30658. MemoryBlock data;
  30659. int bytesUsed;
  30660. uint8* getData() const throw();
  30661. uint8* findEventAfter (uint8* d, int samplePosition) const throw();
  30662. static int getEventTime (const void* d) throw();
  30663. static uint16 getEventDataSize (const void* d) throw();
  30664. static uint16 getEventTotalSize (const void* d) throw();
  30665. JUCE_LEAK_DETECTOR (MidiBuffer);
  30666. };
  30667. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  30668. /*** End of inlined file: juce_MidiBuffer.h ***/
  30669. /**
  30670. Controls a physical MIDI output device.
  30671. To create one of these, use the static getDevices() method to get a list of the
  30672. available output devices, then use the openDevice() method to try to open one.
  30673. @see MidiInput
  30674. */
  30675. class JUCE_API MidiOutput : private Thread
  30676. {
  30677. public:
  30678. /** Returns a list of the available midi output devices.
  30679. You can open one of the devices by passing its index into the
  30680. openDevice() method.
  30681. @see getDefaultDeviceIndex, openDevice
  30682. */
  30683. static const StringArray getDevices();
  30684. /** Returns the index of the default midi output device to use.
  30685. This refers to the index in the list returned by getDevices().
  30686. */
  30687. static int getDefaultDeviceIndex();
  30688. /** Tries to open one of the midi output devices.
  30689. This will return a MidiOutput object if it manages to open it. You can then
  30690. send messages to this device, and delete it when no longer needed.
  30691. If the device can't be opened, this will return a null pointer.
  30692. @param deviceIndex the index of a device from the list returned by getDevices()
  30693. @see getDevices
  30694. */
  30695. static MidiOutput* openDevice (int deviceIndex);
  30696. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30697. /** This will try to create a new midi output device (Not available on Windows).
  30698. This will attempt to create a new midi output device that other apps can connect
  30699. to and use as their midi input.
  30700. Returns 0 if a device can't be created.
  30701. @param deviceName the name to use for the new device
  30702. */
  30703. static MidiOutput* createNewDevice (const String& deviceName);
  30704. #endif
  30705. /** Destructor. */
  30706. virtual ~MidiOutput();
  30707. /** Makes this device output a midi message.
  30708. @see MidiMessage
  30709. */
  30710. virtual void sendMessageNow (const MidiMessage& message);
  30711. /** Sends a midi reset to the device. */
  30712. virtual void reset();
  30713. /** Returns the current volume setting for this device. */
  30714. virtual bool getVolume (float& leftVol,
  30715. float& rightVol);
  30716. /** Changes the overall volume for this device. */
  30717. virtual void setVolume (float leftVol,
  30718. float rightVol);
  30719. /** This lets you supply a block of messages that will be sent out at some point
  30720. in the future.
  30721. The MidiOutput class has an internal thread that can send out timestamped
  30722. messages - this appends a set of messages to its internal buffer, ready for
  30723. sending.
  30724. This will only work if you've already started the thread with startBackgroundThread().
  30725. A time is supplied, at which the block of messages should be sent. This time uses
  30726. the same time base as Time::getMillisecondCounter(), and must be in the future.
  30727. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  30728. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  30729. samplesPerSecondForBuffer value is needed to convert this sample position to a
  30730. real time.
  30731. */
  30732. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  30733. double millisecondCounterToStartAt,
  30734. double samplesPerSecondForBuffer);
  30735. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  30736. */
  30737. virtual void clearAllPendingMessages();
  30738. /** Starts up a background thread so that the device can send blocks of data.
  30739. Call this to get the device ready, before using sendBlockOfMessages().
  30740. */
  30741. virtual void startBackgroundThread();
  30742. /** Stops the background thread, and clears any pending midi events.
  30743. @see startBackgroundThread
  30744. */
  30745. virtual void stopBackgroundThread();
  30746. protected:
  30747. void* internal;
  30748. struct PendingMessage
  30749. {
  30750. PendingMessage (const void* data, int len, double timeStamp);
  30751. MidiMessage message;
  30752. PendingMessage* next;
  30753. };
  30754. CriticalSection lock;
  30755. PendingMessage* firstMessage;
  30756. MidiOutput();
  30757. void run();
  30758. private:
  30759. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  30760. };
  30761. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  30762. /*** End of inlined file: juce_MidiOutput.h ***/
  30763. /*** Start of inlined file: juce_ComboBox.h ***/
  30764. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  30765. #define __JUCE_COMBOBOX_JUCEHEADER__
  30766. /*** Start of inlined file: juce_Label.h ***/
  30767. #ifndef __JUCE_LABEL_JUCEHEADER__
  30768. #define __JUCE_LABEL_JUCEHEADER__
  30769. /*** Start of inlined file: juce_TextEditor.h ***/
  30770. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  30771. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  30772. /*** Start of inlined file: juce_Viewport.h ***/
  30773. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  30774. #define __JUCE_VIEWPORT_JUCEHEADER__
  30775. /*** Start of inlined file: juce_ScrollBar.h ***/
  30776. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  30777. #define __JUCE_SCROLLBAR_JUCEHEADER__
  30778. /*** Start of inlined file: juce_Button.h ***/
  30779. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30780. #define __JUCE_BUTTON_JUCEHEADER__
  30781. /*** Start of inlined file: juce_TooltipWindow.h ***/
  30782. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30783. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30784. /*** Start of inlined file: juce_TooltipClient.h ***/
  30785. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30786. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30787. /**
  30788. Components that want to use pop-up tooltips should implement this interface.
  30789. A TooltipWindow will wait for the mouse to hover over a component that
  30790. implements the TooltipClient interface, and when it finds one, it will display
  30791. the tooltip returned by its getTooltip() method.
  30792. @see TooltipWindow, SettableTooltipClient
  30793. */
  30794. class JUCE_API TooltipClient
  30795. {
  30796. public:
  30797. /** Destructor. */
  30798. virtual ~TooltipClient() {}
  30799. /** Returns the string that this object wants to show as its tooltip. */
  30800. virtual const String getTooltip() = 0;
  30801. };
  30802. /**
  30803. An implementation of TooltipClient that stores the tooltip string and a method
  30804. for changing it.
  30805. This makes it easy to add a tooltip to a custom component, by simply adding this
  30806. as a base class and calling setTooltip().
  30807. Many of the Juce widgets already use this as a base class to implement their
  30808. tooltips.
  30809. @see TooltipClient, TooltipWindow
  30810. */
  30811. class JUCE_API SettableTooltipClient : public TooltipClient
  30812. {
  30813. public:
  30814. /** Destructor. */
  30815. virtual ~SettableTooltipClient() {}
  30816. /** Assigns a new tooltip to this object. */
  30817. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  30818. /** Returns the tooltip assigned to this object. */
  30819. virtual const String getTooltip() { return tooltipString; }
  30820. protected:
  30821. SettableTooltipClient() {}
  30822. private:
  30823. String tooltipString;
  30824. };
  30825. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30826. /*** End of inlined file: juce_TooltipClient.h ***/
  30827. /**
  30828. A window that displays a pop-up tooltip when the mouse hovers over another component.
  30829. To enable tooltips in your app, just create a single instance of a TooltipWindow
  30830. object.
  30831. The TooltipWindow object will then stay invisible, waiting until the mouse
  30832. hovers for the specified length of time - it will then see if it's currently
  30833. over a component which implements the TooltipClient interface, and if so,
  30834. it will make itself visible to show the tooltip in the appropriate place.
  30835. @see TooltipClient, SettableTooltipClient
  30836. */
  30837. class JUCE_API TooltipWindow : public Component,
  30838. private Timer
  30839. {
  30840. public:
  30841. /** Creates a tooltip window.
  30842. Make sure your app only creates one instance of this class, otherwise you'll
  30843. get multiple overlaid tooltips appearing. The window will initially be invisible
  30844. and will make itself visible when it needs to display a tip.
  30845. To change the style of tooltips, see the LookAndFeel class for its tooltip
  30846. methods.
  30847. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  30848. otherwise the tooltip will be added to the given parent
  30849. component.
  30850. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  30851. before a tooltip will be shown
  30852. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  30853. */
  30854. explicit TooltipWindow (Component* parentComponent = 0,
  30855. int millisecondsBeforeTipAppears = 700);
  30856. /** Destructor. */
  30857. ~TooltipWindow();
  30858. /** Changes the time before the tip appears.
  30859. This lets you change the value that was set in the constructor.
  30860. */
  30861. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  30862. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  30863. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30864. methods.
  30865. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30866. */
  30867. enum ColourIds
  30868. {
  30869. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  30870. textColourId = 0x1001c00, /**< The colour to use for the text. */
  30871. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  30872. };
  30873. private:
  30874. int millisecondsBeforeTipAppears;
  30875. Point<int> lastMousePos;
  30876. int mouseClicks;
  30877. unsigned int lastCompChangeTime, lastHideTime;
  30878. Component* lastComponentUnderMouse;
  30879. bool changedCompsSinceShown;
  30880. String tipShowing, lastTipUnderMouse;
  30881. void paint (Graphics& g);
  30882. void mouseEnter (const MouseEvent& e);
  30883. void timerCallback();
  30884. static const String getTipFor (Component* c);
  30885. void showFor (const String& tip);
  30886. void hide();
  30887. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  30888. };
  30889. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30890. /*** End of inlined file: juce_TooltipWindow.h ***/
  30891. #if JUCE_VC6
  30892. #define Listener ButtonListener
  30893. #endif
  30894. /**
  30895. A base class for buttons.
  30896. This contains all the logic for button behaviours such as enabling/disabling,
  30897. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  30898. and radio groups, etc.
  30899. @see TextButton, DrawableButton, ToggleButton
  30900. */
  30901. class JUCE_API Button : public Component,
  30902. public SettableTooltipClient,
  30903. public ApplicationCommandManagerListener,
  30904. public ValueListener,
  30905. private KeyListener
  30906. {
  30907. protected:
  30908. /** Creates a button.
  30909. @param buttonName the text to put in the button (the component's name is also
  30910. initially set to this string, but these can be changed later
  30911. using the setName() and setButtonText() methods)
  30912. */
  30913. explicit Button (const String& buttonName);
  30914. public:
  30915. /** Destructor. */
  30916. virtual ~Button();
  30917. /** Changes the button's text.
  30918. @see getButtonText
  30919. */
  30920. void setButtonText (const String& newText);
  30921. /** Returns the text displayed in the button.
  30922. @see setButtonText
  30923. */
  30924. const String getButtonText() const { return text; }
  30925. /** Returns true if the button is currently being held down by the mouse.
  30926. @see isOver
  30927. */
  30928. bool isDown() const throw();
  30929. /** Returns true if the mouse is currently over the button.
  30930. This will be also be true if the mouse is being held down.
  30931. @see isDown
  30932. */
  30933. bool isOver() const throw();
  30934. /** A button has an on/off state associated with it, and this changes that.
  30935. By default buttons are 'off' and for simple buttons that you click to perform
  30936. an action you won't change this. Toggle buttons, however will want to
  30937. change their state when turned on or off.
  30938. @param shouldBeOn whether to set the button's toggle state to be on or
  30939. off. If it's a member of a button group, this will
  30940. always try to turn it on, and to turn off any other
  30941. buttons in the group
  30942. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  30943. the button will be repainted but no notification will
  30944. be sent
  30945. @see getToggleState, setRadioGroupId
  30946. */
  30947. void setToggleState (bool shouldBeOn,
  30948. bool sendChangeNotification);
  30949. /** Returns true if the button in 'on'.
  30950. By default buttons are 'off' and for simple buttons that you click to perform
  30951. an action you won't change this. Toggle buttons, however will want to
  30952. change their state when turned on or off.
  30953. @see setToggleState
  30954. */
  30955. bool getToggleState() const throw() { return isOn.getValue(); }
  30956. /** Returns the Value object that represents the botton's toggle state.
  30957. You can use this Value object to connect the button's state to external values or setters,
  30958. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  30959. your own Value object.
  30960. @see getToggleState, Value
  30961. */
  30962. Value& getToggleStateValue() { return isOn; }
  30963. /** This tells the button to automatically flip the toggle state when
  30964. the button is clicked.
  30965. If set to true, then before the clicked() callback occurs, the toggle-state
  30966. of the button is flipped.
  30967. */
  30968. void setClickingTogglesState (bool shouldToggle) throw();
  30969. /** Returns true if this button is set to be an automatic toggle-button.
  30970. This returns the last value that was passed to setClickingTogglesState().
  30971. */
  30972. bool getClickingTogglesState() const throw();
  30973. /** Enables the button to act as a member of a mutually-exclusive group
  30974. of 'radio buttons'.
  30975. If the group ID is set to a non-zero number, then this button will
  30976. act as part of a group of buttons with the same ID, only one of
  30977. which can be 'on' at the same time. Note that when it's part of
  30978. a group, clicking a toggle-button that's 'on' won't turn it off.
  30979. To find other buttons with the same ID, this button will search through
  30980. its sibling components for ToggleButtons, so all the buttons for a
  30981. particular group must be placed inside the same parent component.
  30982. Set the group ID back to zero if you want it to act as a normal toggle
  30983. button again.
  30984. @see getRadioGroupId
  30985. */
  30986. void setRadioGroupId (int newGroupId);
  30987. /** Returns the ID of the group to which this button belongs.
  30988. (See setRadioGroupId() for an explanation of this).
  30989. */
  30990. int getRadioGroupId() const throw() { return radioGroupId; }
  30991. /**
  30992. Used to receive callbacks when a button is clicked.
  30993. @see Button::addListener, Button::removeListener
  30994. */
  30995. class JUCE_API Listener
  30996. {
  30997. public:
  30998. /** Destructor. */
  30999. virtual ~Listener() {}
  31000. /** Called when the button is clicked. */
  31001. virtual void buttonClicked (Button* button) = 0;
  31002. /** Called when the button's state changes. */
  31003. virtual void buttonStateChanged (Button*) {}
  31004. };
  31005. /** Registers a listener to receive events when this button's state changes.
  31006. If the listener is already registered, this will not register it again.
  31007. @see removeListener
  31008. */
  31009. void addListener (Listener* newListener);
  31010. /** Removes a previously-registered button listener
  31011. @see addListener
  31012. */
  31013. void removeListener (Listener* listener);
  31014. /** Causes the button to act as if it's been clicked.
  31015. This will asynchronously make the button draw itself going down and up, and
  31016. will then call back the clicked() method as if mouse was clicked on it.
  31017. @see clicked
  31018. */
  31019. virtual void triggerClick();
  31020. /** Sets a command ID for this button to automatically invoke when it's clicked.
  31021. When the button is pressed, it will use the given manager to trigger the
  31022. command ID.
  31023. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  31024. before this button is. To disable the command triggering, call this method and
  31025. pass 0 for the parameters.
  31026. If generateTooltip is true, then the button's tooltip will be automatically
  31027. generated based on the name of this command and its current shortcut key.
  31028. @see addShortcut, getCommandID
  31029. */
  31030. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  31031. int commandID,
  31032. bool generateTooltip);
  31033. /** Returns the command ID that was set by setCommandToTrigger().
  31034. */
  31035. int getCommandID() const throw() { return commandID; }
  31036. /** Assigns a shortcut key to trigger the button.
  31037. The button registers itself with its top-level parent component for keypresses.
  31038. Note that a different way of linking buttons to keypresses is by using the
  31039. setCommandToTrigger() method to invoke a command.
  31040. @see clearShortcuts
  31041. */
  31042. void addShortcut (const KeyPress& key);
  31043. /** Removes all key shortcuts that had been set for this button.
  31044. @see addShortcut
  31045. */
  31046. void clearShortcuts();
  31047. /** Returns true if the given keypress is a shortcut for this button.
  31048. @see addShortcut
  31049. */
  31050. bool isRegisteredForShortcut (const KeyPress& key) const;
  31051. /** Sets an auto-repeat speed for the button when it is held down.
  31052. (Auto-repeat is disabled by default).
  31053. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  31054. triggering the next click. If this is zero, auto-repeat
  31055. is disabled
  31056. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  31057. triggered
  31058. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  31059. get faster, the longer the button is held down, up to the
  31060. minimum interval specified here
  31061. */
  31062. void setRepeatSpeed (int initialDelayInMillisecs,
  31063. int repeatDelayInMillisecs,
  31064. int minimumDelayInMillisecs = -1) throw();
  31065. /** Sets whether the button click should happen when the mouse is pressed or released.
  31066. By default the button is only considered to have been clicked when the mouse is
  31067. released, but setting this to true will make it call the clicked() method as soon
  31068. as the button is pressed.
  31069. This is useful if the button is being used to show a pop-up menu, as it allows
  31070. the click to be used as a drag onto the menu.
  31071. */
  31072. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  31073. /** Returns the number of milliseconds since the last time the button
  31074. went into the 'down' state.
  31075. */
  31076. uint32 getMillisecondsSinceButtonDown() const throw();
  31077. /** Sets the tooltip for this button.
  31078. @see TooltipClient, TooltipWindow
  31079. */
  31080. void setTooltip (const String& newTooltip);
  31081. // (implementation of the TooltipClient method)
  31082. const String getTooltip();
  31083. /** A combination of these flags are used by setConnectedEdges().
  31084. */
  31085. enum ConnectedEdgeFlags
  31086. {
  31087. ConnectedOnLeft = 1,
  31088. ConnectedOnRight = 2,
  31089. ConnectedOnTop = 4,
  31090. ConnectedOnBottom = 8
  31091. };
  31092. /** Hints about which edges of the button might be connected to adjoining buttons.
  31093. The value passed in is a bitwise combination of any of the values in the
  31094. ConnectedEdgeFlags enum.
  31095. E.g. if you are placing two buttons adjacent to each other, you could use this to
  31096. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  31097. without rounded corners on the edges that connect. It's only a hint, so the
  31098. LookAndFeel can choose to ignore it if it's not relevent for this type of
  31099. button.
  31100. */
  31101. void setConnectedEdges (int connectedEdgeFlags);
  31102. /** Returns the set of flags passed into setConnectedEdges(). */
  31103. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  31104. /** Indicates whether the button adjoins another one on its left edge.
  31105. @see setConnectedEdges
  31106. */
  31107. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  31108. /** Indicates whether the button adjoins another one on its right edge.
  31109. @see setConnectedEdges
  31110. */
  31111. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  31112. /** Indicates whether the button adjoins another one on its top edge.
  31113. @see setConnectedEdges
  31114. */
  31115. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  31116. /** Indicates whether the button adjoins another one on its bottom edge.
  31117. @see setConnectedEdges
  31118. */
  31119. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  31120. /** Used by setState(). */
  31121. enum ButtonState
  31122. {
  31123. buttonNormal,
  31124. buttonOver,
  31125. buttonDown
  31126. };
  31127. /** Can be used to force the button into a particular state.
  31128. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  31129. from happening.
  31130. The state that you set here will only last until it is automatically changed when the mouse
  31131. enters or exits the button, or the mouse-button is pressed or released.
  31132. */
  31133. void setState (const ButtonState newState);
  31134. // These are deprecated - please use addListener() and removeListener() instead!
  31135. JUCE_DEPRECATED (void addButtonListener (Listener*));
  31136. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  31137. protected:
  31138. /** This method is called when the button has been clicked.
  31139. Subclasses can override this to perform whatever they actions they need
  31140. to do.
  31141. Alternatively, a ButtonListener can be added to the button, and these listeners
  31142. will be called when the click occurs.
  31143. @see triggerClick
  31144. */
  31145. virtual void clicked();
  31146. /** This method is called when the button has been clicked.
  31147. By default it just calls clicked(), but you might want to override it to handle
  31148. things like clicking when a modifier key is pressed, etc.
  31149. @see ModifierKeys
  31150. */
  31151. virtual void clicked (const ModifierKeys& modifiers);
  31152. /** Subclasses should override this to actually paint the button's contents.
  31153. It's better to use this than the paint method, because it gives you information
  31154. about the over/down state of the button.
  31155. @param g the graphics context to use
  31156. @param isMouseOverButton true if the button is either in the 'over' or
  31157. 'down' state
  31158. @param isButtonDown true if the button should be drawn in the 'down' position
  31159. */
  31160. virtual void paintButton (Graphics& g,
  31161. bool isMouseOverButton,
  31162. bool isButtonDown) = 0;
  31163. /** Called when the button's up/down/over state changes.
  31164. Subclasses can override this if they need to do something special when the button
  31165. goes up or down.
  31166. @see isDown, isOver
  31167. */
  31168. virtual void buttonStateChanged();
  31169. /** @internal */
  31170. virtual void internalClickCallback (const ModifierKeys& modifiers);
  31171. /** @internal */
  31172. void handleCommandMessage (int commandId);
  31173. /** @internal */
  31174. void mouseEnter (const MouseEvent& e);
  31175. /** @internal */
  31176. void mouseExit (const MouseEvent& e);
  31177. /** @internal */
  31178. void mouseDown (const MouseEvent& e);
  31179. /** @internal */
  31180. void mouseDrag (const MouseEvent& e);
  31181. /** @internal */
  31182. void mouseUp (const MouseEvent& e);
  31183. /** @internal */
  31184. bool keyPressed (const KeyPress& key);
  31185. /** @internal */
  31186. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  31187. /** @internal */
  31188. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  31189. /** @internal */
  31190. void paint (Graphics& g);
  31191. /** @internal */
  31192. void parentHierarchyChanged();
  31193. /** @internal */
  31194. void visibilityChanged();
  31195. /** @internal */
  31196. void focusGained (FocusChangeType cause);
  31197. /** @internal */
  31198. void focusLost (FocusChangeType cause);
  31199. /** @internal */
  31200. void enablementChanged();
  31201. /** @internal */
  31202. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  31203. /** @internal */
  31204. void applicationCommandListChanged();
  31205. /** @internal */
  31206. void valueChanged (Value& value);
  31207. private:
  31208. Array <KeyPress> shortcuts;
  31209. WeakReference<Component> keySource;
  31210. String text;
  31211. ListenerList <Listener> buttonListeners;
  31212. class RepeatTimer;
  31213. friend class RepeatTimer;
  31214. friend class ScopedPointer <RepeatTimer>;
  31215. ScopedPointer <RepeatTimer> repeatTimer;
  31216. uint32 buttonPressTime, lastRepeatTime;
  31217. ApplicationCommandManager* commandManagerToUse;
  31218. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  31219. int radioGroupId, commandID, connectedEdgeFlags;
  31220. ButtonState buttonState;
  31221. Value isOn;
  31222. bool lastToggleState : 1;
  31223. bool clickTogglesState : 1;
  31224. bool needsToRelease : 1;
  31225. bool needsRepainting : 1;
  31226. bool isKeyDown : 1;
  31227. bool triggerOnMouseDown : 1;
  31228. bool generateTooltip : 1;
  31229. void repeatTimerCallback();
  31230. RepeatTimer& getRepeatTimer();
  31231. ButtonState updateState();
  31232. ButtonState updateState (bool isOver, bool isDown);
  31233. bool isShortcutPressed() const;
  31234. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  31235. void flashButtonState();
  31236. void sendClickMessage (const ModifierKeys& modifiers);
  31237. void sendStateMessage();
  31238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  31239. };
  31240. #ifndef DOXYGEN
  31241. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  31242. typedef Button::Listener ButtonListener;
  31243. #endif
  31244. #if JUCE_VC6
  31245. #undef Listener
  31246. #endif
  31247. #endif // __JUCE_BUTTON_JUCEHEADER__
  31248. /*** End of inlined file: juce_Button.h ***/
  31249. /**
  31250. A scrollbar component.
  31251. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  31252. sets the range of values it can represent. Then you can use setCurrentRange() to
  31253. change the position and size of the scrollbar's 'thumb'.
  31254. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  31255. the user moves it, and you can use the getCurrentRangeStart() to find out where
  31256. they moved it to.
  31257. The scrollbar will adjust its own visibility according to whether its thumb size
  31258. allows it to actually be scrolled.
  31259. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  31260. instead of handling a scrollbar directly.
  31261. @see ScrollBar::Listener
  31262. */
  31263. class JUCE_API ScrollBar : public Component,
  31264. public AsyncUpdater,
  31265. private Timer
  31266. {
  31267. public:
  31268. /** Creates a Scrollbar.
  31269. @param isVertical whether it should be a vertical or horizontal bar
  31270. @param buttonsAreVisible whether to show the up/down or left/right buttons
  31271. */
  31272. ScrollBar (bool isVertical,
  31273. bool buttonsAreVisible = true);
  31274. /** Destructor. */
  31275. ~ScrollBar();
  31276. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  31277. bool isVertical() const throw() { return vertical; }
  31278. /** Changes the scrollbar's direction.
  31279. You'll also need to resize the bar appropriately - this just changes its internal
  31280. layout.
  31281. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  31282. */
  31283. void setOrientation (bool shouldBeVertical);
  31284. /** Shows or hides the scrollbar's buttons. */
  31285. void setButtonVisibility (bool buttonsAreVisible);
  31286. /** Tells the scrollbar whether to make itself invisible when not needed.
  31287. The default behaviour is for a scrollbar to become invisible when the thumb
  31288. fills the whole of its range (i.e. when it can't be moved). Setting this
  31289. value to false forces the bar to always be visible.
  31290. @see autoHides()
  31291. */
  31292. void setAutoHide (bool shouldHideWhenFullRange);
  31293. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  31294. as its maximum range.
  31295. @see setAutoHide
  31296. */
  31297. bool autoHides() const throw();
  31298. /** Sets the minimum and maximum values that the bar will move between.
  31299. The bar's thumb will always be constrained so that the entire thumb lies
  31300. within this range.
  31301. @see setCurrentRange
  31302. */
  31303. void setRangeLimits (const Range<double>& newRangeLimit);
  31304. /** Sets the minimum and maximum values that the bar will move between.
  31305. The bar's thumb will always be constrained so that the entire thumb lies
  31306. within this range.
  31307. @see setCurrentRange
  31308. */
  31309. void setRangeLimits (double minimum, double maximum);
  31310. /** Returns the current limits on the thumb position.
  31311. @see setRangeLimits
  31312. */
  31313. const Range<double> getRangeLimit() const throw() { return totalRange; }
  31314. /** Returns the lower value that the thumb can be set to.
  31315. This is the value set by setRangeLimits().
  31316. */
  31317. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  31318. /** Returns the upper value that the thumb can be set to.
  31319. This is the value set by setRangeLimits().
  31320. */
  31321. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  31322. /** Changes the position of the scrollbar's 'thumb'.
  31323. If this method call actually changes the scrollbar's position, it will trigger an
  31324. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31325. are registered.
  31326. @see getCurrentRange. setCurrentRangeStart
  31327. */
  31328. void setCurrentRange (const Range<double>& newRange);
  31329. /** Changes the position of the scrollbar's 'thumb'.
  31330. This sets both the position and size of the thumb - to just set the position without
  31331. changing the size, you can use setCurrentRangeStart().
  31332. If this method call actually changes the scrollbar's position, it will trigger an
  31333. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31334. are registered.
  31335. @param newStart the top (or left) of the thumb, in the range
  31336. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  31337. value is beyond these limits, it will be clipped.
  31338. @param newSize the size of the thumb, such that
  31339. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  31340. size is beyond these limits, it will be clipped.
  31341. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  31342. */
  31343. void setCurrentRange (double newStart, double newSize);
  31344. /** Moves the bar's thumb position.
  31345. This will move the thumb position without changing the thumb size. Note
  31346. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  31347. If this method call actually changes the scrollbar's position, it will trigger an
  31348. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  31349. are registered.
  31350. @see setCurrentRange
  31351. */
  31352. void setCurrentRangeStart (double newStart);
  31353. /** Returns the current thumb range.
  31354. @see getCurrentRange, setCurrentRange
  31355. */
  31356. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  31357. /** Returns the position of the top of the thumb.
  31358. @see getCurrentRange, setCurrentRangeStart
  31359. */
  31360. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  31361. /** Returns the current size of the thumb.
  31362. @see getCurrentRange, setCurrentRange
  31363. */
  31364. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  31365. /** Sets the amount by which the up and down buttons will move the bar.
  31366. The value here is in terms of the total range, and is added or subtracted
  31367. from the thumb position when the user clicks an up/down (or left/right) button.
  31368. */
  31369. void setSingleStepSize (double newSingleStepSize);
  31370. /** Moves the scrollbar by a number of single-steps.
  31371. This will move the bar by a multiple of its single-step interval (as
  31372. specified using the setSingleStepSize() method).
  31373. A positive value here will move the bar down or to the right, a negative
  31374. value moves it up or to the left.
  31375. */
  31376. void moveScrollbarInSteps (int howManySteps);
  31377. /** Moves the scroll bar up or down in pages.
  31378. This will move the bar by a multiple of its current thumb size, effectively
  31379. doing a page-up or down.
  31380. A positive value here will move the bar down or to the right, a negative
  31381. value moves it up or to the left.
  31382. */
  31383. void moveScrollbarInPages (int howManyPages);
  31384. /** Scrolls to the top (or left).
  31385. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  31386. */
  31387. void scrollToTop();
  31388. /** Scrolls to the bottom (or right).
  31389. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  31390. */
  31391. void scrollToBottom();
  31392. /** Changes the delay before the up and down buttons autorepeat when they are held
  31393. down.
  31394. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  31395. @see Button::setRepeatSpeed
  31396. */
  31397. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  31398. int repeatDelayInMillisecs,
  31399. int minimumDelayInMillisecs = -1);
  31400. /** A set of colour IDs to use to change the colour of various aspects of the component.
  31401. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31402. methods.
  31403. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31404. */
  31405. enum ColourIds
  31406. {
  31407. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  31408. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  31409. 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. */
  31410. };
  31411. /**
  31412. A class for receiving events from a ScrollBar.
  31413. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  31414. method, and it will be called when the bar's position changes.
  31415. @see ScrollBar::addListener, ScrollBar::removeListener
  31416. */
  31417. class JUCE_API Listener
  31418. {
  31419. public:
  31420. /** Destructor. */
  31421. virtual ~Listener() {}
  31422. /** Called when a ScrollBar is moved.
  31423. @param scrollBarThatHasMoved the bar that has moved
  31424. @param newRangeStart the new range start of this bar
  31425. */
  31426. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  31427. double newRangeStart) = 0;
  31428. };
  31429. /** Registers a listener that will be called when the scrollbar is moved. */
  31430. void addListener (Listener* listener);
  31431. /** Deregisters a previously-registered listener. */
  31432. void removeListener (Listener* listener);
  31433. /** @internal */
  31434. bool keyPressed (const KeyPress& key);
  31435. /** @internal */
  31436. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31437. /** @internal */
  31438. void lookAndFeelChanged();
  31439. /** @internal */
  31440. void handleAsyncUpdate();
  31441. /** @internal */
  31442. void mouseDown (const MouseEvent& e);
  31443. /** @internal */
  31444. void mouseDrag (const MouseEvent& e);
  31445. /** @internal */
  31446. void mouseUp (const MouseEvent& e);
  31447. /** @internal */
  31448. void paint (Graphics& g);
  31449. /** @internal */
  31450. void resized();
  31451. private:
  31452. Range <double> totalRange, visibleRange;
  31453. double singleStepSize, dragStartRange;
  31454. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  31455. int dragStartMousePos, lastMousePos;
  31456. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  31457. bool vertical, isDraggingThumb, autohides;
  31458. class ScrollbarButton;
  31459. friend class ScopedPointer<ScrollbarButton>;
  31460. ScopedPointer<ScrollbarButton> upButton, downButton;
  31461. ListenerList <Listener> listeners;
  31462. void updateThumbPosition();
  31463. void timerCallback();
  31464. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  31465. };
  31466. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  31467. typedef ScrollBar::Listener ScrollBarListener;
  31468. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  31469. /*** End of inlined file: juce_ScrollBar.h ***/
  31470. /**
  31471. A Viewport is used to contain a larger child component, and allows the child
  31472. to be automatically scrolled around.
  31473. To use a Viewport, just create one and set the component that goes inside it
  31474. using the setViewedComponent() method. When the child component changes size,
  31475. the Viewport will adjust its scrollbars accordingly.
  31476. A subclass of the viewport can be created which will receive calls to its
  31477. visibleAreaChanged() method when the subcomponent changes position or size.
  31478. */
  31479. class JUCE_API Viewport : public Component,
  31480. private ComponentListener,
  31481. private ScrollBar::Listener
  31482. {
  31483. public:
  31484. /** Creates a Viewport.
  31485. The viewport is initially empty - use the setViewedComponent() method to
  31486. add a child component for it to manage.
  31487. */
  31488. explicit Viewport (const String& componentName = String::empty);
  31489. /** Destructor. */
  31490. ~Viewport();
  31491. /** Sets the component that this viewport will contain and scroll around.
  31492. This will add the given component to this Viewport and position it at (0, 0).
  31493. (Don't add or remove any child components directly using the normal
  31494. Component::addChildComponent() methods).
  31495. @param newViewedComponent the component to add to this viewport, or null to remove
  31496. the current component.
  31497. @param deleteComponentWhenNoLongerNeeded if true, the component will be deleted
  31498. automatically when the viewport is deleted or when a different
  31499. component is added. If false, the caller must manage the lifetime
  31500. of the component
  31501. @see getViewedComponent
  31502. */
  31503. void setViewedComponent (Component* newViewedComponent,
  31504. bool deleteComponentWhenNoLongerNeeded = true);
  31505. /** Returns the component that's currently being used inside the Viewport.
  31506. @see setViewedComponent
  31507. */
  31508. Component* getViewedComponent() const throw() { return contentComp; }
  31509. /** Changes the position of the viewed component.
  31510. The inner component will be moved so that the pixel at the top left of
  31511. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  31512. within the inner component.
  31513. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31514. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31515. */
  31516. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  31517. /** Changes the position of the viewed component.
  31518. The inner component will be moved so that the pixel at the top left of
  31519. the viewport will be the pixel at the specified coordinates within the
  31520. inner component.
  31521. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31522. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31523. */
  31524. void setViewPosition (const Point<int>& newPosition);
  31525. /** Changes the view position as a proportion of the distance it can move.
  31526. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  31527. visible area in the top-left, and (1, 1) would put it as far down and
  31528. to the right as it's possible to go whilst keeping the child component
  31529. on-screen.
  31530. */
  31531. void setViewPositionProportionately (double proportionX, double proportionY);
  31532. /** If the specified position is at the edges of the viewport, this method scrolls
  31533. the viewport to bring that position nearer to the centre.
  31534. Call this if you're dragging an object inside a viewport and want to make it scroll
  31535. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  31536. useful when auto-scrolling.
  31537. @param mouseX the x position, relative to the Viewport's top-left
  31538. @param mouseY the y position, relative to the Viewport's top-left
  31539. @param distanceFromEdge specifies how close to an edge the position needs to be
  31540. before the viewport should scroll in that direction
  31541. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  31542. to scroll by.
  31543. @returns true if the viewport was scrolled
  31544. */
  31545. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  31546. /** Returns the position within the child component of the top-left of its visible area.
  31547. */
  31548. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  31549. /** Returns the position within the child component of the top-left of its visible area.
  31550. @see getViewWidth, setViewPosition
  31551. */
  31552. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  31553. /** Returns the position within the child component of the top-left of its visible area.
  31554. @see getViewHeight, setViewPosition
  31555. */
  31556. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  31557. /** Returns the width of the visible area of the child component.
  31558. This may be less than the width of this Viewport if there's a vertical scrollbar
  31559. or if the child component is itself smaller.
  31560. */
  31561. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  31562. /** Returns the height of the visible area of the child component.
  31563. This may be less than the height of this Viewport if there's a horizontal scrollbar
  31564. or if the child component is itself smaller.
  31565. */
  31566. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  31567. /** Returns the width available within this component for the contents.
  31568. This will be the width of the viewport component minus the width of a
  31569. vertical scrollbar (if visible).
  31570. */
  31571. int getMaximumVisibleWidth() const;
  31572. /** Returns the height available within this component for the contents.
  31573. This will be the height of the viewport component minus the space taken up
  31574. by a horizontal scrollbar (if visible).
  31575. */
  31576. int getMaximumVisibleHeight() const;
  31577. /** Callback method that is called when the visible area changes.
  31578. This will be called when the visible area is moved either be scrolling or
  31579. by calls to setViewPosition(), etc.
  31580. */
  31581. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  31582. /** Turns scrollbars on or off.
  31583. If set to false, the scrollbars won't ever appear. When true (the default)
  31584. they will appear only when needed.
  31585. */
  31586. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  31587. bool showHorizontalScrollbarIfNeeded);
  31588. /** True if the vertical scrollbar is enabled.
  31589. @see setScrollBarsShown
  31590. */
  31591. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  31592. /** True if the horizontal scrollbar is enabled.
  31593. @see setScrollBarsShown
  31594. */
  31595. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  31596. /** Changes the width of the scrollbars.
  31597. If this isn't specified, the default width from the LookAndFeel class will be used.
  31598. @see LookAndFeel::getDefaultScrollbarWidth
  31599. */
  31600. void setScrollBarThickness (int thickness);
  31601. /** Returns the thickness of the scrollbars.
  31602. @see setScrollBarThickness
  31603. */
  31604. int getScrollBarThickness() const;
  31605. /** Changes the distance that a single-step click on a scrollbar button
  31606. will move the viewport.
  31607. */
  31608. void setSingleStepSizes (int stepX, int stepY);
  31609. /** Shows or hides the buttons on any scrollbars that are used.
  31610. @see ScrollBar::setButtonVisibility
  31611. */
  31612. void setScrollBarButtonVisibility (bool buttonsVisible);
  31613. /** Returns a pointer to the scrollbar component being used.
  31614. Handy if you need to customise the bar somehow.
  31615. */
  31616. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  31617. /** Returns a pointer to the scrollbar component being used.
  31618. Handy if you need to customise the bar somehow.
  31619. */
  31620. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  31621. /** @internal */
  31622. void resized();
  31623. /** @internal */
  31624. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  31625. /** @internal */
  31626. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31627. /** @internal */
  31628. bool keyPressed (const KeyPress& key);
  31629. /** @internal */
  31630. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  31631. /** @internal */
  31632. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31633. private:
  31634. WeakReference<Component> contentComp;
  31635. Rectangle<int> lastVisibleArea;
  31636. int scrollBarThickness;
  31637. int singleStepX, singleStepY;
  31638. bool showHScrollbar, showVScrollbar, deleteContent;
  31639. Component contentHolder;
  31640. ScrollBar verticalScrollBar;
  31641. ScrollBar horizontalScrollBar;
  31642. void updateVisibleArea();
  31643. void deleteContentComp();
  31644. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  31645. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  31646. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  31647. #endif
  31648. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  31649. };
  31650. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  31651. /*** End of inlined file: juce_Viewport.h ***/
  31652. /*** Start of inlined file: juce_PopupMenu.h ***/
  31653. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  31654. #define __JUCE_POPUPMENU_JUCEHEADER__
  31655. /** Creates and displays a popup-menu.
  31656. To show a popup-menu, you create one of these, add some items to it, then
  31657. call its show() method, which returns the id of the item the user selects.
  31658. E.g. @code
  31659. void MyWidget::mouseDown (const MouseEvent& e)
  31660. {
  31661. PopupMenu m;
  31662. m.addItem (1, "item 1");
  31663. m.addItem (2, "item 2");
  31664. const int result = m.show();
  31665. if (result == 0)
  31666. {
  31667. // user dismissed the menu without picking anything
  31668. }
  31669. else if (result == 1)
  31670. {
  31671. // user picked item 1
  31672. }
  31673. else if (result == 2)
  31674. {
  31675. // user picked item 2
  31676. }
  31677. }
  31678. @endcode
  31679. Submenus are easy too: @code
  31680. void MyWidget::mouseDown (const MouseEvent& e)
  31681. {
  31682. PopupMenu subMenu;
  31683. subMenu.addItem (1, "item 1");
  31684. subMenu.addItem (2, "item 2");
  31685. PopupMenu mainMenu;
  31686. mainMenu.addItem (3, "item 3");
  31687. mainMenu.addSubMenu ("other choices", subMenu);
  31688. const int result = m.show();
  31689. ...etc
  31690. }
  31691. @endcode
  31692. */
  31693. class JUCE_API PopupMenu
  31694. {
  31695. public:
  31696. /** Creates an empty popup menu. */
  31697. PopupMenu();
  31698. /** Creates a copy of another menu. */
  31699. PopupMenu (const PopupMenu& other);
  31700. /** Destructor. */
  31701. ~PopupMenu();
  31702. /** Copies this menu from another one. */
  31703. PopupMenu& operator= (const PopupMenu& other);
  31704. /** Resets the menu, removing all its items. */
  31705. void clear();
  31706. /** Appends a new text item for this menu to show.
  31707. @param itemResultId the number that will be returned from the show() method
  31708. if the user picks this item. The value should never be
  31709. zero, because that's used to indicate that the user didn't
  31710. select anything.
  31711. @param itemText the text to show.
  31712. @param isActive if false, the item will be shown 'greyed-out' and can't be
  31713. picked
  31714. @param isTicked if true, the item will be shown with a tick next to it
  31715. @param iconToUse if this is non-zero, it should be an image that will be
  31716. displayed to the left of the item. This method will take its
  31717. own copy of the image passed-in, so there's no need to keep
  31718. it hanging around.
  31719. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  31720. */
  31721. void addItem (int itemResultId,
  31722. const String& itemText,
  31723. bool isActive = true,
  31724. bool isTicked = false,
  31725. const Image& iconToUse = Image::null);
  31726. /** Adds an item that represents one of the commands in a command manager object.
  31727. @param commandManager the manager to use to trigger the command and get information
  31728. about it
  31729. @param commandID the ID of the command
  31730. @param displayName if this is non-empty, then this string will be used instead of
  31731. the command's registered name
  31732. */
  31733. void addCommandItem (ApplicationCommandManager* commandManager,
  31734. int commandID,
  31735. const String& displayName = String::empty);
  31736. /** Appends a text item with a special colour.
  31737. This is the same as addItem(), but specifies a colour to use for the
  31738. text, which will override the default colours that are used by the
  31739. current look-and-feel. See addItem() for a description of the parameters.
  31740. */
  31741. void addColouredItem (int itemResultId,
  31742. const String& itemText,
  31743. const Colour& itemTextColour,
  31744. bool isActive = true,
  31745. bool isTicked = false,
  31746. const Image& iconToUse = Image::null);
  31747. /** Appends a custom menu item that can't be used to trigger a result.
  31748. This will add a user-defined component to use as a menu item. Unlike the
  31749. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  31750. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  31751. delete the component when it's finished, so it's the caller's responsibility
  31752. to manage the component that is passed-in.
  31753. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  31754. detection of a mouse-click on your component, and use that to trigger the
  31755. menu ID specified in itemResultId. If this is false, the menu item can't
  31756. be triggered, so itemResultId is not used.
  31757. @see CustomComponent
  31758. */
  31759. void addCustomItem (int itemResultId,
  31760. Component* customComponent,
  31761. int idealWidth, int idealHeight,
  31762. bool triggerMenuItemAutomaticallyWhenClicked);
  31763. /** Appends a sub-menu.
  31764. If the menu that's passed in is empty, it will appear as an inactive item.
  31765. */
  31766. void addSubMenu (const String& subMenuName,
  31767. const PopupMenu& subMenu,
  31768. bool isActive = true,
  31769. const Image& iconToUse = Image::null,
  31770. bool isTicked = false);
  31771. /** Appends a separator to the menu, to help break it up into sections.
  31772. The menu class is smart enough not to display separators at the top or bottom
  31773. of the menu, and it will replace mutliple adjacent separators with a single
  31774. one, so your code can be quite free and easy about adding these, and it'll
  31775. always look ok.
  31776. */
  31777. void addSeparator();
  31778. /** Adds a non-clickable text item to the menu.
  31779. This is a bold-font items which can be used as a header to separate the items
  31780. into named groups.
  31781. */
  31782. void addSectionHeader (const String& title);
  31783. /** Returns the number of items that the menu currently contains.
  31784. (This doesn't count separators).
  31785. */
  31786. int getNumItems() const throw();
  31787. /** Returns true if the menu contains a command item that triggers the given command. */
  31788. bool containsCommandItem (int commandID) const;
  31789. /** Returns true if the menu contains any items that can be used. */
  31790. bool containsAnyActiveItems() const throw();
  31791. /** Class used to create a set of options to pass to the show() method.
  31792. You can chain together a series of calls to this class's methods to create
  31793. a set of whatever options you want to specify.
  31794. E.g. @code
  31795. PopupMenu menu;
  31796. ...
  31797. menu.showMenu (PopupMenu::Options().withMaximumWidth (100),
  31798. .withMaximumNumColumns (3)
  31799. .withTargetComponent (myComp));
  31800. @endcode
  31801. */
  31802. class JUCE_API Options
  31803. {
  31804. public:
  31805. Options();
  31806. const Options withTargetComponent (Component* targetComponent) const;
  31807. const Options withTargetScreenArea (const Rectangle<int>& targetArea) const;
  31808. const Options withMinimumWidth (int minWidth) const;
  31809. const Options withMaximumNumColumns (int maxNumColumns) const;
  31810. const Options withStandardItemHeight (int standardHeight) const;
  31811. const Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  31812. private:
  31813. friend class PopupMenu;
  31814. Rectangle<int> targetArea;
  31815. Component* targetComponent;
  31816. int visibleItemID, minWidth, maxColumns, standardHeight;
  31817. };
  31818. #if JUCE_MODAL_LOOPS_PERMITTED
  31819. /** Displays the menu and waits for the user to pick something.
  31820. This will display the menu modally, and return the ID of the item that the
  31821. user picks. If they click somewhere off the menu to get rid of it without
  31822. choosing anything, this will return 0.
  31823. The current location of the mouse will be used as the position to show the
  31824. menu - to explicitly set the menu's position, use showAt() instead. Depending
  31825. on where this point is on the screen, the menu will appear above, below or
  31826. to the side of the point.
  31827. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  31828. then when the menu first appears, it will make sure
  31829. that this item is visible. So if the menu has too many
  31830. items to fit on the screen, it will be scrolled to a
  31831. position where this item is visible.
  31832. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  31833. than this if some items are too long to fit.
  31834. @param maximumNumColumns if there are too many items to fit on-screen in a single
  31835. vertical column, the menu may be laid out as a series of
  31836. columns - this is the maximum number allowed. To use the
  31837. default value for this (probably about 7), you can pass
  31838. in zero.
  31839. @param standardItemHeight if this is non-zero, it will be used as the standard
  31840. height for menu items (apart from custom items)
  31841. @param callback if this is non-zero, the menu will be launched asynchronously,
  31842. returning immediately, and the callback will receive a
  31843. call when the menu is either dismissed or has an item
  31844. selected. This object will be owned and deleted by the
  31845. system, so make sure that it works safely and that any
  31846. pointers that it uses are safely within scope.
  31847. @see showAt
  31848. */
  31849. int show (int itemIdThatMustBeVisible = 0,
  31850. int minimumWidth = 0,
  31851. int maximumNumColumns = 0,
  31852. int standardItemHeight = 0,
  31853. ModalComponentManager::Callback* callback = 0);
  31854. /** Displays the menu at a specific location.
  31855. This is the same as show(), but uses a specific location (in global screen
  31856. co-ordinates) rather than the current mouse position.
  31857. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  31858. will be adjacent. Depending on where this is, the menu will decide which edge to
  31859. attach itself to, in order to fit itself fully on-screen. If you just want to
  31860. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  31861. with the position that you want.
  31862. @see show()
  31863. */
  31864. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  31865. int itemIdThatMustBeVisible = 0,
  31866. int minimumWidth = 0,
  31867. int maximumNumColumns = 0,
  31868. int standardItemHeight = 0,
  31869. ModalComponentManager::Callback* callback = 0);
  31870. /** Displays the menu as if it's attached to a component such as a button.
  31871. This is similar to showAt(), but will position it next to the given component, e.g.
  31872. so that the menu's edge is aligned with that of the component. This is intended for
  31873. things like buttons that trigger a pop-up menu.
  31874. */
  31875. int showAt (Component* componentToAttachTo,
  31876. int itemIdThatMustBeVisible = 0,
  31877. int minimumWidth = 0,
  31878. int maximumNumColumns = 0,
  31879. int standardItemHeight = 0,
  31880. ModalComponentManager::Callback* callback = 0);
  31881. /** Displays and runs the menu modally, with a set of options.
  31882. */
  31883. int showMenu (const Options& options);
  31884. #endif
  31885. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  31886. void showMenuAsync (const Options& options,
  31887. ModalComponentManager::Callback* callback);
  31888. /** Closes any menus that are currently open.
  31889. This might be useful if you have a situation where your window is being closed
  31890. by some means other than a user action, and you'd like to make sure that menus
  31891. aren't left hanging around.
  31892. */
  31893. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  31894. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  31895. This can be called before show() if you need a customised menu. Be careful
  31896. not to delete the LookAndFeel object before the menu has been deleted.
  31897. */
  31898. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  31899. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  31900. These constants can be used either via the LookAndFeel::setColour()
  31901. method for the look and feel that is set for this menu with setLookAndFeel()
  31902. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  31903. */
  31904. enum ColourIds
  31905. {
  31906. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  31907. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  31908. colour is specified when the item is added). */
  31909. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  31910. addSectionHeader() method). */
  31911. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  31912. highlighted menu item. */
  31913. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  31914. highlighted item. */
  31915. };
  31916. /**
  31917. Allows you to iterate through the items in a pop-up menu, and examine
  31918. their properties.
  31919. To use this, just create one and repeatedly call its next() method. When this
  31920. returns true, all the member variables of the iterator are filled-out with
  31921. information describing the menu item. When it returns false, the end of the
  31922. list has been reached.
  31923. */
  31924. class JUCE_API MenuItemIterator
  31925. {
  31926. public:
  31927. /** Creates an iterator that will scan through the items in the specified
  31928. menu.
  31929. Be careful not to add any items to a menu while it is being iterated,
  31930. or things could get out of step.
  31931. */
  31932. MenuItemIterator (const PopupMenu& menu);
  31933. /** Destructor. */
  31934. ~MenuItemIterator();
  31935. /** Returns true if there is another item, and sets up all this object's
  31936. member variables to reflect that item's properties.
  31937. */
  31938. bool next();
  31939. String itemName;
  31940. const PopupMenu* subMenu;
  31941. int itemId;
  31942. bool isSeparator;
  31943. bool isTicked;
  31944. bool isEnabled;
  31945. bool isCustomComponent;
  31946. bool isSectionHeader;
  31947. const Colour* customColour;
  31948. Image customImage;
  31949. ApplicationCommandManager* commandManager;
  31950. private:
  31951. const PopupMenu& menu;
  31952. int index;
  31953. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  31954. };
  31955. /** A user-defined copmonent that can be used as an item in a popup menu.
  31956. @see PopupMenu::addCustomItem
  31957. */
  31958. class JUCE_API CustomComponent : public Component,
  31959. public ReferenceCountedObject
  31960. {
  31961. public:
  31962. /** Creates a custom item.
  31963. If isTriggeredAutomatically is true, then the menu will automatically detect
  31964. a mouse-click on this component and use that to invoke the menu item. If it's
  31965. false, then it's up to your class to manually trigger the item when it wants to.
  31966. */
  31967. CustomComponent (bool isTriggeredAutomatically = true);
  31968. /** Destructor. */
  31969. ~CustomComponent();
  31970. /** Returns a rectangle with the size that this component would like to have.
  31971. Note that the size which this method returns isn't necessarily the one that
  31972. the menu will give it, as the items will be stretched to have a uniform width.
  31973. */
  31974. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  31975. /** Dismisses the menu, indicating that this item has been chosen.
  31976. This will cause the menu to exit from its modal state, returning
  31977. this item's id as the result.
  31978. */
  31979. void triggerMenuItem();
  31980. /** Returns true if this item should be highlighted because the mouse is over it.
  31981. You can call this method in your paint() method to find out whether
  31982. to draw a highlight.
  31983. */
  31984. bool isItemHighlighted() const throw() { return isHighlighted; }
  31985. /** @internal */
  31986. bool isTriggeredAutomatically() const throw() { return triggeredAutomatically; }
  31987. /** @internal */
  31988. void setHighlighted (bool shouldBeHighlighted);
  31989. private:
  31990. bool isHighlighted, triggeredAutomatically;
  31991. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  31992. };
  31993. /** Appends a custom menu item.
  31994. This will add a user-defined component to use as a menu item. The component
  31995. passed in will be deleted by this menu when it's no longer needed.
  31996. @see CustomComponent
  31997. */
  31998. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  31999. private:
  32000. class Item;
  32001. class ItemComponent;
  32002. class Window;
  32003. friend class MenuItemIterator;
  32004. friend class ItemComponent;
  32005. friend class Window;
  32006. friend class CustomComponent;
  32007. friend class MenuBarComponent;
  32008. friend class OwnedArray <Item>;
  32009. friend class OwnedArray <ItemComponent>;
  32010. friend class ScopedPointer <Window>;
  32011. OwnedArray <Item> items;
  32012. LookAndFeel* lookAndFeel;
  32013. bool separatorPending;
  32014. void addSeparatorIfPending();
  32015. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  32016. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  32017. JUCE_LEAK_DETECTOR (PopupMenu);
  32018. };
  32019. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  32020. /*** End of inlined file: juce_PopupMenu.h ***/
  32021. /*** Start of inlined file: juce_TextInputTarget.h ***/
  32022. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32023. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32024. /**
  32025. An abstract base class which can be implemented by components that function as
  32026. text editors.
  32027. This class allows different types of text editor component to provide a uniform
  32028. interface, which can be used by things like OS-specific input methods, on-screen
  32029. keyboards, etc.
  32030. */
  32031. class JUCE_API TextInputTarget
  32032. {
  32033. public:
  32034. /** */
  32035. TextInputTarget() {}
  32036. /** Destructor. */
  32037. virtual ~TextInputTarget() {}
  32038. /** Returns true if this input target is currently accepting input.
  32039. For example, a text editor might return false if it's in read-only mode.
  32040. */
  32041. virtual bool isTextInputActive() const = 0;
  32042. /** Returns the extents of the selected text region, or an empty range if
  32043. nothing is selected,
  32044. */
  32045. virtual const Range<int> getHighlightedRegion() const = 0;
  32046. /** Sets the currently-selected text region. */
  32047. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  32048. /** Sets a number of temporarily underlined sections.
  32049. This is needed by MS Windows input method UI.
  32050. */
  32051. virtual void setTemporaryUnderlining (const Array <Range<int> >& underlinedRegions) = 0;
  32052. /** Returns a specified sub-section of the text. */
  32053. virtual const String getTextInRange (const Range<int>& range) const = 0;
  32054. /** Inserts some text, overwriting the selected text region, if there is one. */
  32055. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  32056. /** Returns the position of the caret, relative to the component's origin. */
  32057. virtual const Rectangle<int> getCaretRectangle() = 0;
  32058. };
  32059. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  32060. /*** End of inlined file: juce_TextInputTarget.h ***/
  32061. /*** Start of inlined file: juce_CaretComponent.h ***/
  32062. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  32063. #define __JUCE_CARETCOMPONENT_JUCEHEADER__
  32064. /**
  32065. */
  32066. class JUCE_API CaretComponent : public Component,
  32067. public Timer
  32068. {
  32069. public:
  32070. /** Creates the caret component.
  32071. The keyFocusOwner is an optional component which the caret will check, making
  32072. itself visible only when the keyFocusOwner has keyboard focus.
  32073. */
  32074. CaretComponent (Component* keyFocusOwner);
  32075. /** Destructor. */
  32076. ~CaretComponent();
  32077. /** Sets the caret's position to place it next to the given character.
  32078. The area is the rectangle containing the entire character that the caret is
  32079. positioned on, so by default a vertical-line caret may choose to just show itself
  32080. at the left of this area. You can override this method to customise its size.
  32081. This method will also force the caret to reset its timer and become visible (if
  32082. appropriate), so that as it moves, you can see where it is.
  32083. */
  32084. virtual void setCaretPosition (const Rectangle<int>& characterArea);
  32085. /** A set of colour IDs to use to change the colour of various aspects of the caret.
  32086. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32087. methods.
  32088. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32089. */
  32090. enum ColourIds
  32091. {
  32092. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  32093. };
  32094. /** @internal */
  32095. void paint (Graphics& g);
  32096. /** @internal */
  32097. void timerCallback();
  32098. private:
  32099. Component* owner;
  32100. bool shouldBeShown() const;
  32101. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  32102. };
  32103. #endif // __JUCE_CARETCOMPONENT_JUCEHEADER__
  32104. /*** End of inlined file: juce_CaretComponent.h ***/
  32105. /**
  32106. A component containing text that can be edited.
  32107. A TextEditor can either be in single- or multi-line mode, and supports mixed
  32108. fonts and colours.
  32109. @see TextEditor::Listener, Label
  32110. */
  32111. class JUCE_API TextEditor : public Component,
  32112. public TextInputTarget,
  32113. public SettableTooltipClient
  32114. {
  32115. public:
  32116. /** Creates a new, empty text editor.
  32117. @param componentName the name to pass to the component for it to use as its name
  32118. @param passwordCharacter if this is not zero, this character will be used as a replacement
  32119. for all characters that are drawn on screen - e.g. to create
  32120. a password-style textbox containing circular blobs instead of text,
  32121. you could set this value to 0x25cf, which is the unicode character
  32122. for a black splodge (not all fonts include this, though), or 0x2022,
  32123. which is a bullet (probably the best choice for linux).
  32124. */
  32125. explicit TextEditor (const String& componentName = String::empty,
  32126. juce_wchar passwordCharacter = 0);
  32127. /** Destructor. */
  32128. virtual ~TextEditor();
  32129. /** Puts the editor into either multi- or single-line mode.
  32130. By default, the editor will be in single-line mode, so use this if you need a multi-line
  32131. editor.
  32132. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  32133. on if you want a multi-line editor with line-breaks.
  32134. @see isMultiLine, setReturnKeyStartsNewLine
  32135. */
  32136. void setMultiLine (bool shouldBeMultiLine,
  32137. bool shouldWordWrap = true);
  32138. /** Returns true if the editor is in multi-line mode.
  32139. */
  32140. bool isMultiLine() const;
  32141. /** Changes the behaviour of the return key.
  32142. If set to true, the return key will insert a new-line into the text; if false
  32143. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  32144. method. By default this is set to false, and when true it will only insert
  32145. new-lines when in multi-line mode (see setMultiLine()).
  32146. */
  32147. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  32148. /** Returns the value set by setReturnKeyStartsNewLine().
  32149. See setReturnKeyStartsNewLine() for more info.
  32150. */
  32151. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  32152. /** Indicates whether the tab key should be accepted and used to input a tab character,
  32153. or whether it gets ignored.
  32154. By default the tab key is ignored, so that it can be used to switch keyboard focus
  32155. between components.
  32156. */
  32157. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  32158. /** Returns true if the tab key is being used for input.
  32159. @see setTabKeyUsedAsCharacter
  32160. */
  32161. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  32162. /** Changes the editor to read-only mode.
  32163. By default, the text editor is not read-only. If you're making it read-only, you
  32164. might also want to call setCaretVisible (false) to get rid of the caret.
  32165. The text can still be highlighted and copied when in read-only mode.
  32166. @see isReadOnly, setCaretVisible
  32167. */
  32168. void setReadOnly (bool shouldBeReadOnly);
  32169. /** Returns true if the editor is in read-only mode.
  32170. */
  32171. bool isReadOnly() const;
  32172. /** Makes the caret visible or invisible.
  32173. By default the caret is visible.
  32174. @see setCaretColour, setCaretPosition
  32175. */
  32176. void setCaretVisible (bool shouldBeVisible);
  32177. /** Returns true if the caret is enabled.
  32178. @see setCaretVisible
  32179. */
  32180. bool isCaretVisible() const { return caret != 0; }
  32181. /** Enables/disables a vertical scrollbar.
  32182. (This only applies when in multi-line mode). When the text gets too long to fit
  32183. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  32184. this is enabled, the scrollbar will be hidden unless it's needed.
  32185. By default the scrollbar is enabled.
  32186. */
  32187. void setScrollbarsShown (bool shouldBeEnabled);
  32188. /** Returns true if scrollbars are enabled.
  32189. @see setScrollbarsShown
  32190. */
  32191. bool areScrollbarsShown() const { return scrollbarVisible; }
  32192. /** Changes the password character used to disguise the text.
  32193. @param passwordCharacter if this is not zero, this character will be used as a replacement
  32194. for all characters that are drawn on screen - e.g. to create
  32195. a password-style textbox containing circular blobs instead of text,
  32196. you could set this value to 0x25cf, which is the unicode character
  32197. for a black splodge (not all fonts include this, though), or 0x2022,
  32198. which is a bullet (probably the best choice for linux).
  32199. */
  32200. void setPasswordCharacter (juce_wchar passwordCharacter);
  32201. /** Returns the current password character.
  32202. @see setPasswordCharacter
  32203. */
  32204. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  32205. /** Allows a right-click menu to appear for the editor.
  32206. (This defaults to being enabled).
  32207. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  32208. of options such as cut/copy/paste, undo/redo, etc.
  32209. */
  32210. void setPopupMenuEnabled (bool menuEnabled);
  32211. /** Returns true if the right-click menu is enabled.
  32212. @see setPopupMenuEnabled
  32213. */
  32214. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  32215. /** Returns true if a popup-menu is currently being displayed.
  32216. */
  32217. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  32218. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  32219. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32220. methods.
  32221. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32222. */
  32223. enum ColourIds
  32224. {
  32225. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  32226. transparent if necessary. */
  32227. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  32228. that because the editor can contain multiple colours, calling this
  32229. method won't change the colour of existing text - to do that, call
  32230. applyFontToAllText() after calling this method.*/
  32231. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  32232. the text - this can be transparent if you don't want to show any
  32233. highlighting.*/
  32234. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  32235. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  32236. the edge of the component. */
  32237. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  32238. the edge of the component when it has focus. */
  32239. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  32240. around the edge of the editor. */
  32241. };
  32242. /** Sets the font to use for newly added text.
  32243. This will change the font that will be used next time any text is added or entered
  32244. into the editor. It won't change the font of any existing text - to do that, use
  32245. applyFontToAllText() instead.
  32246. @see applyFontToAllText
  32247. */
  32248. void setFont (const Font& newFont);
  32249. /** Applies a font to all the text in the editor.
  32250. This will also set the current font to use for any new text that's added.
  32251. @see setFont
  32252. */
  32253. void applyFontToAllText (const Font& newFont);
  32254. /** Returns the font that's currently being used for new text.
  32255. @see setFont
  32256. */
  32257. const Font getFont() const;
  32258. /** If set to true, focusing on the editor will highlight all its text.
  32259. (Set to false by default).
  32260. This is useful for boxes where you expect the user to re-enter all the
  32261. text when they focus on the component, rather than editing what's already there.
  32262. */
  32263. void setSelectAllWhenFocused (bool b);
  32264. /** Sets limits on the characters that can be entered.
  32265. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  32266. limit is set
  32267. @param allowedCharacters if this is non-empty, then only characters that occur in
  32268. this string are allowed to be entered into the editor.
  32269. */
  32270. void setInputRestrictions (int maxTextLength,
  32271. const String& allowedCharacters = String::empty);
  32272. /** When the text editor is empty, it can be set to display a message.
  32273. This is handy for things like telling the user what to type in the box - the
  32274. string is only displayed, it's not taken to actually be the contents of
  32275. the editor.
  32276. */
  32277. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  32278. /** Changes the size of the scrollbars that are used.
  32279. Handy if you need smaller scrollbars for a small text box.
  32280. */
  32281. void setScrollBarThickness (int newThicknessPixels);
  32282. /** Shows or hides the buttons on any scrollbars that are used.
  32283. @see ScrollBar::setButtonVisibility
  32284. */
  32285. void setScrollBarButtonVisibility (bool buttonsVisible);
  32286. /**
  32287. Receives callbacks from a TextEditor component when it changes.
  32288. @see TextEditor::addListener
  32289. */
  32290. class JUCE_API Listener
  32291. {
  32292. public:
  32293. /** Destructor. */
  32294. virtual ~Listener() {}
  32295. /** Called when the user changes the text in some way. */
  32296. virtual void textEditorTextChanged (TextEditor& editor);
  32297. /** Called when the user presses the return key. */
  32298. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  32299. /** Called when the user presses the escape key. */
  32300. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  32301. /** Called when the text editor loses focus. */
  32302. virtual void textEditorFocusLost (TextEditor& editor);
  32303. };
  32304. /** Registers a listener to be told when things happen to the text.
  32305. @see removeListener
  32306. */
  32307. void addListener (Listener* newListener);
  32308. /** Deregisters a listener.
  32309. @see addListener
  32310. */
  32311. void removeListener (Listener* listenerToRemove);
  32312. /** Returns the entire contents of the editor. */
  32313. const String getText() const;
  32314. /** Returns a section of the contents of the editor. */
  32315. const String getTextInRange (const Range<int>& textRange) const;
  32316. /** Returns true if there are no characters in the editor.
  32317. This is more efficient than calling getText().isEmpty().
  32318. */
  32319. bool isEmpty() const;
  32320. /** Sets the entire content of the editor.
  32321. This will clear the editor and insert the given text (using the current text colour
  32322. and font). You can set the current text colour using
  32323. @code setColour (TextEditor::textColourId, ...);
  32324. @endcode
  32325. @param newText the text to add
  32326. @param sendTextChangeMessage if true, this will cause a change message to
  32327. be sent to all the listeners.
  32328. @see insertText
  32329. */
  32330. void setText (const String& newText,
  32331. bool sendTextChangeMessage = true);
  32332. /** Returns a Value object that can be used to get or set the text.
  32333. Bear in mind that this operate quite slowly if your text box contains large
  32334. amounts of text, as it needs to dynamically build the string that's involved. It's
  32335. best used for small text boxes.
  32336. */
  32337. Value& getTextValue();
  32338. /** Inserts some text at the current caret position.
  32339. If a section of the text is highlighted, it will be replaced by
  32340. this string, otherwise it will be inserted.
  32341. To delete a section of text, you can use setHighlightedRegion() to
  32342. highlight it, and call insertTextAtCursor (String::empty).
  32343. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  32344. */
  32345. void insertTextAtCaret (const String& textToInsert);
  32346. /** Deletes all the text from the editor. */
  32347. void clear();
  32348. /** Deletes the currently selected region.
  32349. This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
  32350. @see copy, paste, SystemClipboard
  32351. */
  32352. void cut();
  32353. /** Copies the currently selected region to the clipboard.
  32354. @see cut, paste, SystemClipboard
  32355. */
  32356. void copy();
  32357. /** Pastes the contents of the clipboard into the editor at the caret position.
  32358. @see cut, copy, SystemClipboard
  32359. */
  32360. void paste();
  32361. /** Moves the caret to be in front of a given character.
  32362. @see getCaretPosition
  32363. */
  32364. void setCaretPosition (int newIndex);
  32365. /** Returns the current index of the caret.
  32366. @see setCaretPosition
  32367. */
  32368. int getCaretPosition() const;
  32369. /** Attempts to scroll the text editor so that the caret ends up at
  32370. a specified position.
  32371. This won't affect the caret's position within the text, it tries to scroll
  32372. the entire editor vertically and horizontally so that the caret is sitting
  32373. at the given position (relative to the top-left of this component).
  32374. Depending on the amount of text available, it might not be possible to
  32375. scroll far enough for the caret to reach this exact position, but it
  32376. will go as far as it can in that direction.
  32377. */
  32378. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  32379. /** Get the graphical position of the caret.
  32380. The rectangle returned is relative to the component's top-left corner.
  32381. @see scrollEditorToPositionCaret
  32382. */
  32383. const Rectangle<int> getCaretRectangle();
  32384. /** Selects a section of the text. */
  32385. void setHighlightedRegion (const Range<int>& newSelection);
  32386. /** Returns the range of characters that are selected.
  32387. If nothing is selected, this will return an empty range.
  32388. @see setHighlightedRegion
  32389. */
  32390. const Range<int> getHighlightedRegion() const { return selection; }
  32391. /** Returns the section of text that is currently selected. */
  32392. const String getHighlightedText() const;
  32393. /** Finds the index of the character at a given position.
  32394. The co-ordinates are relative to the component's top-left.
  32395. */
  32396. int getTextIndexAt (int x, int y);
  32397. /** Counts the number of characters in the text.
  32398. This is quicker than getting the text as a string if you just need to know
  32399. the length.
  32400. */
  32401. int getTotalNumChars() const;
  32402. /** Returns the total width of the text, as it is currently laid-out.
  32403. This may be larger than the size of the TextEditor, and can change when
  32404. the TextEditor is resized or the text changes.
  32405. */
  32406. int getTextWidth() const;
  32407. /** Returns the maximum height of the text, as it is currently laid-out.
  32408. This may be larger than the size of the TextEditor, and can change when
  32409. the TextEditor is resized or the text changes.
  32410. */
  32411. int getTextHeight() const;
  32412. /** Changes the size of the gap at the top and left-edge of the editor.
  32413. By default there's a gap of 4 pixels.
  32414. */
  32415. void setIndents (int newLeftIndent, int newTopIndent);
  32416. /** Changes the size of border left around the edge of the component.
  32417. @see getBorder
  32418. */
  32419. void setBorder (const BorderSize<int>& border);
  32420. /** Returns the size of border around the edge of the component.
  32421. @see setBorder
  32422. */
  32423. const BorderSize<int> getBorder() const;
  32424. /** Used to disable the auto-scrolling which keeps the caret visible.
  32425. If true (the default), the editor will scroll when the caret moves offscreen. If
  32426. set to false, it won't.
  32427. */
  32428. void setScrollToShowCursor (bool shouldScrollToShowCaret);
  32429. /** @internal */
  32430. void paint (Graphics& g);
  32431. /** @internal */
  32432. void paintOverChildren (Graphics& g);
  32433. /** @internal */
  32434. void mouseDown (const MouseEvent& e);
  32435. /** @internal */
  32436. void mouseUp (const MouseEvent& e);
  32437. /** @internal */
  32438. void mouseDrag (const MouseEvent& e);
  32439. /** @internal */
  32440. void mouseDoubleClick (const MouseEvent& e);
  32441. /** @internal */
  32442. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  32443. /** @internal */
  32444. bool keyPressed (const KeyPress& key);
  32445. /** @internal */
  32446. bool keyStateChanged (bool isKeyDown);
  32447. /** @internal */
  32448. void focusGained (FocusChangeType cause);
  32449. /** @internal */
  32450. void focusLost (FocusChangeType cause);
  32451. /** @internal */
  32452. void resized();
  32453. /** @internal */
  32454. void enablementChanged();
  32455. /** @internal */
  32456. void colourChanged();
  32457. /** @internal */
  32458. void lookAndFeelChanged();
  32459. /** @internal */
  32460. bool isTextInputActive() const;
  32461. /** @internal */
  32462. void setTemporaryUnderlining (const Array <Range<int> >&);
  32463. /** This adds the items to the popup menu.
  32464. By default it adds the cut/copy/paste items, but you can override this if
  32465. you need to replace these with your own items.
  32466. If you want to add your own items to the existing ones, you can override this,
  32467. call the base class's addPopupMenuItems() method, then append your own items.
  32468. When the menu has been shown, performPopupMenuAction() will be called to
  32469. perform the item that the user has chosen.
  32470. The default menu items will be added using item IDs in the range
  32471. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  32472. menu IDs.
  32473. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  32474. a pointer to the info about it, or may be null if the menu is being triggered
  32475. by some other means.
  32476. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  32477. */
  32478. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  32479. const MouseEvent* mouseClickEvent);
  32480. /** This is called to perform one of the items that was shown on the popup menu.
  32481. If you've overridden addPopupMenuItems(), you should also override this
  32482. to perform the actions that you've added.
  32483. If you've overridden addPopupMenuItems() but have still left the default items
  32484. on the menu, remember to call the superclass's performPopupMenuAction()
  32485. so that it can perform the default actions if that's what the user clicked on.
  32486. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  32487. */
  32488. virtual void performPopupMenuAction (int menuItemID);
  32489. protected:
  32490. /** Scrolls the minimum distance needed to get the caret into view. */
  32491. void scrollToMakeSureCursorIsVisible();
  32492. /** @internal */
  32493. void moveCaret (int newCaretPos);
  32494. /** @internal */
  32495. void moveCaretTo (int newPosition, bool isSelecting);
  32496. /** Used internally to dispatch a text-change message. */
  32497. void textChanged();
  32498. /** Begins a new transaction in the UndoManager. */
  32499. void newTransaction();
  32500. /** Used internally to trigger an undo or redo. */
  32501. void doUndoRedo (bool isRedo);
  32502. /** Can be overridden to intercept return key presses directly */
  32503. virtual void returnPressed();
  32504. /** Can be overridden to intercept escape key presses directly */
  32505. virtual void escapePressed();
  32506. /** @internal */
  32507. void handleCommandMessage (int commandId);
  32508. private:
  32509. class Iterator;
  32510. class UniformTextSection;
  32511. class TextHolderComponent;
  32512. class InsertAction;
  32513. class RemoveAction;
  32514. friend class InsertAction;
  32515. friend class RemoveAction;
  32516. ScopedPointer <Viewport> viewport;
  32517. TextHolderComponent* textHolder;
  32518. BorderSize<int> borderSize;
  32519. bool readOnly : 1;
  32520. bool multiline : 1;
  32521. bool wordWrap : 1;
  32522. bool returnKeyStartsNewLine : 1;
  32523. bool popupMenuEnabled : 1;
  32524. bool selectAllTextWhenFocused : 1;
  32525. bool scrollbarVisible : 1;
  32526. bool wasFocused : 1;
  32527. bool keepCaretOnScreen : 1;
  32528. bool tabKeyUsed : 1;
  32529. bool menuActive : 1;
  32530. bool valueTextNeedsUpdating : 1;
  32531. UndoManager undoManager;
  32532. ScopedPointer<CaretComponent> caret;
  32533. int maxTextLength;
  32534. Range<int> selection;
  32535. int leftIndent, topIndent;
  32536. unsigned int lastTransactionTime;
  32537. Font currentFont;
  32538. mutable int totalNumChars;
  32539. int caretPosition;
  32540. Array <UniformTextSection*> sections;
  32541. String textToShowWhenEmpty;
  32542. Colour colourForTextWhenEmpty;
  32543. juce_wchar passwordCharacter;
  32544. Value textValue;
  32545. enum
  32546. {
  32547. notDragging,
  32548. draggingSelectionStart,
  32549. draggingSelectionEnd
  32550. } dragType;
  32551. String allowedCharacters;
  32552. ListenerList <Listener> listeners;
  32553. Array <Range<int> > underlinedSections;
  32554. void coalesceSimilarSections();
  32555. void splitSection (int sectionIndex, int charToSplitAt);
  32556. void clearInternal (UndoManager* um);
  32557. void insert (const String& text, int insertIndex, const Font& font,
  32558. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  32559. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  32560. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  32561. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  32562. void updateCaretPosition();
  32563. void textWasChangedByValue();
  32564. int indexAtPosition (float x, float y);
  32565. int findWordBreakAfter (int position) const;
  32566. int findWordBreakBefore (int position) const;
  32567. friend class TextHolderComponent;
  32568. friend class TextEditorViewport;
  32569. void drawContent (Graphics& g);
  32570. void updateTextHolderSize();
  32571. float getWordWrapWidth() const;
  32572. void timerCallbackInt();
  32573. void repaintText (const Range<int>& range);
  32574. UndoManager* getUndoManager() throw();
  32575. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  32576. };
  32577. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  32578. typedef TextEditor::Listener TextEditorListener;
  32579. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  32580. /*** End of inlined file: juce_TextEditor.h ***/
  32581. #if JUCE_VC6
  32582. #define Listener ButtonListener
  32583. #endif
  32584. /**
  32585. A component that displays a text string, and can optionally become a text
  32586. editor when clicked.
  32587. */
  32588. class JUCE_API Label : public Component,
  32589. public SettableTooltipClient,
  32590. protected TextEditorListener,
  32591. private ComponentListener,
  32592. private ValueListener
  32593. {
  32594. public:
  32595. /** Creates a Label.
  32596. @param componentName the name to give the component
  32597. @param labelText the text to show in the label
  32598. */
  32599. Label (const String& componentName = String::empty,
  32600. const String& labelText = String::empty);
  32601. /** Destructor. */
  32602. ~Label();
  32603. /** Changes the label text.
  32604. If broadcastChangeMessage is true and the new text is different to the current
  32605. text, then the class will broadcast a change message to any Label::Listener objects
  32606. that are registered.
  32607. */
  32608. void setText (const String& newText, bool broadcastChangeMessage);
  32609. /** Returns the label's current text.
  32610. @param returnActiveEditorContents if this is true and the label is currently
  32611. being edited, then this method will return the
  32612. text as it's being shown in the editor. If false,
  32613. then the value returned here won't be updated until
  32614. the user has finished typing and pressed the return
  32615. key.
  32616. */
  32617. const String getText (bool returnActiveEditorContents = false) const;
  32618. /** Returns the text content as a Value object.
  32619. You can call Value::referTo() on this object to make the label read and control
  32620. a Value object that you supply.
  32621. */
  32622. Value& getTextValue() { return textValue; }
  32623. /** Changes the font to use to draw the text.
  32624. @see getFont
  32625. */
  32626. void setFont (const Font& newFont);
  32627. /** Returns the font currently being used.
  32628. @see setFont
  32629. */
  32630. const Font& getFont() const throw();
  32631. /** A set of colour IDs to use to change the colour of various aspects of the label.
  32632. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32633. methods.
  32634. Note that you can also use the constants from TextEditor::ColourIds to change the
  32635. colour of the text editor that is opened when a label is editable.
  32636. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32637. */
  32638. enum ColourIds
  32639. {
  32640. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  32641. textColourId = 0x1000281, /**< The colour for the text. */
  32642. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  32643. Leave this transparent to not have an outline. */
  32644. };
  32645. /** Sets the style of justification to be used for positioning the text.
  32646. (The default is Justification::centredLeft)
  32647. */
  32648. void setJustificationType (const Justification& justification);
  32649. /** Returns the type of justification, as set in setJustificationType(). */
  32650. const Justification getJustificationType() const throw() { return justification; }
  32651. /** Changes the gap that is left between the edge of the component and the text.
  32652. By default there's a small gap left at the sides of the component to allow for
  32653. the drawing of the border, but you can change this if necessary.
  32654. */
  32655. void setBorderSize (int horizontalBorder, int verticalBorder);
  32656. /** Returns the size of the horizontal gap being left around the text.
  32657. */
  32658. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  32659. /** Returns the size of the vertical gap being left around the text.
  32660. */
  32661. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  32662. /** Makes this label "stick to" another component.
  32663. This will cause the label to follow another component around, staying
  32664. either to its left or above it.
  32665. @param owner the component to follow
  32666. @param onLeft if true, the label will stay on the left of its component; if
  32667. false, it will stay above it.
  32668. */
  32669. void attachToComponent (Component* owner, bool onLeft);
  32670. /** If this label has been attached to another component using attachToComponent, this
  32671. returns the other component.
  32672. Returns 0 if the label is not attached.
  32673. */
  32674. Component* getAttachedComponent() const;
  32675. /** If the label is attached to the left of another component, this returns true.
  32676. Returns false if the label is above the other component. This is only relevent if
  32677. attachToComponent() has been called.
  32678. */
  32679. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  32680. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  32681. using ellipsis.
  32682. @see Graphics::drawFittedText
  32683. */
  32684. void setMinimumHorizontalScale (float newScale);
  32685. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  32686. /**
  32687. A class for receiving events from a Label.
  32688. You can register a Label::Listener with a Label using the Label::addListener()
  32689. method, and it will be called when the text of the label changes, either because
  32690. of a call to Label::setText() or by the user editing the text (if the label is
  32691. editable).
  32692. @see Label::addListener, Label::removeListener
  32693. */
  32694. class JUCE_API Listener
  32695. {
  32696. public:
  32697. /** Destructor. */
  32698. virtual ~Listener() {}
  32699. /** Called when a Label's text has changed.
  32700. */
  32701. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  32702. };
  32703. /** Registers a listener that will be called when the label's text changes. */
  32704. void addListener (Listener* listener);
  32705. /** Deregisters a previously-registered listener. */
  32706. void removeListener (Listener* listener);
  32707. /** Makes the label turn into a TextEditor when clicked.
  32708. By default this is turned off.
  32709. If turned on, then single- or double-clicking will turn the label into
  32710. an editor. If the user then changes the text, then the ChangeBroadcaster
  32711. base class will be used to send change messages to any listeners that
  32712. have registered.
  32713. If the user changes the text, the textWasEdited() method will be called
  32714. afterwards, and subclasses can override this if they need to do anything
  32715. special.
  32716. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  32717. @param editOnDoubleClick if true, a double-click is needed to start editing
  32718. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  32719. edited will discard any changes; if false, then this will
  32720. commit the changes.
  32721. @see showEditor, setEditorColours, TextEditor
  32722. */
  32723. void setEditable (bool editOnSingleClick,
  32724. bool editOnDoubleClick = false,
  32725. bool lossOfFocusDiscardsChanges = false);
  32726. /** Returns true if this option was set using setEditable(). */
  32727. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  32728. /** Returns true if this option was set using setEditable(). */
  32729. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  32730. /** Returns true if this option has been set in a call to setEditable(). */
  32731. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  32732. /** Returns true if the user can edit this label's text. */
  32733. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  32734. /** Makes the editor appear as if the label had been clicked by the user.
  32735. @see textWasEdited, setEditable
  32736. */
  32737. void showEditor();
  32738. /** Hides the editor if it was being shown.
  32739. @param discardCurrentEditorContents if true, the label's text will be
  32740. reset to whatever it was before the editor
  32741. was shown; if false, the current contents of the
  32742. editor will be used to set the label's text
  32743. before it is hidden.
  32744. */
  32745. void hideEditor (bool discardCurrentEditorContents);
  32746. /** Returns true if the editor is currently focused and active. */
  32747. bool isBeingEdited() const throw();
  32748. protected:
  32749. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  32750. Subclasses can override this if they need to customise this component in some way.
  32751. */
  32752. virtual TextEditor* createEditorComponent();
  32753. /** Called after the user changes the text. */
  32754. virtual void textWasEdited();
  32755. /** Called when the text has been altered. */
  32756. virtual void textWasChanged();
  32757. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  32758. virtual void editorShown (TextEditor* editorComponent);
  32759. /** Called when the text editor is going to be deleted, after editing has finished. */
  32760. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  32761. /** @internal */
  32762. void paint (Graphics& g);
  32763. /** @internal */
  32764. void resized();
  32765. /** @internal */
  32766. void mouseUp (const MouseEvent& e);
  32767. /** @internal */
  32768. void mouseDoubleClick (const MouseEvent& e);
  32769. /** @internal */
  32770. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  32771. /** @internal */
  32772. void componentParentHierarchyChanged (Component& component);
  32773. /** @internal */
  32774. void componentVisibilityChanged (Component& component);
  32775. /** @internal */
  32776. void inputAttemptWhenModal();
  32777. /** @internal */
  32778. void focusGained (FocusChangeType);
  32779. /** @internal */
  32780. void enablementChanged();
  32781. /** @internal */
  32782. KeyboardFocusTraverser* createFocusTraverser();
  32783. /** @internal */
  32784. void textEditorTextChanged (TextEditor& editor);
  32785. /** @internal */
  32786. void textEditorReturnKeyPressed (TextEditor& editor);
  32787. /** @internal */
  32788. void textEditorEscapeKeyPressed (TextEditor& editor);
  32789. /** @internal */
  32790. void textEditorFocusLost (TextEditor& editor);
  32791. /** @internal */
  32792. void colourChanged();
  32793. /** @internal */
  32794. void valueChanged (Value&);
  32795. private:
  32796. Value textValue;
  32797. String lastTextValue;
  32798. Font font;
  32799. Justification justification;
  32800. ScopedPointer<TextEditor> editor;
  32801. ListenerList<Listener> listeners;
  32802. WeakReference<Component> ownerComponent;
  32803. int horizontalBorderSize, verticalBorderSize;
  32804. float minimumHorizontalScale;
  32805. bool editSingleClick : 1;
  32806. bool editDoubleClick : 1;
  32807. bool lossOfFocusDiscardsChanges : 1;
  32808. bool leftOfOwnerComp : 1;
  32809. bool updateFromTextEditorContents (TextEditor&);
  32810. void callChangeListeners();
  32811. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  32812. };
  32813. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  32814. typedef Label::Listener LabelListener;
  32815. #if JUCE_VC6
  32816. #undef Listener
  32817. #endif
  32818. #endif // __JUCE_LABEL_JUCEHEADER__
  32819. /*** End of inlined file: juce_Label.h ***/
  32820. #if JUCE_VC6
  32821. #define Listener SliderListener
  32822. #endif
  32823. /**
  32824. A component that lets the user choose from a drop-down list of choices.
  32825. The combo-box has a list of text strings, each with an associated id number,
  32826. that will be shown in the drop-down list when the user clicks on the component.
  32827. The currently selected choice is displayed in the combo-box, and this can
  32828. either be read-only text, or editable.
  32829. To find out when the user selects a different item or edits the text, you
  32830. can register a ComboBox::Listener to receive callbacks.
  32831. @see ComboBox::Listener
  32832. */
  32833. class JUCE_API ComboBox : public Component,
  32834. public SettableTooltipClient,
  32835. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  32836. public ValueListener,
  32837. private AsyncUpdater
  32838. {
  32839. public:
  32840. /** Creates a combo-box.
  32841. On construction, the text field will be empty, so you should call the
  32842. setSelectedId() or setText() method to choose the initial value before
  32843. displaying it.
  32844. @param componentName the name to set for the component (see Component::setName())
  32845. */
  32846. explicit ComboBox (const String& componentName = String::empty);
  32847. /** Destructor. */
  32848. ~ComboBox();
  32849. /** Sets whether the test in the combo-box is editable.
  32850. The default state for a new ComboBox is non-editable, and can only be changed
  32851. by choosing from the drop-down list.
  32852. */
  32853. void setEditableText (bool isEditable);
  32854. /** Returns true if the text is directly editable.
  32855. @see setEditableText
  32856. */
  32857. bool isTextEditable() const throw();
  32858. /** Sets the style of justification to be used for positioning the text.
  32859. The default is Justification::centredLeft. The text is displayed using a
  32860. Label component inside the ComboBox.
  32861. */
  32862. void setJustificationType (const Justification& justification);
  32863. /** Returns the current justification for the text box.
  32864. @see setJustificationType
  32865. */
  32866. const Justification getJustificationType() const throw();
  32867. /** Adds an item to be shown in the drop-down list.
  32868. @param newItemText the text of the item to show in the list
  32869. @param newItemId an associated ID number that can be set or retrieved - see
  32870. getSelectedId() and setSelectedId(). Note that this value can not
  32871. be 0!
  32872. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  32873. */
  32874. void addItem (const String& newItemText, int newItemId);
  32875. /** Adds a separator line to the drop-down list.
  32876. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  32877. */
  32878. void addSeparator();
  32879. /** Adds a heading to the drop-down list, so that you can group the items into
  32880. different sections.
  32881. The headings are indented slightly differently to set them apart from the
  32882. items on the list, and obviously can't be selected. You might want to add
  32883. separators between your sections too.
  32884. @see addItem, addSeparator
  32885. */
  32886. void addSectionHeading (const String& headingName);
  32887. /** This allows items in the drop-down list to be selectively disabled.
  32888. When you add an item, it's enabled by default, but you can call this
  32889. method to change its status.
  32890. If you disable an item which is already selected, this won't change the
  32891. current selection - it just stops the user choosing that item from the list.
  32892. */
  32893. void setItemEnabled (int itemId, bool shouldBeEnabled);
  32894. /** Returns true if the given item is enabled. */
  32895. bool isItemEnabled (int itemId) const throw();
  32896. /** Changes the text for an existing item.
  32897. */
  32898. void changeItemText (int itemId, const String& newText);
  32899. /** Removes all the items from the drop-down list.
  32900. If this call causes the content to be cleared, then a change-message
  32901. will be broadcast unless dontSendChangeMessage is true.
  32902. @see addItem, removeItem, getNumItems
  32903. */
  32904. void clear (bool dontSendChangeMessage = false);
  32905. /** Returns the number of items that have been added to the list.
  32906. Note that this doesn't include headers or separators.
  32907. */
  32908. int getNumItems() const throw();
  32909. /** Returns the text for one of the items in the list.
  32910. Note that this doesn't include headers or separators.
  32911. @param index the item's index from 0 to (getNumItems() - 1)
  32912. */
  32913. const String getItemText (int index) const;
  32914. /** Returns the ID for one of the items in the list.
  32915. Note that this doesn't include headers or separators.
  32916. @param index the item's index from 0 to (getNumItems() - 1)
  32917. */
  32918. int getItemId (int index) const throw();
  32919. /** Returns the index in the list of a particular item ID.
  32920. If no such ID is found, this will return -1.
  32921. */
  32922. int indexOfItemId (int itemId) const throw();
  32923. /** Returns the ID of the item that's currently shown in the box.
  32924. If no item is selected, or if the text is editable and the user
  32925. has entered something which isn't one of the items in the list, then
  32926. this will return 0.
  32927. @see setSelectedId, getSelectedItemIndex, getText
  32928. */
  32929. int getSelectedId() const throw();
  32930. /** Returns a Value object that can be used to get or set the selected item's ID.
  32931. You can call Value::referTo() on this object to make the combo box control
  32932. another Value object.
  32933. */
  32934. Value& getSelectedIdAsValue() { return currentId; }
  32935. /** Sets one of the items to be the current selection.
  32936. This will set the ComboBox's text to that of the item that matches
  32937. this ID.
  32938. @param newItemId the new item to select
  32939. @param dontSendChangeMessage if set to true, this method won't trigger a
  32940. change notification
  32941. @see getSelectedId, setSelectedItemIndex, setText
  32942. */
  32943. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  32944. /** Returns the index of the item that's currently shown in the box.
  32945. If no item is selected, or if the text is editable and the user
  32946. has entered something which isn't one of the items in the list, then
  32947. this will return -1.
  32948. @see setSelectedItemIndex, getSelectedId, getText
  32949. */
  32950. int getSelectedItemIndex() const;
  32951. /** Sets one of the items to be the current selection.
  32952. This will set the ComboBox's text to that of the item at the given
  32953. index in the list.
  32954. @param newItemIndex the new item to select
  32955. @param dontSendChangeMessage if set to true, this method won't trigger a
  32956. change notification
  32957. @see getSelectedItemIndex, setSelectedId, setText
  32958. */
  32959. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  32960. /** Returns the text that is currently shown in the combo-box's text field.
  32961. If the ComboBox has editable text, then this text may have been edited
  32962. by the user; otherwise it will be one of the items from the list, or
  32963. possibly an empty string if nothing was selected.
  32964. @see setText, getSelectedId, getSelectedItemIndex
  32965. */
  32966. const String getText() const;
  32967. /** Sets the contents of the combo-box's text field.
  32968. The text passed-in will be set as the current text regardless of whether
  32969. it is one of the items in the list. If the current text isn't one of the
  32970. items, then getSelectedId() will return -1, otherwise it wil return
  32971. the approriate ID.
  32972. @param newText the text to select
  32973. @param dontSendChangeMessage if set to true, this method won't trigger a
  32974. change notification
  32975. @see getText
  32976. */
  32977. void setText (const String& newText, bool dontSendChangeMessage = false);
  32978. /** Programmatically opens the text editor to allow the user to edit the current item.
  32979. This is the same effect as when the box is clicked-on.
  32980. @see Label::showEditor();
  32981. */
  32982. void showEditor();
  32983. /** Pops up the combo box's list. */
  32984. void showPopup();
  32985. /**
  32986. A class for receiving events from a ComboBox.
  32987. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  32988. method, and it will be called when the selected item in the box changes.
  32989. @see ComboBox::addListener, ComboBox::removeListener
  32990. */
  32991. class JUCE_API Listener
  32992. {
  32993. public:
  32994. /** Destructor. */
  32995. virtual ~Listener() {}
  32996. /** Called when a ComboBox has its selected item changed. */
  32997. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  32998. };
  32999. /** Registers a listener that will be called when the box's content changes. */
  33000. void addListener (Listener* listener);
  33001. /** Deregisters a previously-registered listener. */
  33002. void removeListener (Listener* listener);
  33003. /** Sets a message to display when there is no item currently selected.
  33004. @see getTextWhenNothingSelected
  33005. */
  33006. void setTextWhenNothingSelected (const String& newMessage);
  33007. /** Returns the text that is shown when no item is selected.
  33008. @see setTextWhenNothingSelected
  33009. */
  33010. const String getTextWhenNothingSelected() const;
  33011. /** Sets the message to show when there are no items in the list, and the user clicks
  33012. on the drop-down box.
  33013. By default it just says "no choices", but this lets you change it to something more
  33014. meaningful.
  33015. */
  33016. void setTextWhenNoChoicesAvailable (const String& newMessage);
  33017. /** Returns the text shown when no items have been added to the list.
  33018. @see setTextWhenNoChoicesAvailable
  33019. */
  33020. const String getTextWhenNoChoicesAvailable() const;
  33021. /** Gives the ComboBox a tooltip. */
  33022. void setTooltip (const String& newTooltip);
  33023. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  33024. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33025. methods.
  33026. To change the colours of the menu that pops up
  33027. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33028. */
  33029. enum ColourIds
  33030. {
  33031. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  33032. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  33033. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  33034. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  33035. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  33036. };
  33037. /** @internal */
  33038. void labelTextChanged (Label*);
  33039. /** @internal */
  33040. void enablementChanged();
  33041. /** @internal */
  33042. void colourChanged();
  33043. /** @internal */
  33044. void focusGained (Component::FocusChangeType cause);
  33045. /** @internal */
  33046. void focusLost (Component::FocusChangeType cause);
  33047. /** @internal */
  33048. void handleAsyncUpdate();
  33049. /** @internal */
  33050. const String getTooltip() { return label->getTooltip(); }
  33051. /** @internal */
  33052. void mouseDown (const MouseEvent&);
  33053. /** @internal */
  33054. void mouseDrag (const MouseEvent&);
  33055. /** @internal */
  33056. void mouseUp (const MouseEvent&);
  33057. /** @internal */
  33058. void lookAndFeelChanged();
  33059. /** @internal */
  33060. void paint (Graphics&);
  33061. /** @internal */
  33062. void resized();
  33063. /** @internal */
  33064. bool keyStateChanged (bool isKeyDown);
  33065. /** @internal */
  33066. bool keyPressed (const KeyPress&);
  33067. /** @internal */
  33068. void valueChanged (Value&);
  33069. private:
  33070. struct ItemInfo
  33071. {
  33072. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  33073. bool isSeparator() const throw();
  33074. bool isRealItem() const throw();
  33075. String name;
  33076. int itemId;
  33077. bool isEnabled : 1, isHeading : 1;
  33078. };
  33079. OwnedArray <ItemInfo> items;
  33080. Value currentId;
  33081. int lastCurrentId;
  33082. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  33083. ListenerList <Listener> listeners;
  33084. ScopedPointer<Label> label;
  33085. String textWhenNothingSelected, noChoicesMessage;
  33086. ItemInfo* getItemForId (int itemId) const throw();
  33087. ItemInfo* getItemForIndex (int index) const throw();
  33088. bool selectIfEnabled (int index);
  33089. static void popupMenuFinishedCallback (int, ComboBox*);
  33090. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  33091. };
  33092. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  33093. typedef ComboBox::Listener ComboBoxListener;
  33094. #if JUCE_VC6
  33095. #undef Listener
  33096. #endif
  33097. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  33098. /*** End of inlined file: juce_ComboBox.h ***/
  33099. /**
  33100. Manages the state of some audio and midi i/o devices.
  33101. This class keeps tracks of a currently-selected audio device, through
  33102. with which it continuously streams data from an audio callback, as well as
  33103. one or more midi inputs.
  33104. The idea is that your application will create one global instance of this object,
  33105. and let it take care of creating and deleting specific types of audio devices
  33106. internally. So when the device is changed, your callbacks will just keep running
  33107. without having to worry about this.
  33108. The manager can save and reload all of its device settings as XML, which
  33109. makes it very easy for you to save and reload the audio setup of your
  33110. application.
  33111. And to make it easy to let the user change its settings, there's a component
  33112. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  33113. device selection/sample-rate/latency controls.
  33114. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  33115. call addAudioCallback() to register your audio callback with it, and use that to process
  33116. your audio data.
  33117. The manager also acts as a handy hub for incoming midi messages, allowing a
  33118. listener to register for messages from either a specific midi device, or from whatever
  33119. the current default midi input device is. The listener then doesn't have to worry about
  33120. re-registering with different midi devices if they are changed or deleted.
  33121. And yet another neat trick is that amount of CPU time being used is measured and
  33122. available with the getCpuUsage() method.
  33123. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  33124. listeners whenever one of its settings is changed.
  33125. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  33126. */
  33127. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  33128. {
  33129. public:
  33130. /** Creates a default AudioDeviceManager.
  33131. Initially no audio device will be selected. You should call the initialise() method
  33132. and register an audio callback with setAudioCallback() before it'll be able to
  33133. actually make any noise.
  33134. */
  33135. AudioDeviceManager();
  33136. /** Destructor. */
  33137. ~AudioDeviceManager();
  33138. /**
  33139. This structure holds a set of properties describing the current audio setup.
  33140. An AudioDeviceManager uses this class to save/load its current settings, and to
  33141. specify your preferred options when opening a device.
  33142. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  33143. */
  33144. struct JUCE_API AudioDeviceSetup
  33145. {
  33146. /** Creates an AudioDeviceSetup object.
  33147. The default constructor sets all the member variables to indicate default values.
  33148. You can then fill-in any values you want to before passing the object to
  33149. AudioDeviceManager::initialise().
  33150. */
  33151. AudioDeviceSetup();
  33152. bool operator== (const AudioDeviceSetup& other) const;
  33153. /** The name of the audio device used for output.
  33154. The name has to be one of the ones listed by the AudioDeviceManager's currently
  33155. selected device type.
  33156. This may be the same as the input device.
  33157. An empty string indicates the default device.
  33158. */
  33159. String outputDeviceName;
  33160. /** The name of the audio device used for input.
  33161. This may be the same as the output device.
  33162. An empty string indicates the default device.
  33163. */
  33164. String inputDeviceName;
  33165. /** The current sample rate.
  33166. This rate is used for both the input and output devices.
  33167. A value of 0 indicates the default rate.
  33168. */
  33169. double sampleRate;
  33170. /** The buffer size, in samples.
  33171. This buffer size is used for both the input and output devices.
  33172. A value of 0 indicates the default buffer size.
  33173. */
  33174. int bufferSize;
  33175. /** The set of active input channels.
  33176. The bits that are set in this array indicate the channels of the
  33177. input device that are active.
  33178. If useDefaultInputChannels is true, this value is ignored.
  33179. */
  33180. BigInteger inputChannels;
  33181. /** If this is true, it indicates that the inputChannels array
  33182. should be ignored, and instead, the device's default channels
  33183. should be used.
  33184. */
  33185. bool useDefaultInputChannels;
  33186. /** The set of active output channels.
  33187. The bits that are set in this array indicate the channels of the
  33188. input device that are active.
  33189. If useDefaultOutputChannels is true, this value is ignored.
  33190. */
  33191. BigInteger outputChannels;
  33192. /** If this is true, it indicates that the outputChannels array
  33193. should be ignored, and instead, the device's default channels
  33194. should be used.
  33195. */
  33196. bool useDefaultOutputChannels;
  33197. };
  33198. /** Opens a set of audio devices ready for use.
  33199. This will attempt to open either a default audio device, or one that was
  33200. previously saved as XML.
  33201. @param numInputChannelsNeeded a minimum number of input channels needed
  33202. by your app.
  33203. @param numOutputChannelsNeeded a minimum number of output channels to open
  33204. @param savedState either a previously-saved state that was produced
  33205. by createStateXml(), or 0 if you want the manager
  33206. to choose the best device to open.
  33207. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  33208. fails to open, then a default device will be used
  33209. instead. If false, then on failure, no device is
  33210. opened.
  33211. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  33212. name, then that will be used as the default device
  33213. (assuming that there wasn't one specified in the XML).
  33214. The string can actually be a simple wildcard, containing "*"
  33215. and "?" characters
  33216. @param preferredSetupOptions if this is non-null, the structure will be used as the
  33217. set of preferred settings when opening the device. If you
  33218. use this parameter, the preferredDefaultDeviceName
  33219. field will be ignored
  33220. @returns an error message if anything went wrong, or an empty string if it worked ok.
  33221. */
  33222. const String initialise (int numInputChannelsNeeded,
  33223. int numOutputChannelsNeeded,
  33224. const XmlElement* savedState,
  33225. bool selectDefaultDeviceOnFailure,
  33226. const String& preferredDefaultDeviceName = String::empty,
  33227. const AudioDeviceSetup* preferredSetupOptions = 0);
  33228. /** Returns some XML representing the current state of the manager.
  33229. This stores the current device, its samplerate, block size, etc, and
  33230. can be restored later with initialise().
  33231. */
  33232. XmlElement* createStateXml() const;
  33233. /** Returns the current device properties that are in use.
  33234. @see setAudioDeviceSetup
  33235. */
  33236. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  33237. /** Changes the current device or its settings.
  33238. If you want to change a device property, like the current sample rate or
  33239. block size, you can call getAudioDeviceSetup() to retrieve the current
  33240. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  33241. and pass it back into this method to apply the new settings.
  33242. @param newSetup the settings that you'd like to use
  33243. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  33244. settings will be taken as having been explicitly chosen by the
  33245. user, and the next time createStateXml() is called, these settings
  33246. will be returned. If it's false, then the device is treated as a
  33247. temporary or default device, and a call to createStateXml() will
  33248. return either the last settings that were made with treatAsChosenDevice
  33249. as true, or the last XML settings that were passed into initialise().
  33250. @returns an error message if anything went wrong, or an empty string if it worked ok.
  33251. @see getAudioDeviceSetup
  33252. */
  33253. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  33254. bool treatAsChosenDevice);
  33255. /** Returns the currently-active audio device. */
  33256. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  33257. /** Returns the type of audio device currently in use.
  33258. @see setCurrentAudioDeviceType
  33259. */
  33260. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  33261. /** Returns the currently active audio device type object.
  33262. Don't keep a copy of this pointer - it's owned by the device manager and could
  33263. change at any time.
  33264. */
  33265. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  33266. /** Changes the class of audio device being used.
  33267. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  33268. this because there's only one type: CoreAudio.
  33269. For a list of types, see getAvailableDeviceTypes().
  33270. */
  33271. void setCurrentAudioDeviceType (const String& type,
  33272. bool treatAsChosenDevice);
  33273. /** Closes the currently-open device.
  33274. You can call restartLastAudioDevice() later to reopen it in the same state
  33275. that it was just in.
  33276. */
  33277. void closeAudioDevice();
  33278. /** Tries to reload the last audio device that was running.
  33279. Note that this only reloads the last device that was running before
  33280. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  33281. and can only be called after a device has been opened with SetAudioDevice().
  33282. If a device is already open, this call will do nothing.
  33283. */
  33284. void restartLastAudioDevice();
  33285. /** Registers an audio callback to be used.
  33286. The manager will redirect callbacks from whatever audio device is currently
  33287. in use to all registered callback objects. If more than one callback is
  33288. active, they will all be given the same input data, and their outputs will
  33289. be summed.
  33290. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  33291. object before returning.
  33292. To remove a callback, use removeAudioCallback().
  33293. */
  33294. void addAudioCallback (AudioIODeviceCallback* newCallback);
  33295. /** Deregisters a previously added callback.
  33296. If necessary, this method will invoke audioDeviceStopped() on the callback
  33297. object before returning.
  33298. @see addAudioCallback
  33299. */
  33300. void removeAudioCallback (AudioIODeviceCallback* callback);
  33301. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  33302. Returns a value between 0 and 1.0
  33303. */
  33304. double getCpuUsage() const;
  33305. /** Enables or disables a midi input device.
  33306. The list of devices can be obtained with the MidiInput::getDevices() method.
  33307. Any incoming messages from enabled input devices will be forwarded on to all the
  33308. listeners that have been registered with the addMidiInputCallback() method. They
  33309. can either register for messages from a particular device, or from just the
  33310. "default" midi input.
  33311. Routing the midi input via an AudioDeviceManager means that when a listener
  33312. registers for the default midi input, this default device can be changed by the
  33313. manager without the listeners having to know about it or re-register.
  33314. It also means that a listener can stay registered for a midi input that is disabled
  33315. or not present, so that when the input is re-enabled, the listener will start
  33316. receiving messages again.
  33317. @see addMidiInputCallback, isMidiInputEnabled
  33318. */
  33319. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  33320. /** Returns true if a given midi input device is being used.
  33321. @see setMidiInputEnabled
  33322. */
  33323. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  33324. /** Registers a listener for callbacks when midi events arrive from a midi input.
  33325. The device name can be empty to indicate that it wants events from whatever the
  33326. current "default" device is. Or it can be the name of one of the midi input devices
  33327. (see MidiInput::getDevices() for the names).
  33328. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  33329. events forwarded on to listeners.
  33330. */
  33331. void addMidiInputCallback (const String& midiInputDeviceName,
  33332. MidiInputCallback* callback);
  33333. /** Removes a listener that was previously registered with addMidiInputCallback().
  33334. */
  33335. void removeMidiInputCallback (const String& midiInputDeviceName,
  33336. MidiInputCallback* callback);
  33337. /** Sets a midi output device to use as the default.
  33338. The list of devices can be obtained with the MidiOutput::getDevices() method.
  33339. The specified device will be opened automatically and can be retrieved with the
  33340. getDefaultMidiOutput() method.
  33341. Pass in an empty string to deselect all devices. For the default device, you
  33342. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  33343. @see getDefaultMidiOutput, getDefaultMidiOutputName
  33344. */
  33345. void setDefaultMidiOutput (const String& deviceName);
  33346. /** Returns the name of the default midi output.
  33347. @see setDefaultMidiOutput, getDefaultMidiOutput
  33348. */
  33349. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  33350. /** Returns the current default midi output device.
  33351. If no device has been selected, or the device can't be opened, this will
  33352. return 0.
  33353. @see getDefaultMidiOutputName
  33354. */
  33355. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  33356. /** Returns a list of the types of device supported.
  33357. */
  33358. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  33359. /** Creates a list of available types.
  33360. This will add a set of new AudioIODeviceType objects to the specified list, to
  33361. represent each available types of device.
  33362. You can override this if your app needs to do something specific, like avoid
  33363. using DirectSound devices, etc.
  33364. */
  33365. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  33366. /** Plays a beep through the current audio device.
  33367. This is here to allow the audio setup UI panels to easily include a "test"
  33368. button so that the user can check where the audio is coming from.
  33369. */
  33370. void playTestSound();
  33371. /** Turns on level-measuring.
  33372. When enabled, the device manager will measure the peak input level
  33373. across all channels, and you can get this level by calling getCurrentInputLevel().
  33374. This is mainly intended for audio setup UI panels to use to create a mic
  33375. level display, so that the user can check that they've selected the right
  33376. device.
  33377. A simple filter is used to make the level decay smoothly, but this is
  33378. only intended for giving rough feedback, and not for any kind of accurate
  33379. measurement.
  33380. */
  33381. void enableInputLevelMeasurement (bool enableMeasurement);
  33382. /** Returns the current input level.
  33383. To use this, you must first enable it by calling enableInputLevelMeasurement().
  33384. See enableInputLevelMeasurement() for more info.
  33385. */
  33386. double getCurrentInputLevel() const;
  33387. /** Returns the a lock that can be used to synchronise access to the audio callback.
  33388. Obviously while this is locked, you're blocking the audio thread from running, so
  33389. it must only be used for very brief periods when absolutely necessary.
  33390. */
  33391. CriticalSection& getAudioCallbackLock() throw() { return audioCallbackLock; }
  33392. /** Returns the a lock that can be used to synchronise access to the midi callback.
  33393. Obviously while this is locked, you're blocking the midi system from running, so
  33394. it must only be used for very brief periods when absolutely necessary.
  33395. */
  33396. CriticalSection& getMidiCallbackLock() throw() { return midiCallbackLock; }
  33397. private:
  33398. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  33399. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  33400. AudioDeviceSetup currentSetup;
  33401. ScopedPointer <AudioIODevice> currentAudioDevice;
  33402. SortedSet <AudioIODeviceCallback*> callbacks;
  33403. int numInputChansNeeded, numOutputChansNeeded;
  33404. String currentDeviceType;
  33405. BigInteger inputChannels, outputChannels;
  33406. ScopedPointer <XmlElement> lastExplicitSettings;
  33407. mutable bool listNeedsScanning;
  33408. bool useInputNames;
  33409. int inputLevelMeasurementEnabledCount;
  33410. double inputLevel;
  33411. ScopedPointer <AudioSampleBuffer> testSound;
  33412. int testSoundPosition;
  33413. AudioSampleBuffer tempBuffer;
  33414. StringArray midiInsFromXml;
  33415. OwnedArray <MidiInput> enabledMidiInputs;
  33416. Array <MidiInputCallback*> midiCallbacks;
  33417. StringArray midiCallbackDevices;
  33418. String defaultMidiOutputName;
  33419. ScopedPointer <MidiOutput> defaultMidiOutput;
  33420. CriticalSection audioCallbackLock, midiCallbackLock;
  33421. double cpuUsageMs, timeToCpuScale;
  33422. class CallbackHandler : public AudioIODeviceCallback,
  33423. public MidiInputCallback
  33424. {
  33425. public:
  33426. void audioDeviceIOCallback (const float**, int, float**, int, int);
  33427. void audioDeviceAboutToStart (AudioIODevice*);
  33428. void audioDeviceStopped();
  33429. void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
  33430. AudioDeviceManager* owner;
  33431. };
  33432. CallbackHandler callbackHandler;
  33433. friend class CallbackHandler;
  33434. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  33435. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  33436. void audioDeviceAboutToStartInt (AudioIODevice*);
  33437. void audioDeviceStoppedInt();
  33438. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  33439. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  33440. const BigInteger& ins, const BigInteger& outs);
  33441. void stopDevice();
  33442. void updateXml();
  33443. void createDeviceTypesIfNeeded();
  33444. void scanDevicesIfNeeded();
  33445. void deleteCurrentDevice();
  33446. double chooseBestSampleRate (double preferred) const;
  33447. int chooseBestBufferSize (int preferred) const;
  33448. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  33449. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  33450. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  33451. };
  33452. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  33453. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  33454. #endif
  33455. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  33456. #endif
  33457. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  33458. #endif
  33459. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  33460. #endif
  33461. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  33462. #endif
  33463. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  33464. /*** Start of inlined file: juce_Decibels.h ***/
  33465. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  33466. #define __JUCE_DECIBELS_JUCEHEADER__
  33467. /**
  33468. This class contains some helpful static methods for dealing with decibel values.
  33469. */
  33470. class Decibels
  33471. {
  33472. public:
  33473. /** Converts a dBFS value to its equivalent gain level.
  33474. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  33475. decibel value lower than minusInfinityDb will return a gain of 0.
  33476. */
  33477. template <typename Type>
  33478. static Type decibelsToGain (const Type decibels,
  33479. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33480. {
  33481. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  33482. : Type();
  33483. }
  33484. /** Converts a gain level into a dBFS value.
  33485. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  33486. If the gain is 0 (or negative), then the method will return the value
  33487. provided as minusInfinityDb.
  33488. */
  33489. template <typename Type>
  33490. static Type gainToDecibels (const Type gain,
  33491. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33492. {
  33493. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
  33494. : minusInfinityDb;
  33495. }
  33496. /** Converts a decibel reading to a string, with the 'dB' suffix.
  33497. If the decibel value is lower than minusInfinityDb, the return value will
  33498. be "-INF dB".
  33499. */
  33500. template <typename Type>
  33501. static const String toString (const Type decibels,
  33502. const int decimalPlaces = 2,
  33503. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  33504. {
  33505. String s;
  33506. if (decibels <= minusInfinityDb)
  33507. {
  33508. s = "-INF dB";
  33509. }
  33510. else
  33511. {
  33512. if (decibels >= Type())
  33513. s << '+';
  33514. s << String (decibels, decimalPlaces) << " dB";
  33515. }
  33516. return s;
  33517. }
  33518. private:
  33519. enum
  33520. {
  33521. defaultMinusInfinitydB = -100
  33522. };
  33523. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  33524. JUCE_DECLARE_NON_COPYABLE (Decibels);
  33525. };
  33526. #endif // __JUCE_DECIBELS_JUCEHEADER__
  33527. /*** End of inlined file: juce_Decibels.h ***/
  33528. #endif
  33529. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  33530. #endif
  33531. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  33532. #endif
  33533. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  33534. /*** Start of inlined file: juce_MidiFile.h ***/
  33535. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  33536. #define __JUCE_MIDIFILE_JUCEHEADER__
  33537. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  33538. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33539. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33540. /**
  33541. A sequence of timestamped midi messages.
  33542. This allows the sequence to be manipulated, and also to be read from and
  33543. written to a standard midi file.
  33544. @see MidiMessage, MidiFile
  33545. */
  33546. class JUCE_API MidiMessageSequence
  33547. {
  33548. public:
  33549. /** Creates an empty midi sequence object. */
  33550. MidiMessageSequence();
  33551. /** Creates a copy of another sequence. */
  33552. MidiMessageSequence (const MidiMessageSequence& other);
  33553. /** Replaces this sequence with another one. */
  33554. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  33555. /** Destructor. */
  33556. ~MidiMessageSequence();
  33557. /** Structure used to hold midi events in the sequence.
  33558. These structures act as 'handles' on the events as they are moved about in
  33559. the list, and make it quick to find the matching note-offs for note-on events.
  33560. @see MidiMessageSequence::getEventPointer
  33561. */
  33562. class MidiEventHolder
  33563. {
  33564. public:
  33565. /** Destructor. */
  33566. ~MidiEventHolder();
  33567. /** The message itself, whose timestamp is used to specify the event's time.
  33568. */
  33569. MidiMessage message;
  33570. /** The matching note-off event (if this is a note-on event).
  33571. If this isn't a note-on, this pointer will be null.
  33572. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  33573. note-offs up-to-date after events have been moved around in the sequence
  33574. or deleted.
  33575. */
  33576. MidiEventHolder* noteOffObject;
  33577. private:
  33578. friend class MidiMessageSequence;
  33579. MidiEventHolder (const MidiMessage& message);
  33580. JUCE_LEAK_DETECTOR (MidiEventHolder);
  33581. };
  33582. /** Clears the sequence. */
  33583. void clear();
  33584. /** Returns the number of events in the sequence. */
  33585. int getNumEvents() const;
  33586. /** Returns a pointer to one of the events. */
  33587. MidiEventHolder* getEventPointer (int index) const;
  33588. /** Returns the time of the note-up that matches the note-on at this index.
  33589. If the event at this index isn't a note-on, it'll just return 0.
  33590. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33591. */
  33592. double getTimeOfMatchingKeyUp (int index) const;
  33593. /** Returns the index of the note-up that matches the note-on at this index.
  33594. If the event at this index isn't a note-on, it'll just return -1.
  33595. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33596. */
  33597. int getIndexOfMatchingKeyUp (int index) const;
  33598. /** Returns the index of an event. */
  33599. int getIndexOf (MidiEventHolder* event) const;
  33600. /** Returns the index of the first event on or after the given timestamp.
  33601. If the time is beyond the end of the sequence, this will return the
  33602. number of events.
  33603. */
  33604. int getNextIndexAtTime (double timeStamp) const;
  33605. /** Returns the timestamp of the first event in the sequence.
  33606. @see getEndTime
  33607. */
  33608. double getStartTime() const;
  33609. /** Returns the timestamp of the last event in the sequence.
  33610. @see getStartTime
  33611. */
  33612. double getEndTime() const;
  33613. /** Returns the timestamp of the event at a given index.
  33614. If the index is out-of-range, this will return 0.0
  33615. */
  33616. double getEventTime (int index) const;
  33617. /** Inserts a midi message into the sequence.
  33618. The index at which the new message gets inserted will depend on its timestamp,
  33619. because the sequence is kept sorted.
  33620. Remember to call updateMatchedPairs() after adding note-on events.
  33621. @param newMessage the new message to add (an internal copy will be made)
  33622. @param timeAdjustment an optional value to add to the timestamp of the message
  33623. that will be inserted
  33624. @see updateMatchedPairs
  33625. */
  33626. void addEvent (const MidiMessage& newMessage,
  33627. double timeAdjustment = 0);
  33628. /** Deletes one of the events in the sequence.
  33629. Remember to call updateMatchedPairs() after removing events.
  33630. @param index the index of the event to delete
  33631. @param deleteMatchingNoteUp whether to also remove the matching note-off
  33632. if the event you're removing is a note-on
  33633. */
  33634. void deleteEvent (int index, bool deleteMatchingNoteUp);
  33635. /** Merges another sequence into this one.
  33636. Remember to call updateMatchedPairs() after using this method.
  33637. @param other the sequence to add from
  33638. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  33639. as they are read from the other sequence
  33640. @param firstAllowableDestTime events will not be added if their time is earlier
  33641. than this time. (This is after their time has been adjusted
  33642. by the timeAdjustmentDelta)
  33643. @param endOfAllowableDestTimes events will not be added if their time is equal to
  33644. or greater than this time. (This is after their time has
  33645. been adjusted by the timeAdjustmentDelta)
  33646. */
  33647. void addSequence (const MidiMessageSequence& other,
  33648. double timeAdjustmentDelta,
  33649. double firstAllowableDestTime,
  33650. double endOfAllowableDestTimes);
  33651. /** Makes sure all the note-on and note-off pairs are up-to-date.
  33652. Call this after moving messages about or deleting/adding messages, and it
  33653. will scan the list and make sure all the note-offs in the MidiEventHolder
  33654. structures are pointing at the correct ones.
  33655. */
  33656. void updateMatchedPairs();
  33657. /** Copies all the messages for a particular midi channel to another sequence.
  33658. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  33659. @param destSequence the sequence that the chosen events should be copied to
  33660. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  33661. channel) will also be copied across.
  33662. @see extractSysExMessages
  33663. */
  33664. void extractMidiChannelMessages (int channelNumberToExtract,
  33665. MidiMessageSequence& destSequence,
  33666. bool alsoIncludeMetaEvents) const;
  33667. /** Copies all midi sys-ex messages to another sequence.
  33668. @param destSequence this is the sequence to which any sys-exes in this sequence
  33669. will be added
  33670. @see extractMidiChannelMessages
  33671. */
  33672. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  33673. /** Removes any messages in this sequence that have a specific midi channel.
  33674. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  33675. */
  33676. void deleteMidiChannelMessages (int channelNumberToRemove);
  33677. /** Removes any sys-ex messages from this sequence.
  33678. */
  33679. void deleteSysExMessages();
  33680. /** Adds an offset to the timestamps of all events in the sequence.
  33681. @param deltaTime the amount to add to each timestamp.
  33682. */
  33683. void addTimeToMessages (double deltaTime);
  33684. /** Scans through the sequence to determine the state of any midi controllers at
  33685. a given time.
  33686. This will create a sequence of midi controller changes that can be
  33687. used to set all midi controllers to the state they would be in at the
  33688. specified time within this sequence.
  33689. As well as controllers, it will also recreate the midi program number
  33690. and pitch bend position.
  33691. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  33692. for other channels will be ignored.
  33693. @param time the time at which you want to find out the state - there are
  33694. no explicit units for this time measurement, it's the same units
  33695. as used for the timestamps of the messages
  33696. @param resultMessages an array to which midi controller-change messages will be added. This
  33697. will be the minimum number of controller changes to recreate the
  33698. state at the required time.
  33699. */
  33700. void createControllerUpdatesForTime (int channelNumber, double time,
  33701. OwnedArray<MidiMessage>& resultMessages);
  33702. /** Swaps this sequence with another one. */
  33703. void swapWith (MidiMessageSequence& other) throw();
  33704. /** @internal */
  33705. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  33706. const MidiMessageSequence::MidiEventHolder* second) throw();
  33707. private:
  33708. friend class MidiFile;
  33709. OwnedArray <MidiEventHolder> list;
  33710. void sort();
  33711. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  33712. };
  33713. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33714. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  33715. /**
  33716. Reads/writes standard midi format files.
  33717. To read a midi file, create a MidiFile object and call its readFrom() method. You
  33718. can then get the individual midi tracks from it using the getTrack() method.
  33719. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  33720. to it using the addTrack() method, and then call its writeTo() method to stream
  33721. it out.
  33722. @see MidiMessageSequence
  33723. */
  33724. class JUCE_API MidiFile
  33725. {
  33726. public:
  33727. /** Creates an empty MidiFile object.
  33728. */
  33729. MidiFile();
  33730. /** Destructor. */
  33731. ~MidiFile();
  33732. /** Returns the number of tracks in the file.
  33733. @see getTrack, addTrack
  33734. */
  33735. int getNumTracks() const throw();
  33736. /** Returns a pointer to one of the tracks in the file.
  33737. @returns a pointer to the track, or 0 if the index is out-of-range
  33738. @see getNumTracks, addTrack
  33739. */
  33740. const MidiMessageSequence* getTrack (int index) const throw();
  33741. /** Adds a midi track to the file.
  33742. This will make its own internal copy of the sequence that is passed-in.
  33743. @see getNumTracks, getTrack
  33744. */
  33745. void addTrack (const MidiMessageSequence& trackSequence);
  33746. /** Removes all midi tracks from the file.
  33747. @see getNumTracks
  33748. */
  33749. void clear();
  33750. /** Returns the raw time format code that will be written to a stream.
  33751. After reading a midi file, this method will return the time-format that
  33752. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  33753. or setSmpteTimeFormat() methods.
  33754. If the value returned is positive, it indicates the number of midi ticks
  33755. per quarter-note - see setTicksPerQuarterNote().
  33756. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  33757. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  33758. */
  33759. short getTimeFormat() const throw();
  33760. /** Sets the time format to use when this file is written to a stream.
  33761. If this is called, the file will be written as bars/beats using the
  33762. specified resolution, rather than SMPTE absolute times, as would be
  33763. used if setSmpteTimeFormat() had been called instead.
  33764. @param ticksPerQuarterNote e.g. 96, 960
  33765. @see setSmpteTimeFormat
  33766. */
  33767. void setTicksPerQuarterNote (int ticksPerQuarterNote) throw();
  33768. /** Sets the time format to use when this file is written to a stream.
  33769. If this is called, the file will be written using absolute times, rather
  33770. than bars/beats as would be the case if setTicksPerBeat() had been called
  33771. instead.
  33772. @param framesPerSecond must be 24, 25, 29 or 30
  33773. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  33774. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  33775. timing, setSmpteTimeFormat (25, 40)
  33776. @see setTicksPerBeat
  33777. */
  33778. void setSmpteTimeFormat (int framesPerSecond,
  33779. int subframeResolution) throw();
  33780. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  33781. Useful for finding the positions of all the tempo changes in a file.
  33782. @param tempoChangeEvents a list to which all the events will be added
  33783. */
  33784. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  33785. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  33786. Useful for finding the positions of all the tempo changes in a file.
  33787. @param timeSigEvents a list to which all the events will be added
  33788. */
  33789. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  33790. /** Returns the latest timestamp in any of the tracks.
  33791. (Useful for finding the length of the file).
  33792. */
  33793. double getLastTimestamp() const;
  33794. /** Reads a midi file format stream.
  33795. After calling this, you can get the tracks that were read from the file by using the
  33796. getNumTracks() and getTrack() methods.
  33797. The timestamps of the midi events in the tracks will represent their positions in
  33798. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  33799. method.
  33800. @returns true if the stream was read successfully
  33801. */
  33802. bool readFrom (InputStream& sourceStream);
  33803. /** Writes the midi tracks as a standard midi file.
  33804. @returns true if the operation succeeded.
  33805. */
  33806. bool writeTo (OutputStream& destStream);
  33807. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  33808. This will use the midi time format and tempo/time signature info in the
  33809. tracks to convert all the timestamps to absolute values in seconds.
  33810. */
  33811. void convertTimestampTicksToSeconds();
  33812. private:
  33813. OwnedArray <MidiMessageSequence> tracks;
  33814. short timeFormat;
  33815. void readNextTrack (const uint8* data, int size);
  33816. void writeTrack (OutputStream& mainOut, int trackNum);
  33817. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  33818. };
  33819. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  33820. /*** End of inlined file: juce_MidiFile.h ***/
  33821. #endif
  33822. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  33823. #endif
  33824. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33825. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  33826. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33827. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33828. class MidiKeyboardState;
  33829. /**
  33830. Receives events from a MidiKeyboardState object.
  33831. @see MidiKeyboardState
  33832. */
  33833. class JUCE_API MidiKeyboardStateListener
  33834. {
  33835. public:
  33836. MidiKeyboardStateListener() throw() {}
  33837. virtual ~MidiKeyboardStateListener() {}
  33838. /** Called when one of the MidiKeyboardState's keys is pressed.
  33839. This will be called synchronously when the state is either processing a
  33840. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  33841. when a note is being played with its MidiKeyboardState::noteOn() method.
  33842. Note that this callback could happen from an audio callback thread, so be
  33843. careful not to block, and avoid any UI activity in the callback.
  33844. */
  33845. virtual void handleNoteOn (MidiKeyboardState* source,
  33846. int midiChannel, int midiNoteNumber, float velocity) = 0;
  33847. /** Called when one of the MidiKeyboardState's keys is released.
  33848. This will be called synchronously when the state is either processing a
  33849. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  33850. when a note is being played with its MidiKeyboardState::noteOff() method.
  33851. Note that this callback could happen from an audio callback thread, so be
  33852. careful not to block, and avoid any UI activity in the callback.
  33853. */
  33854. virtual void handleNoteOff (MidiKeyboardState* source,
  33855. int midiChannel, int midiNoteNumber) = 0;
  33856. };
  33857. /**
  33858. Represents a piano keyboard, keeping track of which keys are currently pressed.
  33859. This object can parse a stream of midi events, using them to update its idea
  33860. of which keys are pressed for each individiual midi channel.
  33861. When keys go up or down, it can broadcast these events to listener objects.
  33862. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  33863. methods, and midi messages for these events will be merged into the
  33864. midi stream that gets processed by processNextMidiBuffer().
  33865. */
  33866. class JUCE_API MidiKeyboardState
  33867. {
  33868. public:
  33869. MidiKeyboardState();
  33870. ~MidiKeyboardState();
  33871. /** Resets the state of the object.
  33872. All internal data for all the channels is reset, but no events are sent as a
  33873. result.
  33874. If you want to release any keys that are currently down, and to send out note-up
  33875. midi messages for this, use the allNotesOff() method instead.
  33876. */
  33877. void reset();
  33878. /** Returns true if the given midi key is currently held down for the given midi channel.
  33879. The channel number must be between 1 and 16. If you want to see if any notes are
  33880. on for a range of channels, use the isNoteOnForChannels() method.
  33881. */
  33882. bool isNoteOn (int midiChannel, int midiNoteNumber) const throw();
  33883. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  33884. The channel mask has a bit set for each midi channel you want to test for - bit
  33885. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  33886. If a note is on for at least one of the specified channels, this returns true.
  33887. */
  33888. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const throw();
  33889. /** Turns a specified note on.
  33890. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  33891. next call to processNextMidiBuffer().
  33892. It will also trigger a synchronous callback to the listeners to tell them that the key has
  33893. gone down.
  33894. */
  33895. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  33896. /** Turns a specified note off.
  33897. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  33898. next call to processNextMidiBuffer().
  33899. It will also trigger a synchronous callback to the listeners to tell them that the key has
  33900. gone up.
  33901. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  33902. */
  33903. void noteOff (int midiChannel, int midiNoteNumber);
  33904. /** This will turn off any currently-down notes for the given midi channel.
  33905. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  33906. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  33907. and events being added to the midi stream.
  33908. */
  33909. void allNotesOff (int midiChannel);
  33910. /** Looks at a key-up/down event and uses it to update the state of this object.
  33911. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  33912. instead.
  33913. */
  33914. void processNextMidiEvent (const MidiMessage& message);
  33915. /** Scans a midi stream for up/down events and adds its own events to it.
  33916. This will look for any up/down events and use them to update the internal state,
  33917. synchronously making suitable callbacks to the listeners.
  33918. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  33919. and noteOff() calls will be added into the buffer.
  33920. Only the section of the buffer whose timestamps are between startSample and
  33921. (startSample + numSamples) will be affected, and any events added will be placed
  33922. between these times.
  33923. If you're going to use this method, you'll need to keep calling it regularly for
  33924. it to work satisfactorily.
  33925. To process a single midi event at a time, use the processNextMidiEvent() method
  33926. instead.
  33927. */
  33928. void processNextMidiBuffer (MidiBuffer& buffer,
  33929. int startSample,
  33930. int numSamples,
  33931. bool injectIndirectEvents);
  33932. /** Registers a listener for callbacks when keys go up or down.
  33933. @see removeListener
  33934. */
  33935. void addListener (MidiKeyboardStateListener* listener);
  33936. /** Deregisters a listener.
  33937. @see addListener
  33938. */
  33939. void removeListener (MidiKeyboardStateListener* listener);
  33940. private:
  33941. CriticalSection lock;
  33942. uint16 noteStates [128];
  33943. MidiBuffer eventsToAdd;
  33944. Array <MidiKeyboardStateListener*> listeners;
  33945. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  33946. void noteOffInternal (int midiChannel, int midiNoteNumber);
  33947. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  33948. };
  33949. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33950. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  33951. #endif
  33952. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  33953. #endif
  33954. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33955. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  33956. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33957. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33958. /**
  33959. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  33960. processing by a block-based audio callback.
  33961. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  33962. so it can easily use a midi input or keyboard component as its source.
  33963. @see MidiMessage, MidiInput
  33964. */
  33965. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  33966. public MidiInputCallback
  33967. {
  33968. public:
  33969. /** Creates a MidiMessageCollector. */
  33970. MidiMessageCollector();
  33971. /** Destructor. */
  33972. ~MidiMessageCollector();
  33973. /** Clears any messages from the queue.
  33974. You need to call this method before starting to use the collector, so that
  33975. it knows the correct sample rate to use.
  33976. */
  33977. void reset (double sampleRate);
  33978. /** Takes an incoming real-time message and adds it to the queue.
  33979. The message's timestamp is taken, and it will be ready for retrieval as part
  33980. of the block returned by the next call to removeNextBlockOfMessages().
  33981. This method is fully thread-safe when overlapping calls are made with
  33982. removeNextBlockOfMessages().
  33983. */
  33984. void addMessageToQueue (const MidiMessage& message);
  33985. /** Removes all the pending messages from the queue as a buffer.
  33986. This will also correct the messages' timestamps to make sure they're in
  33987. the range 0 to numSamples - 1.
  33988. This call should be made regularly by something like an audio processing
  33989. callback, because the time that it happens is used in calculating the
  33990. midi event positions.
  33991. This method is fully thread-safe when overlapping calls are made with
  33992. addMessageToQueue().
  33993. */
  33994. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  33995. /** @internal */
  33996. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  33997. /** @internal */
  33998. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  33999. /** @internal */
  34000. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  34001. private:
  34002. double lastCallbackTime;
  34003. CriticalSection midiCallbackLock;
  34004. MidiBuffer incomingMessages;
  34005. double sampleRate;
  34006. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  34007. };
  34008. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  34009. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  34010. #endif
  34011. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  34012. #endif
  34013. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  34014. #endif
  34015. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34016. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  34017. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34018. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34019. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  34020. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34021. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34022. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  34023. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34024. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34025. /*** Start of inlined file: juce_AudioProcessor.h ***/
  34026. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34027. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34028. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  34029. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34030. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34031. class AudioProcessor;
  34032. /**
  34033. Base class for the component that acts as the GUI for an AudioProcessor.
  34034. Derive your editor component from this class, and create an instance of it
  34035. by overriding the AudioProcessor::createEditor() method.
  34036. @see AudioProcessor, GenericAudioProcessorEditor
  34037. */
  34038. class JUCE_API AudioProcessorEditor : public Component
  34039. {
  34040. protected:
  34041. /** Creates an editor for the specified processor.
  34042. */
  34043. AudioProcessorEditor (AudioProcessor* owner);
  34044. public:
  34045. /** Destructor. */
  34046. ~AudioProcessorEditor();
  34047. /** Returns a pointer to the processor that this editor represents. */
  34048. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  34049. private:
  34050. AudioProcessor* const owner;
  34051. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  34052. };
  34053. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34054. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  34055. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  34056. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34057. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34058. class AudioProcessor;
  34059. /**
  34060. Base class for listeners that want to know about changes to an AudioProcessor.
  34061. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  34062. @see AudioProcessor
  34063. */
  34064. class JUCE_API AudioProcessorListener
  34065. {
  34066. public:
  34067. /** Destructor. */
  34068. virtual ~AudioProcessorListener() {}
  34069. /** Receives a callback when a parameter is changed.
  34070. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  34071. many audio processors will change their parameter during their audio callback.
  34072. This means that not only has your handler code got to be completely thread-safe,
  34073. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  34074. this event on your message thread, use this callback to trigger an AsyncUpdater
  34075. or ChangeBroadcaster which you can respond to on the message thread.
  34076. */
  34077. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  34078. int parameterIndex,
  34079. float newValue) = 0;
  34080. /** Called to indicate that something else in the plugin has changed, like its
  34081. program, number of parameters, etc.
  34082. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34083. call it during their audio callback. This means that not only has your handler code
  34084. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34085. blocking. If you need to handle this event on your message thread, use this callback
  34086. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34087. message thread.
  34088. */
  34089. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  34090. /** Indicates that a parameter change gesture has started.
  34091. E.g. if the user is dragging a slider, this would be called when they first
  34092. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  34093. called when they release it.
  34094. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34095. call it during their audio callback. This means that not only has your handler code
  34096. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34097. blocking. If you need to handle this event on your message thread, use this callback
  34098. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34099. message thread.
  34100. @see audioProcessorParameterChangeGestureEnd
  34101. */
  34102. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  34103. int parameterIndex);
  34104. /** Indicates that a parameter change gesture has finished.
  34105. E.g. if the user is dragging a slider, this would be called when they release
  34106. the mouse button.
  34107. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  34108. call it during their audio callback. This means that not only has your handler code
  34109. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  34110. blocking. If you need to handle this event on your message thread, use this callback
  34111. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  34112. message thread.
  34113. @see audioProcessorParameterChangeGestureBegin
  34114. */
  34115. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  34116. int parameterIndex);
  34117. };
  34118. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34119. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  34120. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  34121. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34122. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34123. /**
  34124. A subclass of AudioPlayHead can supply information about the position and
  34125. status of a moving play head during audio playback.
  34126. One of these can be supplied to an AudioProcessor object so that it can find
  34127. out about the position of the audio that it is rendering.
  34128. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  34129. */
  34130. class JUCE_API AudioPlayHead
  34131. {
  34132. protected:
  34133. AudioPlayHead() {}
  34134. public:
  34135. virtual ~AudioPlayHead() {}
  34136. /** Frame rate types. */
  34137. enum FrameRateType
  34138. {
  34139. fps24 = 0,
  34140. fps25 = 1,
  34141. fps2997 = 2,
  34142. fps30 = 3,
  34143. fps2997drop = 4,
  34144. fps30drop = 5,
  34145. fpsUnknown = 99
  34146. };
  34147. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  34148. */
  34149. struct CurrentPositionInfo
  34150. {
  34151. /** The tempo in BPM */
  34152. double bpm;
  34153. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  34154. int timeSigNumerator;
  34155. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  34156. int timeSigDenominator;
  34157. /** The current play position, in seconds from the start of the edit. */
  34158. double timeInSeconds;
  34159. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  34160. double editOriginTime;
  34161. /** The current play position in pulses-per-quarter-note.
  34162. This is the number of quarter notes since the edit start.
  34163. */
  34164. double ppqPosition;
  34165. /** The position of the start of the last bar, in pulses-per-quarter-note.
  34166. This is the number of quarter notes from the start of the edit to the
  34167. start of the current bar.
  34168. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  34169. it's not available, the value will be 0.
  34170. */
  34171. double ppqPositionOfLastBarStart;
  34172. /** The video frame rate, if applicable. */
  34173. FrameRateType frameRate;
  34174. /** True if the transport is currently playing. */
  34175. bool isPlaying;
  34176. /** True if the transport is currently recording.
  34177. (When isRecording is true, then isPlaying will also be true).
  34178. */
  34179. bool isRecording;
  34180. bool operator== (const CurrentPositionInfo& other) const throw();
  34181. bool operator!= (const CurrentPositionInfo& other) const throw();
  34182. void resetToDefault();
  34183. };
  34184. /** Fills-in the given structure with details about the transport's
  34185. position at the start of the current processing block.
  34186. */
  34187. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  34188. };
  34189. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34190. /*** End of inlined file: juce_AudioPlayHead.h ***/
  34191. /**
  34192. Base class for audio processing filters or plugins.
  34193. This is intended to act as a base class of audio filter that is general enough to
  34194. be wrapped as a VST, AU, RTAS, etc, or used internally.
  34195. It is also used by the plugin hosting code as the wrapper around an instance
  34196. of a loaded plugin.
  34197. Derive your filter class from this base class, and if you're building a plugin,
  34198. you should implement a global function called createPluginFilter() which creates
  34199. and returns a new instance of your subclass.
  34200. */
  34201. class JUCE_API AudioProcessor
  34202. {
  34203. protected:
  34204. /** Constructor.
  34205. You can also do your initialisation tasks in the initialiseFilterInfo()
  34206. call, which will be made after this object has been created.
  34207. */
  34208. AudioProcessor();
  34209. public:
  34210. /** Destructor. */
  34211. virtual ~AudioProcessor();
  34212. /** Returns the name of this processor.
  34213. */
  34214. virtual const String getName() const = 0;
  34215. /** Called before playback starts, to let the filter prepare itself.
  34216. The sample rate is the target sample rate, and will remain constant until
  34217. playback stops.
  34218. The estimatedSamplesPerBlock value is a HINT about the typical number of
  34219. samples that will be processed for each callback, but isn't any kind
  34220. of guarantee. The actual block sizes that the host uses may be different
  34221. each time the callback happens, and may be more or less than this value.
  34222. */
  34223. virtual void prepareToPlay (double sampleRate,
  34224. int estimatedSamplesPerBlock) = 0;
  34225. /** Called after playback has stopped, to let the filter free up any resources it
  34226. no longer needs.
  34227. */
  34228. virtual void releaseResources() = 0;
  34229. /** Renders the next block.
  34230. When this method is called, the buffer contains a number of channels which is
  34231. at least as great as the maximum number of input and output channels that
  34232. this filter is using. It will be filled with the filter's input data and
  34233. should be replaced with the filter's output.
  34234. So for example if your filter has 2 input channels and 4 output channels, then
  34235. the buffer will contain 4 channels, the first two being filled with the
  34236. input data. Your filter should read these, do its processing, and replace
  34237. the contents of all 4 channels with its output.
  34238. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  34239. all filled with data, and your filter should overwrite the first 2 of these
  34240. with its output. But be VERY careful not to write anything to the last 3
  34241. channels, as these might be mapped to memory that the host assumes is read-only!
  34242. Note that if you have more outputs than inputs, then only those channels that
  34243. correspond to an input channel are guaranteed to contain sensible data - e.g.
  34244. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  34245. but the last two channels may contain garbage, so you should be careful not to
  34246. let this pass through without being overwritten or cleared.
  34247. Also note that the buffer may have more channels than are strictly necessary,
  34248. but your should only read/write from the ones that your filter is supposed to
  34249. be using.
  34250. The number of samples in these buffers is NOT guaranteed to be the same for every
  34251. callback, and may be more or less than the estimated value given to prepareToPlay().
  34252. Your code must be able to cope with variable-sized blocks, or you're going to get
  34253. clicks and crashes!
  34254. If the filter is receiving a midi input, then the midiMessages array will be filled
  34255. with the midi messages for this block. Each message's timestamp will indicate the
  34256. message's time, as a number of samples from the start of the block.
  34257. Any messages left in the midi buffer when this method has finished are assumed to
  34258. be the filter's midi output. This means that your filter should be careful to
  34259. clear any incoming messages from the array if it doesn't want them to be passed-on.
  34260. Be very careful about what you do in this callback - it's going to be called by
  34261. the audio thread, so any kind of interaction with the UI is absolutely
  34262. out of the question. If you change a parameter in here and need to tell your UI to
  34263. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  34264. the UI components register as listeners, and then call sendChangeMessage() inside the
  34265. processBlock() method to send out an asynchronous message. You could also use
  34266. the AsyncUpdater class in a similar way.
  34267. */
  34268. virtual void processBlock (AudioSampleBuffer& buffer,
  34269. MidiBuffer& midiMessages) = 0;
  34270. /** Returns the current AudioPlayHead object that should be used to find
  34271. out the state and position of the playhead.
  34272. You can call this from your processBlock() method, and use the AudioPlayHead
  34273. object to get the details about the time of the start of the block currently
  34274. being processed.
  34275. If the host hasn't supplied a playhead object, this will return 0.
  34276. */
  34277. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  34278. /** Returns the current sample rate.
  34279. This can be called from your processBlock() method - it's not guaranteed
  34280. to be valid at any other time, and may return 0 if it's unknown.
  34281. */
  34282. double getSampleRate() const throw() { return sampleRate; }
  34283. /** Returns the current typical block size that is being used.
  34284. This can be called from your processBlock() method - it's not guaranteed
  34285. to be valid at any other time.
  34286. Remember it's not the ONLY block size that may be used when calling
  34287. processBlock, it's just the normal one. The actual block sizes used may be
  34288. larger or smaller than this, and will vary between successive calls.
  34289. */
  34290. int getBlockSize() const throw() { return blockSize; }
  34291. /** Returns the number of input channels that the host will be sending the filter.
  34292. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  34293. number of channels that your filter would prefer to have, and this method lets
  34294. you know how many the host is actually using.
  34295. Note that this method is only valid during or after the prepareToPlay()
  34296. method call. Until that point, the number of channels will be unknown.
  34297. */
  34298. int getNumInputChannels() const throw() { return numInputChannels; }
  34299. /** Returns the number of output channels that the host will be sending the filter.
  34300. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  34301. number of channels that your filter would prefer to have, and this method lets
  34302. you know how many the host is actually using.
  34303. Note that this method is only valid during or after the prepareToPlay()
  34304. method call. Until that point, the number of channels will be unknown.
  34305. */
  34306. int getNumOutputChannels() const throw() { return numOutputChannels; }
  34307. /** Returns the name of one of the input channels, as returned by the host.
  34308. The host might not supply very useful names for channels, and this might be
  34309. something like "1", "2", "left", "right", etc.
  34310. */
  34311. virtual const String getInputChannelName (int channelIndex) const = 0;
  34312. /** Returns the name of one of the output channels, as returned by the host.
  34313. The host might not supply very useful names for channels, and this might be
  34314. something like "1", "2", "left", "right", etc.
  34315. */
  34316. virtual const String getOutputChannelName (int channelIndex) const = 0;
  34317. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  34318. virtual bool isInputChannelStereoPair (int index) const = 0;
  34319. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  34320. virtual bool isOutputChannelStereoPair (int index) const = 0;
  34321. /** This returns the number of samples delay that the filter imposes on the audio
  34322. passing through it.
  34323. The host will call this to find the latency - the filter itself should set this value
  34324. by calling setLatencySamples() as soon as it can during its initialisation.
  34325. */
  34326. int getLatencySamples() const throw() { return latencySamples; }
  34327. /** The filter should call this to set the number of samples delay that it introduces.
  34328. The filter should call this as soon as it can during initialisation, and can call it
  34329. later if the value changes.
  34330. */
  34331. void setLatencySamples (int newLatency);
  34332. /** Returns true if the processor wants midi messages. */
  34333. virtual bool acceptsMidi() const = 0;
  34334. /** Returns true if the processor produces midi messages. */
  34335. virtual bool producesMidi() const = 0;
  34336. /** This returns a critical section that will automatically be locked while the host
  34337. is calling the processBlock() method.
  34338. Use it from your UI or other threads to lock access to variables that are used
  34339. by the process callback, but obviously be careful not to keep it locked for
  34340. too long, because that could cause stuttering playback. If you need to do something
  34341. that'll take a long time and need the processing to stop while it happens, use the
  34342. suspendProcessing() method instead.
  34343. @see suspendProcessing
  34344. */
  34345. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  34346. /** Enables and disables the processing callback.
  34347. If you need to do something time-consuming on a thread and would like to make sure
  34348. the audio processing callback doesn't happen until you've finished, use this
  34349. to disable the callback and re-enable it again afterwards.
  34350. E.g.
  34351. @code
  34352. void loadNewPatch()
  34353. {
  34354. suspendProcessing (true);
  34355. ..do something that takes ages..
  34356. suspendProcessing (false);
  34357. }
  34358. @endcode
  34359. If the host tries to make an audio callback while processing is suspended, the
  34360. filter will return an empty buffer, but won't block the audio thread like it would
  34361. do if you use the getCallbackLock() critical section to synchronise access.
  34362. If you're going to use this, your processBlock() method must call isSuspended() and
  34363. check whether it's suspended or not. If it is, then it should skip doing any real
  34364. processing, either emitting silence or passing the input through unchanged.
  34365. @see getCallbackLock
  34366. */
  34367. void suspendProcessing (bool shouldBeSuspended);
  34368. /** Returns true if processing is currently suspended.
  34369. @see suspendProcessing
  34370. */
  34371. bool isSuspended() const throw() { return suspended; }
  34372. /** A plugin can override this to be told when it should reset any playing voices.
  34373. The default implementation does nothing, but a host may call this to tell the
  34374. plugin that it should stop any tails or sounds that have been left running.
  34375. */
  34376. virtual void reset();
  34377. /** Returns true if the processor is being run in an offline mode for rendering.
  34378. If the processor is being run live on realtime signals, this returns false.
  34379. If the mode is unknown, this will assume it's realtime and return false.
  34380. This value may be unreliable until the prepareToPlay() method has been called,
  34381. and could change each time prepareToPlay() is called.
  34382. @see setNonRealtime()
  34383. */
  34384. bool isNonRealtime() const throw() { return nonRealtime; }
  34385. /** Called by the host to tell this processor whether it's being used in a non-realime
  34386. capacity for offline rendering or bouncing.
  34387. Whatever value is passed-in will be
  34388. */
  34389. void setNonRealtime (bool isNonRealtime) throw();
  34390. /** Creates the filter's UI.
  34391. This can return 0 if you want a UI-less filter, in which case the host may create
  34392. a generic UI that lets the user twiddle the parameters directly.
  34393. If you do want to pass back a component, the component should be created and set to
  34394. the correct size before returning it. If you implement this method, you must
  34395. also implement the hasEditor() method and make it return true.
  34396. Remember not to do anything silly like allowing your filter to keep a pointer to
  34397. the component that gets created - it could be deleted later without any warning, which
  34398. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  34399. The correct way to handle the connection between an editor component and its
  34400. filter is to use something like a ChangeBroadcaster so that the editor can
  34401. register itself as a listener, and be told when a change occurs. This lets them
  34402. safely unregister themselves when they are deleted.
  34403. Here are a few things to bear in mind when writing an editor:
  34404. - Initially there won't be an editor, until the user opens one, or they might
  34405. not open one at all. Your filter mustn't rely on it being there.
  34406. - An editor object may be deleted and a replacement one created again at any time.
  34407. - It's safe to assume that an editor will be deleted before its filter.
  34408. @see hasEditor
  34409. */
  34410. virtual AudioProcessorEditor* createEditor() = 0;
  34411. /** Your filter must override this and return true if it can create an editor component.
  34412. @see createEditor
  34413. */
  34414. virtual bool hasEditor() const = 0;
  34415. /** Returns the active editor, if there is one.
  34416. Bear in mind this can return 0, even if an editor has previously been
  34417. opened.
  34418. */
  34419. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  34420. /** Returns the active editor, or if there isn't one, it will create one.
  34421. This may call createEditor() internally to create the component.
  34422. */
  34423. AudioProcessorEditor* createEditorIfNeeded();
  34424. /** This must return the correct value immediately after the object has been
  34425. created, and mustn't change the number of parameters later.
  34426. */
  34427. virtual int getNumParameters() = 0;
  34428. /** Returns the name of a particular parameter. */
  34429. virtual const String getParameterName (int parameterIndex) = 0;
  34430. /** Called by the host to find out the value of one of the filter's parameters.
  34431. The host will expect the value returned to be between 0 and 1.0.
  34432. This could be called quite frequently, so try to make your code efficient.
  34433. It's also likely to be called by non-UI threads, so the code in here should
  34434. be thread-aware.
  34435. */
  34436. virtual float getParameter (int parameterIndex) = 0;
  34437. /** Returns the value of a parameter as a text string. */
  34438. virtual const String getParameterText (int parameterIndex) = 0;
  34439. /** The host will call this method to change the value of one of the filter's parameters.
  34440. The host may call this at any time, including during the audio processing
  34441. callback, so the filter has to process this very fast and avoid blocking.
  34442. If you want to set the value of a parameter internally, e.g. from your
  34443. editor component, then don't call this directly - instead, use the
  34444. setParameterNotifyingHost() method, which will also send a message to
  34445. the host telling it about the change. If the message isn't sent, the host
  34446. won't be able to automate your parameters properly.
  34447. The value passed will be between 0 and 1.0.
  34448. */
  34449. virtual void setParameter (int parameterIndex,
  34450. float newValue) = 0;
  34451. /** Your filter can call this when it needs to change one of its parameters.
  34452. This could happen when the editor or some other internal operation changes
  34453. a parameter. This method will call the setParameter() method to change the
  34454. value, and will then send a message to the host telling it about the change.
  34455. Note that to make sure the host correctly handles automation, you should call
  34456. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  34457. tell the host when the user has started and stopped changing the parameter.
  34458. */
  34459. void setParameterNotifyingHost (int parameterIndex,
  34460. float newValue);
  34461. /** Returns true if the host can automate this parameter.
  34462. By default, this returns true for all parameters.
  34463. */
  34464. virtual bool isParameterAutomatable (int parameterIndex) const;
  34465. /** Should return true if this parameter is a "meta" parameter.
  34466. A meta-parameter is a parameter that changes other params. It is used
  34467. by some hosts (e.g. AudioUnit hosts).
  34468. By default this returns false.
  34469. */
  34470. virtual bool isMetaParameter (int parameterIndex) const;
  34471. /** Sends a signal to the host to tell it that the user is about to start changing this
  34472. parameter.
  34473. This allows the host to know when a parameter is actively being held by the user, and
  34474. it may use this information to help it record automation.
  34475. If you call this, it must be matched by a later call to endParameterChangeGesture().
  34476. */
  34477. void beginParameterChangeGesture (int parameterIndex);
  34478. /** Tells the host that the user has finished changing this parameter.
  34479. This allows the host to know when a parameter is actively being held by the user, and
  34480. it may use this information to help it record automation.
  34481. A call to this method must follow a call to beginParameterChangeGesture().
  34482. */
  34483. void endParameterChangeGesture (int parameterIndex);
  34484. /** The filter can call this when something (apart from a parameter value) has changed.
  34485. It sends a hint to the host that something like the program, number of parameters,
  34486. etc, has changed, and that it should update itself.
  34487. */
  34488. void updateHostDisplay();
  34489. /** Returns the number of preset programs the filter supports.
  34490. The value returned must be valid as soon as this object is created, and
  34491. must not change over its lifetime.
  34492. This value shouldn't be less than 1.
  34493. */
  34494. virtual int getNumPrograms() = 0;
  34495. /** Returns the number of the currently active program.
  34496. */
  34497. virtual int getCurrentProgram() = 0;
  34498. /** Called by the host to change the current program.
  34499. */
  34500. virtual void setCurrentProgram (int index) = 0;
  34501. /** Must return the name of a given program. */
  34502. virtual const String getProgramName (int index) = 0;
  34503. /** Called by the host to rename a program.
  34504. */
  34505. virtual void changeProgramName (int index, const String& newName) = 0;
  34506. /** The host will call this method when it wants to save the filter's internal state.
  34507. This must copy any info about the filter's state into the block of memory provided,
  34508. so that the host can store this and later restore it using setStateInformation().
  34509. Note that there's also a getCurrentProgramStateInformation() method, which only
  34510. stores the current program, not the state of the entire filter.
  34511. See also the helper function copyXmlToBinary() for storing settings as XML.
  34512. @see getCurrentProgramStateInformation
  34513. */
  34514. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  34515. /** The host will call this method if it wants to save the state of just the filter's
  34516. current program.
  34517. Unlike getStateInformation, this should only return the current program's state.
  34518. Not all hosts support this, and if you don't implement it, the base class
  34519. method just calls getStateInformation() instead. If you do implement it, be
  34520. sure to also implement getCurrentProgramStateInformation.
  34521. @see getStateInformation, setCurrentProgramStateInformation
  34522. */
  34523. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  34524. /** This must restore the filter's state from a block of data previously created
  34525. using getStateInformation().
  34526. Note that there's also a setCurrentProgramStateInformation() method, which tries
  34527. to restore just the current program, not the state of the entire filter.
  34528. See also the helper function getXmlFromBinary() for loading settings as XML.
  34529. @see setCurrentProgramStateInformation
  34530. */
  34531. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  34532. /** The host will call this method if it wants to restore the state of just the filter's
  34533. current program.
  34534. Not all hosts support this, and if you don't implement it, the base class
  34535. method just calls setStateInformation() instead. If you do implement it, be
  34536. sure to also implement getCurrentProgramStateInformation.
  34537. @see setStateInformation, getCurrentProgramStateInformation
  34538. */
  34539. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  34540. /** Adds a listener that will be called when an aspect of this processor changes. */
  34541. void addListener (AudioProcessorListener* newListener);
  34542. /** Removes a previously added listener. */
  34543. void removeListener (AudioProcessorListener* listenerToRemove);
  34544. /** Tells the processor to use this playhead object.
  34545. The processor will not take ownership of the object, so the caller must delete it when
  34546. it is no longer being used.
  34547. */
  34548. void setPlayHead (AudioPlayHead* newPlayHead) throw();
  34549. /** Not for public use - this is called before deleting an editor component. */
  34550. void editorBeingDeleted (AudioProcessorEditor* editor) throw();
  34551. /** Not for public use - this is called to initialise the processor before playing. */
  34552. void setPlayConfigDetails (int numIns, int numOuts,
  34553. double sampleRate,
  34554. int blockSize) throw();
  34555. protected:
  34556. /** Helper function that just converts an xml element into a binary blob.
  34557. Use this in your filter's getStateInformation() method if you want to
  34558. store its state as xml.
  34559. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  34560. from a binary blob.
  34561. */
  34562. static void copyXmlToBinary (const XmlElement& xml,
  34563. JUCE_NAMESPACE::MemoryBlock& destData);
  34564. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  34565. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  34566. an XmlElement object that the caller must delete when no longer needed.
  34567. */
  34568. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  34569. /** @internal */
  34570. AudioPlayHead* playHead;
  34571. /** @internal */
  34572. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  34573. private:
  34574. Array <AudioProcessorListener*> listeners;
  34575. Component::SafePointer<AudioProcessorEditor> activeEditor;
  34576. double sampleRate;
  34577. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  34578. bool suspended, nonRealtime;
  34579. CriticalSection callbackLock, listenerLock;
  34580. #if JUCE_DEBUG
  34581. BigInteger changingParams;
  34582. #endif
  34583. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  34584. };
  34585. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34586. /*** End of inlined file: juce_AudioProcessor.h ***/
  34587. /*** Start of inlined file: juce_PluginDescription.h ***/
  34588. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34589. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34590. /**
  34591. A small class to represent some facts about a particular type of plugin.
  34592. This class is for storing and managing the details about a plugin without
  34593. actually having to load an instance of it.
  34594. A KnownPluginList contains a list of PluginDescription objects.
  34595. @see KnownPluginList
  34596. */
  34597. class JUCE_API PluginDescription
  34598. {
  34599. public:
  34600. PluginDescription();
  34601. PluginDescription (const PluginDescription& other);
  34602. PluginDescription& operator= (const PluginDescription& other);
  34603. ~PluginDescription();
  34604. /** The name of the plugin. */
  34605. String name;
  34606. /** A more descriptive name for the plugin.
  34607. This may be the same as the 'name' field, but some plugins may provide an
  34608. alternative name.
  34609. */
  34610. String descriptiveName;
  34611. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  34612. */
  34613. String pluginFormatName;
  34614. /** A category, such as "Dynamics", "Reverbs", etc.
  34615. */
  34616. String category;
  34617. /** The manufacturer. */
  34618. String manufacturerName;
  34619. /** The version. This string doesn't have any particular format. */
  34620. String version;
  34621. /** Either the file containing the plugin module, or some other unique way
  34622. of identifying it.
  34623. E.g. for an AU, this would be an ID string that the component manager
  34624. could use to retrieve the plugin. For a VST, it's the file path.
  34625. */
  34626. String fileOrIdentifier;
  34627. /** The last time the plugin file was changed.
  34628. This is handy when scanning for new or changed plugins.
  34629. */
  34630. Time lastFileModTime;
  34631. /** A unique ID for the plugin.
  34632. Note that this might not be unique between formats, e.g. a VST and some
  34633. other format might actually have the same id.
  34634. @see createIdentifierString
  34635. */
  34636. int uid;
  34637. /** True if the plugin identifies itself as a synthesiser. */
  34638. bool isInstrument;
  34639. /** The number of inputs. */
  34640. int numInputChannels;
  34641. /** The number of outputs. */
  34642. int numOutputChannels;
  34643. /** Returns true if the two descriptions refer the the same plugin.
  34644. This isn't quite as simple as them just having the same file (because of
  34645. shell plugins).
  34646. */
  34647. bool isDuplicateOf (const PluginDescription& other) const;
  34648. /** Returns a string that can be saved and used to uniquely identify the
  34649. plugin again.
  34650. This contains less info than the XML encoding, and is independent of the
  34651. plugin's file location, so can be used to store a plugin ID for use
  34652. across different machines.
  34653. */
  34654. const String createIdentifierString() const;
  34655. /** Creates an XML object containing these details.
  34656. @see loadFromXml
  34657. */
  34658. XmlElement* createXml() const;
  34659. /** Reloads the info in this structure from an XML record that was previously
  34660. saved with createXML().
  34661. Returns true if the XML was a valid plugin description.
  34662. */
  34663. bool loadFromXml (const XmlElement& xml);
  34664. private:
  34665. JUCE_LEAK_DETECTOR (PluginDescription);
  34666. };
  34667. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34668. /*** End of inlined file: juce_PluginDescription.h ***/
  34669. /**
  34670. Base class for an active instance of a plugin.
  34671. This derives from the AudioProcessor class, and adds some extra functionality
  34672. that helps when wrapping dynamically loaded plugins.
  34673. @see AudioProcessor, AudioPluginFormat
  34674. */
  34675. class JUCE_API AudioPluginInstance : public AudioProcessor
  34676. {
  34677. public:
  34678. /** Destructor.
  34679. Make sure that you delete any UI components that belong to this plugin before
  34680. deleting the plugin.
  34681. */
  34682. virtual ~AudioPluginInstance();
  34683. /** Fills-in the appropriate parts of this plugin description object.
  34684. */
  34685. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  34686. /** Returns a pointer to some kind of platform-specific data about the plugin.
  34687. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  34688. cast to an AudioUnit handle.
  34689. */
  34690. virtual void* getPlatformSpecificData();
  34691. protected:
  34692. AudioPluginInstance();
  34693. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  34694. };
  34695. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34696. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  34697. class PluginDescription;
  34698. /**
  34699. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  34700. Use the static getNumFormats() and getFormat() calls to find the types
  34701. of format that are available.
  34702. */
  34703. class JUCE_API AudioPluginFormat
  34704. {
  34705. public:
  34706. /** Destructor. */
  34707. virtual ~AudioPluginFormat();
  34708. /** Returns the format name.
  34709. E.g. "VST", "AudioUnit", etc.
  34710. */
  34711. virtual const String getName() const = 0;
  34712. /** This tries to create descriptions for all the plugin types available in
  34713. a binary module file.
  34714. The file will be some kind of DLL or bundle.
  34715. Normally there will only be one type returned, but some plugins
  34716. (e.g. VST shells) can use a single DLL to create a set of different plugin
  34717. subtypes, so in that case, each subtype is returned as a separate object.
  34718. */
  34719. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  34720. const String& fileOrIdentifier) = 0;
  34721. /** Tries to recreate a type from a previously generated PluginDescription.
  34722. @see PluginDescription::createInstance
  34723. */
  34724. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  34725. /** Should do a quick check to see if this file or directory might be a plugin of
  34726. this format.
  34727. This is for searching for potential files, so it shouldn't actually try to
  34728. load the plugin or do anything time-consuming.
  34729. */
  34730. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  34731. /** Returns a readable version of the name of the plugin that this identifier refers to.
  34732. */
  34733. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  34734. /** Checks whether this plugin could possibly be loaded.
  34735. It doesn't actually need to load it, just to check whether the file or component
  34736. still exists.
  34737. */
  34738. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  34739. /** Searches a suggested set of directories for any plugins in this format.
  34740. The path might be ignored, e.g. by AUs, which are found by the OS rather
  34741. than manually.
  34742. */
  34743. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  34744. bool recursive) = 0;
  34745. /** Returns the typical places to look for this kind of plugin.
  34746. Note that if this returns no paths, it means that the format can't be scanned-for
  34747. (i.e. it's an internal format that doesn't live in files)
  34748. */
  34749. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  34750. protected:
  34751. AudioPluginFormat() throw();
  34752. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  34753. };
  34754. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34755. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  34756. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  34757. /**
  34758. Implements a plugin format manager for AudioUnits.
  34759. */
  34760. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  34761. {
  34762. public:
  34763. AudioUnitPluginFormat();
  34764. ~AudioUnitPluginFormat();
  34765. const String getName() const { return "AudioUnit"; }
  34766. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34767. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34768. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34769. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  34770. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  34771. bool doesPluginStillExist (const PluginDescription& desc);
  34772. const FileSearchPath getDefaultLocationsToSearch();
  34773. private:
  34774. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  34775. };
  34776. #endif
  34777. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34778. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  34779. #endif
  34780. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34781. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  34782. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34783. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34784. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  34785. // Sorry, this file is just a placeholder at the moment!...
  34786. /**
  34787. Implements a plugin format manager for DirectX plugins.
  34788. */
  34789. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  34790. {
  34791. public:
  34792. DirectXPluginFormat();
  34793. ~DirectXPluginFormat();
  34794. const String getName() const { return "DirectX"; }
  34795. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34796. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34797. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34798. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34799. const FileSearchPath getDefaultLocationsToSearch();
  34800. private:
  34801. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  34802. };
  34803. #endif
  34804. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34805. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  34806. #endif
  34807. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34808. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  34809. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34810. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34811. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  34812. // Sorry, this file is just a placeholder at the moment!...
  34813. /**
  34814. Implements a plugin format manager for DirectX plugins.
  34815. */
  34816. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  34817. {
  34818. public:
  34819. LADSPAPluginFormat();
  34820. ~LADSPAPluginFormat();
  34821. const String getName() const { return "LADSPA"; }
  34822. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34823. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34824. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34825. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34826. const FileSearchPath getDefaultLocationsToSearch();
  34827. private:
  34828. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  34829. };
  34830. #endif
  34831. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34832. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  34833. #endif
  34834. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34835. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  34836. #ifdef __aeffect__
  34837. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34838. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34839. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  34840. events to the list.
  34841. This is used by both the VST hosting code and the plugin wrapper.
  34842. */
  34843. class VSTMidiEventList
  34844. {
  34845. public:
  34846. VSTMidiEventList()
  34847. : numEventsUsed (0), numEventsAllocated (0)
  34848. {
  34849. }
  34850. ~VSTMidiEventList()
  34851. {
  34852. freeEvents();
  34853. }
  34854. void clear()
  34855. {
  34856. numEventsUsed = 0;
  34857. if (events != 0)
  34858. events->numEvents = 0;
  34859. }
  34860. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  34861. {
  34862. ensureSize (numEventsUsed + 1);
  34863. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  34864. events->numEvents = ++numEventsUsed;
  34865. if (numBytes <= 4)
  34866. {
  34867. if (e->type == kVstSysExType)
  34868. {
  34869. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  34870. e->type = kVstMidiType;
  34871. e->byteSize = sizeof (VstMidiEvent);
  34872. e->noteLength = 0;
  34873. e->noteOffset = 0;
  34874. e->detune = 0;
  34875. e->noteOffVelocity = 0;
  34876. }
  34877. e->deltaFrames = frameOffset;
  34878. memcpy (e->midiData, midiData, numBytes);
  34879. }
  34880. else
  34881. {
  34882. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  34883. if (se->type == kVstSysExType)
  34884. delete[] se->sysexDump;
  34885. se->sysexDump = new char [numBytes];
  34886. memcpy (se->sysexDump, midiData, numBytes);
  34887. se->type = kVstSysExType;
  34888. se->byteSize = sizeof (VstMidiSysexEvent);
  34889. se->deltaFrames = frameOffset;
  34890. se->flags = 0;
  34891. se->dumpBytes = numBytes;
  34892. se->resvd1 = 0;
  34893. se->resvd2 = 0;
  34894. }
  34895. }
  34896. // Handy method to pull the events out of an event buffer supplied by the host
  34897. // or plugin.
  34898. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  34899. {
  34900. for (int i = 0; i < events->numEvents; ++i)
  34901. {
  34902. const VstEvent* const e = events->events[i];
  34903. if (e != 0)
  34904. {
  34905. if (e->type == kVstMidiType)
  34906. {
  34907. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  34908. 4, e->deltaFrames);
  34909. }
  34910. else if (e->type == kVstSysExType)
  34911. {
  34912. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  34913. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  34914. e->deltaFrames);
  34915. }
  34916. }
  34917. }
  34918. }
  34919. void ensureSize (int numEventsNeeded)
  34920. {
  34921. if (numEventsNeeded > numEventsAllocated)
  34922. {
  34923. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  34924. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  34925. if (events == 0)
  34926. events.calloc (size, 1);
  34927. else
  34928. events.realloc (size, 1);
  34929. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  34930. {
  34931. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  34932. (int) sizeof (VstMidiSysexEvent)));
  34933. e->type = kVstMidiType;
  34934. e->byteSize = sizeof (VstMidiEvent);
  34935. events->events[i] = (VstEvent*) e;
  34936. }
  34937. numEventsAllocated = numEventsNeeded;
  34938. }
  34939. }
  34940. void freeEvents()
  34941. {
  34942. if (events != 0)
  34943. {
  34944. for (int i = numEventsAllocated; --i >= 0;)
  34945. {
  34946. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  34947. if (e->type == kVstSysExType)
  34948. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  34949. juce_free (e);
  34950. }
  34951. events.free();
  34952. numEventsUsed = 0;
  34953. numEventsAllocated = 0;
  34954. }
  34955. }
  34956. HeapBlock <VstEvents> events;
  34957. private:
  34958. int numEventsUsed, numEventsAllocated;
  34959. };
  34960. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34961. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34962. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  34963. #endif
  34964. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34965. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  34966. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34967. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34968. #if JUCE_PLUGINHOST_VST
  34969. /**
  34970. Implements a plugin format manager for VSTs.
  34971. */
  34972. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  34973. {
  34974. public:
  34975. VSTPluginFormat();
  34976. ~VSTPluginFormat();
  34977. const String getName() const { return "VST"; }
  34978. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34979. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34980. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34981. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  34982. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  34983. bool doesPluginStillExist (const PluginDescription& desc);
  34984. const FileSearchPath getDefaultLocationsToSearch();
  34985. private:
  34986. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  34987. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  34988. };
  34989. #endif
  34990. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34991. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  34992. #endif
  34993. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34994. #endif
  34995. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34996. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  34997. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34998. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34999. /**
  35000. This maintains a list of known AudioPluginFormats.
  35001. @see AudioPluginFormat
  35002. */
  35003. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  35004. {
  35005. public:
  35006. AudioPluginFormatManager();
  35007. /** Destructor. */
  35008. ~AudioPluginFormatManager();
  35009. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  35010. /** Adds any formats that it knows about, e.g. VST.
  35011. */
  35012. void addDefaultFormats();
  35013. /** Returns the number of types of format that are available.
  35014. Use getFormat() to get one of them.
  35015. */
  35016. int getNumFormats();
  35017. /** Returns one of the available formats.
  35018. @see getNumFormats
  35019. */
  35020. AudioPluginFormat* getFormat (int index);
  35021. /** Adds a format to the list.
  35022. The object passed in will be owned and deleted by the manager.
  35023. */
  35024. void addFormat (AudioPluginFormat* format);
  35025. /** Tries to load the type for this description, by trying all the formats
  35026. that this manager knows about.
  35027. The caller is responsible for deleting the object that is returned.
  35028. If it can't load the plugin, it returns 0 and leaves a message in the
  35029. errorMessage string.
  35030. */
  35031. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  35032. String& errorMessage) const;
  35033. /** Checks that the file or component for this plugin actually still exists.
  35034. (This won't try to load the plugin)
  35035. */
  35036. bool doesPluginStillExist (const PluginDescription& description) const;
  35037. private:
  35038. OwnedArray <AudioPluginFormat> formats;
  35039. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  35040. };
  35041. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  35042. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  35043. #endif
  35044. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  35045. #endif
  35046. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35047. /*** Start of inlined file: juce_KnownPluginList.h ***/
  35048. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35049. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35050. /**
  35051. Manages a list of plugin types.
  35052. This can be easily edited, saved and loaded, and used to create instances of
  35053. the plugin types in it.
  35054. @see PluginListComponent
  35055. */
  35056. class JUCE_API KnownPluginList : public ChangeBroadcaster
  35057. {
  35058. public:
  35059. /** Creates an empty list.
  35060. */
  35061. KnownPluginList();
  35062. /** Destructor. */
  35063. ~KnownPluginList();
  35064. /** Clears the list. */
  35065. void clear();
  35066. /** Returns the number of types currently in the list.
  35067. @see getType
  35068. */
  35069. int getNumTypes() const throw() { return types.size(); }
  35070. /** Returns one of the types.
  35071. @see getNumTypes
  35072. */
  35073. PluginDescription* getType (int index) const throw() { return types [index]; }
  35074. /** Looks for a type in the list which comes from this file.
  35075. */
  35076. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  35077. /** Looks for a type in the list which matches a plugin type ID.
  35078. The identifierString parameter must have been created by
  35079. PluginDescription::createIdentifierString().
  35080. */
  35081. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  35082. /** Adds a type manually from its description. */
  35083. bool addType (const PluginDescription& type);
  35084. /** Removes a type. */
  35085. void removeType (int index);
  35086. /** Looks for all types that can be loaded from a given file, and adds them
  35087. to the list.
  35088. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  35089. re-tested if it's not already in the list, or if the file's modification
  35090. time has changed since the list was created. If dontRescanIfAlreadyInList is
  35091. false, the file will always be reloaded and tested.
  35092. Returns true if any new types were added, and all the types found in this
  35093. file (even if it was already known and hasn't been re-scanned) get returned
  35094. in the array.
  35095. */
  35096. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  35097. bool dontRescanIfAlreadyInList,
  35098. OwnedArray <PluginDescription>& typesFound,
  35099. AudioPluginFormat& formatToUse);
  35100. /** Returns true if the specified file is already known about and if it
  35101. hasn't been modified since our entry was created.
  35102. */
  35103. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  35104. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  35105. If any types are found in the files, their descriptions are returned in the array.
  35106. */
  35107. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  35108. OwnedArray <PluginDescription>& typesFound);
  35109. /** Sort methods used to change the order of the plugins in the list.
  35110. */
  35111. enum SortMethod
  35112. {
  35113. defaultOrder = 0,
  35114. sortAlphabetically,
  35115. sortByCategory,
  35116. sortByManufacturer,
  35117. sortByFileSystemLocation
  35118. };
  35119. /** Adds all the plugin types to a popup menu so that the user can select one.
  35120. Depending on the sort method, it may add sub-menus for categories,
  35121. manufacturers, etc.
  35122. Use getIndexChosenByMenu() to find out the type that was chosen.
  35123. */
  35124. void addToMenu (PopupMenu& menu,
  35125. const SortMethod sortMethod) const;
  35126. /** Converts a menu item index that has been chosen into its index in this list.
  35127. Returns -1 if it's not an ID that was used.
  35128. @see addToMenu
  35129. */
  35130. int getIndexChosenByMenu (int menuResultCode) const;
  35131. /** Sorts the list. */
  35132. void sort (const SortMethod method);
  35133. /** Creates some XML that can be used to store the state of this list.
  35134. */
  35135. XmlElement* createXml() const;
  35136. /** Recreates the state of this list from its stored XML format.
  35137. */
  35138. void recreateFromXml (const XmlElement& xml);
  35139. private:
  35140. OwnedArray <PluginDescription> types;
  35141. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  35142. };
  35143. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  35144. /*** End of inlined file: juce_KnownPluginList.h ***/
  35145. #endif
  35146. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  35147. #endif
  35148. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35149. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  35150. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35151. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35152. /**
  35153. Scans a directory for plugins, and adds them to a KnownPluginList.
  35154. To use one of these, create it and call scanNextFile() repeatedly, until
  35155. it returns false.
  35156. */
  35157. class JUCE_API PluginDirectoryScanner
  35158. {
  35159. public:
  35160. /**
  35161. Creates a scanner.
  35162. @param listToAddResultsTo this will get the new types added to it.
  35163. @param formatToLookFor this is the type of format that you want to look for
  35164. @param directoriesToSearch the path to search
  35165. @param searchRecursively true to search recursively
  35166. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  35167. be used as a file to store the names of any plugins
  35168. that crash during initialisation. If there are
  35169. any plugins listed in it, then these will always
  35170. be scanned after all other possible files have
  35171. been tried - in this way, even if there's a few
  35172. dodgy plugins in your path, then a couple of rescans
  35173. will still manage to find all the proper plugins.
  35174. It's probably best to choose a file in the user's
  35175. application data directory (alongside your app's
  35176. settings file) for this. The file format it uses
  35177. is just a list of filenames of the modules that
  35178. failed.
  35179. */
  35180. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  35181. AudioPluginFormat& formatToLookFor,
  35182. FileSearchPath directoriesToSearch,
  35183. bool searchRecursively,
  35184. const File& deadMansPedalFile);
  35185. /** Destructor. */
  35186. ~PluginDirectoryScanner();
  35187. /** Tries the next likely-looking file.
  35188. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  35189. re-tested if it's not already in the list, or if the file's modification
  35190. time has changed since the list was created. If dontRescanIfAlreadyInList is
  35191. false, the file will always be reloaded and tested.
  35192. Returns false when there are no more files to try.
  35193. */
  35194. bool scanNextFile (bool dontRescanIfAlreadyInList);
  35195. /** Skips over the next file without scanning it.
  35196. Returns false when there are no more files to try.
  35197. */
  35198. bool skipNextFile();
  35199. /** Returns the description of the plugin that will be scanned during the next
  35200. call to scanNextFile().
  35201. This is handy if you want to show the user which file is currently getting
  35202. scanned.
  35203. */
  35204. const String getNextPluginFileThatWillBeScanned() const;
  35205. /** Returns the estimated progress, between 0 and 1.
  35206. */
  35207. float getProgress() const { return progress; }
  35208. /** This returns a list of all the filenames of things that looked like being
  35209. a plugin file, but which failed to open for some reason.
  35210. */
  35211. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  35212. private:
  35213. KnownPluginList& list;
  35214. AudioPluginFormat& format;
  35215. StringArray filesOrIdentifiersToScan;
  35216. File deadMansPedalFile;
  35217. StringArray failedFiles;
  35218. int nextIndex;
  35219. float progress;
  35220. const StringArray getDeadMansPedalFile();
  35221. void setDeadMansPedalFile (const StringArray& newContents);
  35222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  35223. };
  35224. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  35225. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  35226. #endif
  35227. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35228. /*** Start of inlined file: juce_PluginListComponent.h ***/
  35229. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35230. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35231. /*** Start of inlined file: juce_ListBox.h ***/
  35232. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  35233. #define __JUCE_LISTBOX_JUCEHEADER__
  35234. class ListViewport;
  35235. /**
  35236. A subclass of this is used to drive a ListBox.
  35237. @see ListBox
  35238. */
  35239. class JUCE_API ListBoxModel
  35240. {
  35241. public:
  35242. /** Destructor. */
  35243. virtual ~ListBoxModel() {}
  35244. /** This has to return the number of items in the list.
  35245. @see ListBox::getNumRows()
  35246. */
  35247. virtual int getNumRows() = 0;
  35248. /** This method must be implemented to draw a row of the list.
  35249. */
  35250. virtual void paintListBoxItem (int rowNumber,
  35251. Graphics& g,
  35252. int width, int height,
  35253. bool rowIsSelected) = 0;
  35254. /** This is used to create or update a custom component to go in a row of the list.
  35255. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  35256. and handle mouse clicks with listBoxItemClicked().
  35257. This method will be called whenever a custom component might need to be updated - e.g.
  35258. when the table is changed, or TableListBox::updateContent() is called.
  35259. If you don't need a custom component for the specified row, then return 0.
  35260. If you do want a custom component, and the existingComponentToUpdate is null, then
  35261. this method must create a suitable new component and return it.
  35262. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35263. by this method. In this case, the method must either update it to make sure it's correctly representing
  35264. the given row (which may be different from the one that the component was created for), or it can
  35265. delete this component and return a new one.
  35266. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  35267. */
  35268. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  35269. Component* existingComponentToUpdate);
  35270. /** This can be overridden to react to the user clicking on a row.
  35271. @see listBoxItemDoubleClicked
  35272. */
  35273. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  35274. /** This can be overridden to react to the user double-clicking on a row.
  35275. @see listBoxItemClicked
  35276. */
  35277. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  35278. /** This can be overridden to react to the user double-clicking on a part of the list where
  35279. there are no rows.
  35280. @see listBoxItemClicked
  35281. */
  35282. virtual void backgroundClicked();
  35283. /** Override this to be informed when rows are selected or deselected.
  35284. This will be called whenever a row is selected or deselected. If a range of
  35285. rows is selected all at once, this will just be called once for that event.
  35286. @param lastRowSelected the last row that the user selected. If no
  35287. rows are currently selected, this may be -1.
  35288. */
  35289. virtual void selectedRowsChanged (int lastRowSelected);
  35290. /** Override this to be informed when the delete key is pressed.
  35291. If no rows are selected when they press the key, this won't be called.
  35292. @param lastRowSelected the last row that had been selected when they pressed the
  35293. key - if there are multiple selections, this might not be
  35294. very useful
  35295. */
  35296. virtual void deleteKeyPressed (int lastRowSelected);
  35297. /** Override this to be informed when the return key is pressed.
  35298. If no rows are selected when they press the key, this won't be called.
  35299. @param lastRowSelected the last row that had been selected when they pressed the
  35300. key - if there are multiple selections, this might not be
  35301. very useful
  35302. */
  35303. virtual void returnKeyPressed (int lastRowSelected);
  35304. /** Override this to be informed when the list is scrolled.
  35305. This might be caused by the user moving the scrollbar, or by programmatic changes
  35306. to the list position.
  35307. */
  35308. virtual void listWasScrolled();
  35309. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  35310. If this returns a non-empty name then when the user drags a row, the listbox will
  35311. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  35312. a drag-and-drop operation, using this string as the source description, with the listbox
  35313. itself as the source component.
  35314. @see DragAndDropContainer::startDragging
  35315. */
  35316. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35317. /** You can override this to provide tool tips for specific rows.
  35318. @see TooltipClient
  35319. */
  35320. virtual const String getTooltipForRow (int row);
  35321. };
  35322. /**
  35323. A list of items that can be scrolled vertically.
  35324. To create a list, you'll need to create a subclass of ListBoxModel. This can
  35325. either paint each row of the list and respond to events via callbacks, or for
  35326. more specialised tasks, it can supply a custom component to fill each row.
  35327. @see ComboBox, TableListBox
  35328. */
  35329. class JUCE_API ListBox : public Component,
  35330. public SettableTooltipClient
  35331. {
  35332. public:
  35333. /** Creates a ListBox.
  35334. The model pointer passed-in can be null, in which case you can set it later
  35335. with setModel().
  35336. */
  35337. ListBox (const String& componentName = String::empty,
  35338. ListBoxModel* model = 0);
  35339. /** Destructor. */
  35340. ~ListBox();
  35341. /** Changes the current data model to display. */
  35342. void setModel (ListBoxModel* newModel);
  35343. /** Returns the current list model. */
  35344. ListBoxModel* getModel() const throw() { return model; }
  35345. /** Causes the list to refresh its content.
  35346. Call this when the number of rows in the list changes, or if you want it
  35347. to call refreshComponentForRow() on all the row components.
  35348. Be careful not to call it from a different thread, though, as it's not
  35349. thread-safe.
  35350. */
  35351. void updateContent();
  35352. /** Turns on multiple-selection of rows.
  35353. By default this is disabled.
  35354. When your row component gets clicked you'll need to call the
  35355. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  35356. clicked and to get it to do the appropriate selection based on whether
  35357. the ctrl/shift keys are held down.
  35358. */
  35359. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  35360. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  35361. This function is here primarily for the ComboBox class to use, but might be
  35362. useful for some other purpose too.
  35363. */
  35364. void setMouseMoveSelectsRows (bool shouldSelect);
  35365. /** Selects a row.
  35366. If the row is already selected, this won't do anything.
  35367. @param rowNumber the row to select
  35368. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  35369. the selected row is off-screen, it'll scroll to make
  35370. sure that row is on-screen
  35371. @param deselectOthersFirst if true and there are multiple selections, these will
  35372. first be deselected before this item is selected
  35373. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  35374. deselectAllRows, selectRangeOfRows
  35375. */
  35376. void selectRow (int rowNumber,
  35377. bool dontScrollToShowThisRow = false,
  35378. bool deselectOthersFirst = true);
  35379. /** Selects a set of rows.
  35380. This will add these rows to the current selection, so you might need to
  35381. clear the current selection first with deselectAllRows()
  35382. @param firstRow the first row to select (inclusive)
  35383. @param lastRow the last row to select (inclusive)
  35384. */
  35385. void selectRangeOfRows (int firstRow,
  35386. int lastRow);
  35387. /** Deselects a row.
  35388. If it's not currently selected, this will do nothing.
  35389. @see selectRow, deselectAllRows
  35390. */
  35391. void deselectRow (int rowNumber);
  35392. /** Deselects any currently selected rows.
  35393. @see deselectRow
  35394. */
  35395. void deselectAllRows();
  35396. /** Selects or deselects a row.
  35397. If the row's currently selected, this deselects it, and vice-versa.
  35398. */
  35399. void flipRowSelection (int rowNumber);
  35400. /** Returns a sparse set indicating the rows that are currently selected.
  35401. @see setSelectedRows
  35402. */
  35403. const SparseSet<int> getSelectedRows() const;
  35404. /** Sets the rows that should be selected, based on an explicit set of ranges.
  35405. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  35406. method will be called. If it's false, no notification will be sent to the model.
  35407. @see getSelectedRows
  35408. */
  35409. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  35410. bool sendNotificationEventToModel = true);
  35411. /** Checks whether a row is selected.
  35412. */
  35413. bool isRowSelected (int rowNumber) const;
  35414. /** Returns the number of rows that are currently selected.
  35415. @see getSelectedRow, isRowSelected, getLastRowSelected
  35416. */
  35417. int getNumSelectedRows() const;
  35418. /** Returns the row number of a selected row.
  35419. This will return the row number of the Nth selected row. The row numbers returned will
  35420. be sorted in order from low to high.
  35421. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  35422. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  35423. selected
  35424. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  35425. */
  35426. int getSelectedRow (int index = 0) const;
  35427. /** Returns the last row that the user selected.
  35428. This isn't the same as the highest row number that is currently selected - if the user
  35429. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  35430. If nothing is selected, it will return -1.
  35431. */
  35432. int getLastRowSelected() const;
  35433. /** Multiply-selects rows based on the modifier keys.
  35434. If no modifier keys are down, this will select the given row and
  35435. deselect any others.
  35436. If the ctrl (or command on the Mac) key is down, it'll flip the
  35437. state of the selected row.
  35438. If the shift key is down, it'll select up to the given row from the
  35439. last row selected.
  35440. @see selectRow
  35441. */
  35442. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  35443. const ModifierKeys& modifiers,
  35444. bool isMouseUpEvent);
  35445. /** Scrolls the list to a particular position.
  35446. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  35447. 1.0 scrolls to the bottom.
  35448. If the total number of rows all fit onto the screen at once, then this
  35449. method won't do anything.
  35450. @see getVerticalPosition
  35451. */
  35452. void setVerticalPosition (double newProportion);
  35453. /** Returns the current vertical position as a proportion of the total.
  35454. This can be used in conjunction with setVerticalPosition() to save and restore
  35455. the list's position. It returns a value in the range 0 to 1.
  35456. @see setVerticalPosition
  35457. */
  35458. double getVerticalPosition() const;
  35459. /** Scrolls if necessary to make sure that a particular row is visible.
  35460. */
  35461. void scrollToEnsureRowIsOnscreen (int row);
  35462. /** Returns a pointer to the scrollbar.
  35463. (Unlikely to be useful for most people).
  35464. */
  35465. ScrollBar* getVerticalScrollBar() const throw();
  35466. /** Returns a pointer to the scrollbar.
  35467. (Unlikely to be useful for most people).
  35468. */
  35469. ScrollBar* getHorizontalScrollBar() const throw();
  35470. /** Finds the row index that contains a given x,y position.
  35471. The position is relative to the ListBox's top-left.
  35472. If no row exists at this position, the method will return -1.
  35473. @see getComponentForRowNumber
  35474. */
  35475. int getRowContainingPosition (int x, int y) const throw();
  35476. /** Finds a row index that would be the most suitable place to insert a new
  35477. item for a given position.
  35478. This is useful when the user is e.g. dragging and dropping onto the listbox,
  35479. because it lets you easily choose the best position to insert the item that
  35480. they drop, based on where they drop it.
  35481. If the position is out of range, this will return -1. If the position is
  35482. beyond the end of the list, it will return getNumRows() to indicate the end
  35483. of the list.
  35484. @see getComponentForRowNumber
  35485. */
  35486. int getInsertionIndexForPosition (int x, int y) const throw();
  35487. /** Returns the position of one of the rows, relative to the top-left of
  35488. the listbox.
  35489. This may be off-screen, and the range of the row number that is passed-in is
  35490. not checked to see if it's a valid row.
  35491. */
  35492. const Rectangle<int> getRowPosition (int rowNumber,
  35493. bool relativeToComponentTopLeft) const throw();
  35494. /** Finds the row component for a given row in the list.
  35495. The component returned will have been created using createRowComponent().
  35496. If the component for this row is off-screen or if the row is out-of-range,
  35497. this will return 0.
  35498. @see getRowContainingPosition
  35499. */
  35500. Component* getComponentForRowNumber (int rowNumber) const throw();
  35501. /** Returns the row number that the given component represents.
  35502. If the component isn't one of the list's rows, this will return -1.
  35503. */
  35504. int getRowNumberOfComponent (Component* rowComponent) const throw();
  35505. /** Returns the width of a row (which may be less than the width of this component
  35506. if there's a scrollbar).
  35507. */
  35508. int getVisibleRowWidth() const throw();
  35509. /** Sets the height of each row in the list.
  35510. The default height is 22 pixels.
  35511. @see getRowHeight
  35512. */
  35513. void setRowHeight (int newHeight);
  35514. /** Returns the height of a row in the list.
  35515. @see setRowHeight
  35516. */
  35517. int getRowHeight() const throw() { return rowHeight; }
  35518. /** Returns the number of rows actually visible.
  35519. This is the number of whole rows which will fit on-screen, so the value might
  35520. be more than the actual number of rows in the list.
  35521. */
  35522. int getNumRowsOnScreen() const throw();
  35523. /** A set of colour IDs to use to change the colour of various aspects of the label.
  35524. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35525. methods.
  35526. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35527. */
  35528. enum ColourIds
  35529. {
  35530. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  35531. Make this transparent if you don't want the background to be filled. */
  35532. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  35533. Make this transparent to not have an outline. */
  35534. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  35535. };
  35536. /** Sets the thickness of a border that will be drawn around the box.
  35537. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  35538. @see outlineColourId
  35539. */
  35540. void setOutlineThickness (int outlineThickness);
  35541. /** Returns the thickness of outline that will be drawn around the listbox.
  35542. @see setOutlineColour
  35543. */
  35544. int getOutlineThickness() const throw() { return outlineThickness; }
  35545. /** Sets a component that the list should use as a header.
  35546. This will position the given component at the top of the list, maintaining the
  35547. height of the component passed-in, but rescaling it horizontally to match the
  35548. width of the items in the listbox.
  35549. The component will be deleted when setHeaderComponent() is called with a
  35550. different component, or when the listbox is deleted.
  35551. */
  35552. void setHeaderComponent (Component* newHeaderComponent);
  35553. /** Changes the width of the rows in the list.
  35554. This can be used to make the list's row components wider than the list itself - the
  35555. width of the rows will be either the width of the list or this value, whichever is
  35556. greater, and if the rows become wider than the list, a horizontal scrollbar will
  35557. appear.
  35558. The default value for this is 0, which means that the rows will always
  35559. be the same width as the list.
  35560. */
  35561. void setMinimumContentWidth (int newMinimumWidth);
  35562. /** Returns the space currently available for the row items, taking into account
  35563. borders, scrollbars, etc.
  35564. */
  35565. int getVisibleContentWidth() const throw();
  35566. /** Repaints one of the rows.
  35567. This is a lightweight alternative to calling updateContent, and just causes a
  35568. repaint of the row's area.
  35569. */
  35570. void repaintRow (int rowNumber) throw();
  35571. /** This fairly obscure method creates an image that just shows the currently
  35572. selected row components.
  35573. It's a handy method for doing drag-and-drop, as it can be passed to the
  35574. DragAndDropContainer for use as the drag image.
  35575. Note that it will make the row components temporarily invisible, so if you're
  35576. using custom components this could affect them if they're sensitive to that
  35577. sort of thing.
  35578. @see Component::createComponentSnapshot
  35579. */
  35580. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  35581. /** Returns the viewport that this ListBox uses.
  35582. You may need to use this to change parameters such as whether scrollbars
  35583. are shown, etc.
  35584. */
  35585. Viewport* getViewport() const throw();
  35586. /** @internal */
  35587. bool keyPressed (const KeyPress& key);
  35588. /** @internal */
  35589. bool keyStateChanged (bool isKeyDown);
  35590. /** @internal */
  35591. void paint (Graphics& g);
  35592. /** @internal */
  35593. void paintOverChildren (Graphics& g);
  35594. /** @internal */
  35595. void resized();
  35596. /** @internal */
  35597. void visibilityChanged();
  35598. /** @internal */
  35599. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35600. /** @internal */
  35601. void mouseMove (const MouseEvent&);
  35602. /** @internal */
  35603. void mouseExit (const MouseEvent&);
  35604. /** @internal */
  35605. void mouseUp (const MouseEvent&);
  35606. /** @internal */
  35607. void colourChanged();
  35608. /** @internal */
  35609. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  35610. private:
  35611. friend class ListViewport;
  35612. friend class TableListBox;
  35613. ListBoxModel* model;
  35614. ScopedPointer<ListViewport> viewport;
  35615. ScopedPointer<Component> headerComponent;
  35616. int totalItems, rowHeight, minimumRowWidth;
  35617. int outlineThickness;
  35618. int lastRowSelected;
  35619. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  35620. SparseSet <int> selected;
  35621. void selectRowInternal (int rowNumber,
  35622. bool dontScrollToShowThisRow,
  35623. bool deselectOthersFirst,
  35624. bool isMouseClick);
  35625. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  35626. };
  35627. #endif // __JUCE_LISTBOX_JUCEHEADER__
  35628. /*** End of inlined file: juce_ListBox.h ***/
  35629. /*** Start of inlined file: juce_TextButton.h ***/
  35630. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35631. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  35632. /**
  35633. A button that uses the standard lozenge-shaped background with a line of
  35634. text on it.
  35635. @see Button, DrawableButton
  35636. */
  35637. class JUCE_API TextButton : public Button
  35638. {
  35639. public:
  35640. /** Creates a TextButton.
  35641. @param buttonName the text to put in the button (the component's name is also
  35642. initially set to this string, but these can be changed later
  35643. using the setName() and setButtonText() methods)
  35644. @param toolTip an optional string to use as a toolip
  35645. @see Button
  35646. */
  35647. TextButton (const String& buttonName = String::empty,
  35648. const String& toolTip = String::empty);
  35649. /** Destructor. */
  35650. ~TextButton();
  35651. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35652. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35653. methods.
  35654. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35655. */
  35656. enum ColourIds
  35657. {
  35658. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  35659. 'off'). The look-and-feel class might re-interpret this to add
  35660. effects, etc. */
  35661. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  35662. 'on'). The look-and-feel class might re-interpret this to add
  35663. effects, etc. */
  35664. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  35665. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  35666. };
  35667. /** Resizes the button to fit neatly around its current text.
  35668. If newHeight is >= 0, the button's height will be changed to this
  35669. value. If it's less than zero, its height will be unaffected.
  35670. */
  35671. void changeWidthToFitText (int newHeight = -1);
  35672. /** This can be overridden to use different fonts than the default one.
  35673. Note that you'll need to set the font's size appropriately, too.
  35674. */
  35675. virtual const Font getFont();
  35676. protected:
  35677. /** @internal */
  35678. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35679. /** @internal */
  35680. void colourChanged();
  35681. private:
  35682. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  35683. };
  35684. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  35685. /*** End of inlined file: juce_TextButton.h ***/
  35686. /**
  35687. A component displaying a list of plugins, with options to scan for them,
  35688. add, remove and sort them.
  35689. */
  35690. class JUCE_API PluginListComponent : public Component,
  35691. public ListBoxModel,
  35692. public ChangeListener,
  35693. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  35694. public Timer
  35695. {
  35696. public:
  35697. /**
  35698. Creates the list component.
  35699. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  35700. The properties file, if supplied, is used to store the user's last search paths.
  35701. */
  35702. PluginListComponent (KnownPluginList& listToRepresent,
  35703. const File& deadMansPedalFile,
  35704. PropertiesFile* propertiesToUse);
  35705. /** Destructor. */
  35706. ~PluginListComponent();
  35707. /** @internal */
  35708. void resized();
  35709. /** @internal */
  35710. bool isInterestedInFileDrag (const StringArray& files);
  35711. /** @internal */
  35712. void filesDropped (const StringArray& files, int, int);
  35713. /** @internal */
  35714. int getNumRows();
  35715. /** @internal */
  35716. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  35717. /** @internal */
  35718. void deleteKeyPressed (int lastRowSelected);
  35719. /** @internal */
  35720. void buttonClicked (Button* b);
  35721. /** @internal */
  35722. void changeListenerCallback (ChangeBroadcaster*);
  35723. /** @internal */
  35724. void timerCallback();
  35725. private:
  35726. KnownPluginList& list;
  35727. File deadMansPedalFile;
  35728. ListBox listBox;
  35729. TextButton optionsButton;
  35730. PropertiesFile* propertiesToUse;
  35731. int typeToScan;
  35732. void scanFor (AudioPluginFormat* format);
  35733. static void optionsMenuStaticCallback (int result, PluginListComponent*);
  35734. void optionsMenuCallback (int result);
  35735. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  35736. };
  35737. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35738. /*** End of inlined file: juce_PluginListComponent.h ***/
  35739. #endif
  35740. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  35741. #endif
  35742. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  35743. #endif
  35744. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  35745. #endif
  35746. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35747. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  35748. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35749. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35750. /**
  35751. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  35752. Use one of these objects if you want to wire-up a set of AudioProcessors
  35753. and play back the result.
  35754. Processors can be added to the graph as "nodes" using addNode(), and once
  35755. added, you can connect any of their input or output channels to other
  35756. nodes using addConnection().
  35757. To play back a graph through an audio device, you might want to use an
  35758. AudioProcessorPlayer object.
  35759. */
  35760. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  35761. public AsyncUpdater
  35762. {
  35763. public:
  35764. /** Creates an empty graph.
  35765. */
  35766. AudioProcessorGraph();
  35767. /** Destructor.
  35768. Any processor objects that have been added to the graph will also be deleted.
  35769. */
  35770. ~AudioProcessorGraph();
  35771. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  35772. To create a node, call AudioProcessorGraph::addNode().
  35773. */
  35774. class JUCE_API Node : public ReferenceCountedObject
  35775. {
  35776. public:
  35777. /** The ID number assigned to this node.
  35778. This is assigned by the graph that owns it, and can't be changed.
  35779. */
  35780. const uint32 id;
  35781. /** The actual processor object that this node represents. */
  35782. AudioProcessor* getProcessor() const throw() { return processor; }
  35783. /** A set of user-definable properties that are associated with this node.
  35784. This can be used to attach values to the node for whatever purpose seems
  35785. useful. For example, you might store an x and y position if your application
  35786. is displaying the nodes on-screen.
  35787. */
  35788. NamedValueSet properties;
  35789. /** A convenient typedef for referring to a pointer to a node object.
  35790. */
  35791. typedef ReferenceCountedObjectPtr <Node> Ptr;
  35792. private:
  35793. friend class AudioProcessorGraph;
  35794. const ScopedPointer<AudioProcessor> processor;
  35795. bool isPrepared;
  35796. Node (uint32 id, AudioProcessor* processor);
  35797. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  35798. void unprepare();
  35799. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  35800. };
  35801. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  35802. To create a connection, use AudioProcessorGraph::addConnection().
  35803. */
  35804. struct JUCE_API Connection
  35805. {
  35806. public:
  35807. /** The ID number of the node which is the input source for this connection.
  35808. @see AudioProcessorGraph::getNodeForId
  35809. */
  35810. uint32 sourceNodeId;
  35811. /** The index of the output channel of the source node from which this
  35812. connection takes its data.
  35813. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35814. it is referring to the source node's midi output. Otherwise, it is the zero-based
  35815. index of an audio output channel in the source node.
  35816. */
  35817. int sourceChannelIndex;
  35818. /** The ID number of the node which is the destination for this connection.
  35819. @see AudioProcessorGraph::getNodeForId
  35820. */
  35821. uint32 destNodeId;
  35822. /** The index of the input channel of the destination node to which this
  35823. connection delivers its data.
  35824. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35825. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  35826. index of an audio input channel in the destination node.
  35827. */
  35828. int destChannelIndex;
  35829. private:
  35830. JUCE_LEAK_DETECTOR (Connection);
  35831. };
  35832. /** Deletes all nodes and connections from this graph.
  35833. Any processor objects in the graph will be deleted.
  35834. */
  35835. void clear();
  35836. /** Returns the number of nodes in the graph. */
  35837. int getNumNodes() const { return nodes.size(); }
  35838. /** Returns a pointer to one of the nodes in the graph.
  35839. This will return 0 if the index is out of range.
  35840. @see getNodeForId
  35841. */
  35842. Node* getNode (const int index) const { return nodes [index]; }
  35843. /** Searches the graph for a node with the given ID number and returns it.
  35844. If no such node was found, this returns 0.
  35845. @see getNode
  35846. */
  35847. Node* getNodeForId (const uint32 nodeId) const;
  35848. /** Adds a node to the graph.
  35849. This creates a new node in the graph, for the specified processor. Once you have
  35850. added a processor to the graph, the graph owns it and will delete it later when
  35851. it is no longer needed.
  35852. The optional nodeId parameter lets you specify an ID to use for the node, but
  35853. if the value is already in use, this new node will overwrite the old one.
  35854. If this succeeds, it returns a pointer to the newly-created node.
  35855. */
  35856. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  35857. /** Deletes a node within the graph which has the specified ID.
  35858. This will also delete any connections that are attached to this node.
  35859. */
  35860. bool removeNode (uint32 nodeId);
  35861. /** Returns the number of connections in the graph. */
  35862. int getNumConnections() const { return connections.size(); }
  35863. /** Returns a pointer to one of the connections in the graph. */
  35864. const Connection* getConnection (int index) const { return connections [index]; }
  35865. /** Searches for a connection between some specified channels.
  35866. If no such connection is found, this returns 0.
  35867. */
  35868. const Connection* getConnectionBetween (uint32 sourceNodeId,
  35869. int sourceChannelIndex,
  35870. uint32 destNodeId,
  35871. int destChannelIndex) const;
  35872. /** Returns true if there is a connection between any of the channels of
  35873. two specified nodes.
  35874. */
  35875. bool isConnected (uint32 possibleSourceNodeId,
  35876. uint32 possibleDestNodeId) const;
  35877. /** Returns true if it would be legal to connect the specified points.
  35878. */
  35879. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  35880. uint32 destNodeId, int destChannelIndex) const;
  35881. /** Attempts to connect two specified channels of two nodes.
  35882. If this isn't allowed (e.g. because you're trying to connect a midi channel
  35883. to an audio one or other such nonsense), then it'll return false.
  35884. */
  35885. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35886. uint32 destNodeId, int destChannelIndex);
  35887. /** Deletes the connection with the specified index.
  35888. Returns true if a connection was actually deleted.
  35889. */
  35890. void removeConnection (int index);
  35891. /** Deletes any connection between two specified points.
  35892. Returns true if a connection was actually deleted.
  35893. */
  35894. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35895. uint32 destNodeId, int destChannelIndex);
  35896. /** Removes all connections from the specified node.
  35897. */
  35898. bool disconnectNode (uint32 nodeId);
  35899. /** Performs a sanity checks of all the connections.
  35900. This might be useful if some of the processors are doing things like changing
  35901. their channel counts, which could render some connections obsolete.
  35902. */
  35903. bool removeIllegalConnections();
  35904. /** A special number that represents the midi channel of a node.
  35905. This is used as a channel index value if you want to refer to the midi input
  35906. or output instead of an audio channel.
  35907. */
  35908. static const int midiChannelIndex;
  35909. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  35910. in order to use the audio that comes into and out of the graph itself.
  35911. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  35912. node in the graph which delivers the audio that is coming into the parent
  35913. graph. This allows you to stream the data to other nodes and process the
  35914. incoming audio.
  35915. Likewise, one of these in "output" mode can be sent data which it will add to
  35916. the sum of data being sent to the graph's output.
  35917. @see AudioProcessorGraph
  35918. */
  35919. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  35920. {
  35921. public:
  35922. /** Specifies the mode in which this processor will operate.
  35923. */
  35924. enum IODeviceType
  35925. {
  35926. audioInputNode, /**< In this mode, the processor has output channels
  35927. representing all the audio input channels that are
  35928. coming into its parent audio graph. */
  35929. audioOutputNode, /**< In this mode, the processor has input channels
  35930. representing all the audio output channels that are
  35931. going out of its parent audio graph. */
  35932. midiInputNode, /**< In this mode, the processor has a midi output which
  35933. delivers the same midi data that is arriving at its
  35934. parent graph. */
  35935. midiOutputNode /**< In this mode, the processor has a midi input and
  35936. any data sent to it will be passed out of the parent
  35937. graph. */
  35938. };
  35939. /** Returns the mode of this processor. */
  35940. IODeviceType getType() const { return type; }
  35941. /** Returns the parent graph to which this processor belongs, or 0 if it
  35942. hasn't yet been added to one. */
  35943. AudioProcessorGraph* getParentGraph() const { return graph; }
  35944. /** True if this is an audio or midi input. */
  35945. bool isInput() const;
  35946. /** True if this is an audio or midi output. */
  35947. bool isOutput() const;
  35948. AudioGraphIOProcessor (const IODeviceType type);
  35949. ~AudioGraphIOProcessor();
  35950. const String getName() const;
  35951. void fillInPluginDescription (PluginDescription& d) const;
  35952. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35953. void releaseResources();
  35954. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35955. const String getInputChannelName (int channelIndex) const;
  35956. const String getOutputChannelName (int channelIndex) const;
  35957. bool isInputChannelStereoPair (int index) const;
  35958. bool isOutputChannelStereoPair (int index) const;
  35959. bool acceptsMidi() const;
  35960. bool producesMidi() const;
  35961. bool hasEditor() const;
  35962. AudioProcessorEditor* createEditor();
  35963. int getNumParameters();
  35964. const String getParameterName (int);
  35965. float getParameter (int);
  35966. const String getParameterText (int);
  35967. void setParameter (int, float);
  35968. int getNumPrograms();
  35969. int getCurrentProgram();
  35970. void setCurrentProgram (int);
  35971. const String getProgramName (int);
  35972. void changeProgramName (int, const String&);
  35973. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35974. void setStateInformation (const void* data, int sizeInBytes);
  35975. /** @internal */
  35976. void setParentGraph (AudioProcessorGraph* graph);
  35977. private:
  35978. const IODeviceType type;
  35979. AudioProcessorGraph* graph;
  35980. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  35981. };
  35982. // AudioProcessor methods:
  35983. const String getName() const;
  35984. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35985. void releaseResources();
  35986. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35987. const String getInputChannelName (int channelIndex) const;
  35988. const String getOutputChannelName (int channelIndex) const;
  35989. bool isInputChannelStereoPair (int index) const;
  35990. bool isOutputChannelStereoPair (int index) const;
  35991. bool acceptsMidi() const;
  35992. bool producesMidi() const;
  35993. bool hasEditor() const { return false; }
  35994. AudioProcessorEditor* createEditor() { return 0; }
  35995. int getNumParameters() { return 0; }
  35996. const String getParameterName (int) { return String::empty; }
  35997. float getParameter (int) { return 0; }
  35998. const String getParameterText (int) { return String::empty; }
  35999. void setParameter (int, float) { }
  36000. int getNumPrograms() { return 0; }
  36001. int getCurrentProgram() { return 0; }
  36002. void setCurrentProgram (int) { }
  36003. const String getProgramName (int) { return String::empty; }
  36004. void changeProgramName (int, const String&) { }
  36005. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  36006. void setStateInformation (const void* data, int sizeInBytes);
  36007. /** @internal */
  36008. void handleAsyncUpdate();
  36009. private:
  36010. ReferenceCountedArray <Node> nodes;
  36011. OwnedArray <Connection> connections;
  36012. int lastNodeId;
  36013. AudioSampleBuffer renderingBuffers;
  36014. OwnedArray <MidiBuffer> midiBuffers;
  36015. CriticalSection renderLock;
  36016. Array<void*> renderingOps;
  36017. friend class AudioGraphIOProcessor;
  36018. AudioSampleBuffer* currentAudioInputBuffer;
  36019. AudioSampleBuffer currentAudioOutputBuffer;
  36020. MidiBuffer* currentMidiInputBuffer;
  36021. MidiBuffer currentMidiOutputBuffer;
  36022. void clearRenderingSequence();
  36023. void buildRenderingSequence();
  36024. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  36025. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  36026. };
  36027. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  36028. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  36029. #endif
  36030. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  36031. #endif
  36032. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36033. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  36034. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36035. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36036. /**
  36037. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  36038. To use one of these, just make it the callback used by your AudioIODevice, and
  36039. give it a processor to use by calling setProcessor().
  36040. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  36041. input to send both streams through the processor.
  36042. @see AudioProcessor, AudioProcessorGraph
  36043. */
  36044. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  36045. public MidiInputCallback
  36046. {
  36047. public:
  36048. /**
  36049. */
  36050. AudioProcessorPlayer();
  36051. /** Destructor. */
  36052. virtual ~AudioProcessorPlayer();
  36053. /** Sets the processor that should be played.
  36054. The processor that is passed in will not be deleted or owned by this object.
  36055. To stop anything playing, pass in 0 to this method.
  36056. */
  36057. void setProcessor (AudioProcessor* processorToPlay);
  36058. /** Returns the current audio processor that is being played.
  36059. */
  36060. AudioProcessor* getCurrentProcessor() const { return processor; }
  36061. /** Returns a midi message collector that you can pass midi messages to if you
  36062. want them to be injected into the midi stream that is being sent to the
  36063. processor.
  36064. */
  36065. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  36066. /** @internal */
  36067. void audioDeviceIOCallback (const float** inputChannelData,
  36068. int totalNumInputChannels,
  36069. float** outputChannelData,
  36070. int totalNumOutputChannels,
  36071. int numSamples);
  36072. /** @internal */
  36073. void audioDeviceAboutToStart (AudioIODevice* device);
  36074. /** @internal */
  36075. void audioDeviceStopped();
  36076. /** @internal */
  36077. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  36078. private:
  36079. AudioProcessor* processor;
  36080. CriticalSection lock;
  36081. double sampleRate;
  36082. int blockSize;
  36083. bool isPrepared;
  36084. int numInputChans, numOutputChans;
  36085. float* channels [128];
  36086. AudioSampleBuffer tempBuffer;
  36087. MidiBuffer incomingMidi;
  36088. MidiMessageCollector messageCollector;
  36089. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  36090. };
  36091. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  36092. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  36093. #endif
  36094. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36095. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  36096. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36097. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36098. /*** Start of inlined file: juce_PropertyPanel.h ***/
  36099. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  36100. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  36101. /*** Start of inlined file: juce_PropertyComponent.h ***/
  36102. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36103. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36104. class EditableProperty;
  36105. /**
  36106. A base class for a component that goes in a PropertyPanel and displays one of
  36107. an item's properties.
  36108. Subclasses of this are used to display a property in various forms, e.g. a
  36109. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  36110. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  36111. A subclass must implement the refresh() method which will be called to tell the
  36112. component to update itself, and is also responsible for calling this it when the
  36113. item that it refers to is changed.
  36114. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  36115. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  36116. */
  36117. class JUCE_API PropertyComponent : public Component,
  36118. public SettableTooltipClient
  36119. {
  36120. public:
  36121. /** Creates a PropertyComponent.
  36122. @param propertyName the name is stored as this component's name, and is
  36123. used as the name displayed next to this component in
  36124. a property panel
  36125. @param preferredHeight the height that the component should be given - some
  36126. items may need to be larger than a normal row height.
  36127. This value can also be set if a subclass changes the
  36128. preferredHeight member variable.
  36129. */
  36130. PropertyComponent (const String& propertyName,
  36131. int preferredHeight = 25);
  36132. /** Destructor. */
  36133. ~PropertyComponent();
  36134. /** Returns this item's preferred height.
  36135. This value is specified either in the constructor or by a subclass changing the
  36136. preferredHeight member variable.
  36137. */
  36138. int getPreferredHeight() const throw() { return preferredHeight; }
  36139. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  36140. /** Updates the property component if the item it refers to has changed.
  36141. A subclass must implement this method, and other objects may call it to
  36142. force it to refresh itself.
  36143. The subclass should be economical in the amount of work is done, so for
  36144. example it should check whether it really needs to do a repaint rather than
  36145. just doing one every time this method is called, as it may be called when
  36146. the value being displayed hasn't actually changed.
  36147. */
  36148. virtual void refresh() = 0;
  36149. /** The default paint method fills the background and draws a label for the
  36150. item's name.
  36151. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  36152. */
  36153. void paint (Graphics& g);
  36154. /** The default resize method positions any child component to the right of this
  36155. one, based on the look and feel's default label size.
  36156. */
  36157. void resized();
  36158. /** By default, this just repaints the component. */
  36159. void enablementChanged();
  36160. protected:
  36161. /** Used by the PropertyPanel to determine how high this component needs to be.
  36162. A subclass can update this value in its constructor but shouldn't alter it later
  36163. as changes won't necessarily be picked up.
  36164. */
  36165. int preferredHeight;
  36166. private:
  36167. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  36168. };
  36169. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  36170. /*** End of inlined file: juce_PropertyComponent.h ***/
  36171. /**
  36172. A panel that holds a list of PropertyComponent objects.
  36173. This panel displays a list of PropertyComponents, and allows them to be organised
  36174. into collapsible sections.
  36175. To use, simply create one of these and add your properties to it with addProperties()
  36176. or addSection().
  36177. @see PropertyComponent
  36178. */
  36179. class JUCE_API PropertyPanel : public Component
  36180. {
  36181. public:
  36182. /** Creates an empty property panel. */
  36183. PropertyPanel();
  36184. /** Destructor. */
  36185. ~PropertyPanel();
  36186. /** Deletes all property components from the panel.
  36187. */
  36188. void clear();
  36189. /** Adds a set of properties to the panel.
  36190. The components in the list will be owned by this object and will be automatically
  36191. deleted later on when no longer needed.
  36192. These properties are added without them being inside a named section. If you
  36193. want them to be kept together in a collapsible section, use addSection() instead.
  36194. */
  36195. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  36196. /** Adds a set of properties to the panel.
  36197. These properties are added at the bottom of the list, under a section heading with
  36198. a plus/minus button that allows it to be opened and closed.
  36199. The components in the list will be owned by this object and will be automatically
  36200. deleted later on when no longer needed.
  36201. To add properies without them being in a section, use addProperties().
  36202. */
  36203. void addSection (const String& sectionTitle,
  36204. const Array <PropertyComponent*>& newPropertyComponents,
  36205. bool shouldSectionInitiallyBeOpen = true);
  36206. /** Calls the refresh() method of all PropertyComponents in the panel */
  36207. void refreshAll() const;
  36208. /** Returns a list of all the names of sections in the panel.
  36209. These are the sections that have been added with addSection().
  36210. */
  36211. const StringArray getSectionNames() const;
  36212. /** Returns true if the section at this index is currently open.
  36213. The index is from 0 up to the number of items returned by getSectionNames().
  36214. */
  36215. bool isSectionOpen (int sectionIndex) const;
  36216. /** Opens or closes one of the sections.
  36217. The index is from 0 up to the number of items returned by getSectionNames().
  36218. */
  36219. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  36220. /** Enables or disables one of the sections.
  36221. The index is from 0 up to the number of items returned by getSectionNames().
  36222. */
  36223. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  36224. /** Saves the current state of open/closed sections so it can be restored later.
  36225. The caller is responsible for deleting the object that is returned.
  36226. To restore this state, use restoreOpennessState().
  36227. @see restoreOpennessState
  36228. */
  36229. XmlElement* getOpennessState() const;
  36230. /** Restores a previously saved arrangement of open/closed sections.
  36231. This will try to restore a snapshot of the panel's state that was created by
  36232. the getOpennessState() method. If any of the sections named in the original
  36233. XML aren't present, they will be ignored.
  36234. @see getOpennessState
  36235. */
  36236. void restoreOpennessState (const XmlElement& newState);
  36237. /** Sets a message to be displayed when there are no properties in the panel.
  36238. The default message is "nothing selected".
  36239. */
  36240. void setMessageWhenEmpty (const String& newMessage);
  36241. /** Returns the message that is displayed when there are no properties.
  36242. @see setMessageWhenEmpty
  36243. */
  36244. const String& getMessageWhenEmpty() const;
  36245. /** @internal */
  36246. void paint (Graphics& g);
  36247. /** @internal */
  36248. void resized();
  36249. private:
  36250. Viewport viewport;
  36251. class PropertyHolderComponent;
  36252. PropertyHolderComponent* propertyHolderComponent;
  36253. String messageWhenEmpty;
  36254. void updatePropHolderLayout() const;
  36255. void updatePropHolderLayout (int width) const;
  36256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  36257. };
  36258. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  36259. /*** End of inlined file: juce_PropertyPanel.h ***/
  36260. /**
  36261. A type of UI component that displays the parameters of an AudioProcessor as
  36262. a simple list of sliders.
  36263. This can be used for showing an editor for a processor that doesn't supply
  36264. its own custom editor.
  36265. @see AudioProcessor
  36266. */
  36267. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  36268. {
  36269. public:
  36270. GenericAudioProcessorEditor (AudioProcessor* owner);
  36271. ~GenericAudioProcessorEditor();
  36272. void paint (Graphics& g);
  36273. void resized();
  36274. private:
  36275. PropertyPanel panel;
  36276. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  36277. };
  36278. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  36279. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  36280. #endif
  36281. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  36282. /*** Start of inlined file: juce_Sampler.h ***/
  36283. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  36284. #define __JUCE_SAMPLER_JUCEHEADER__
  36285. /*** Start of inlined file: juce_Synthesiser.h ***/
  36286. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36287. #define __JUCE_SYNTHESISER_JUCEHEADER__
  36288. /**
  36289. Describes one of the sounds that a Synthesiser can play.
  36290. A synthesiser can contain one or more sounds, and a sound can choose which
  36291. midi notes and channels can trigger it.
  36292. The SynthesiserSound is a passive class that just describes what the sound is -
  36293. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  36294. more than one SynthesiserVoice to play the same sound at the same time.
  36295. @see Synthesiser, SynthesiserVoice
  36296. */
  36297. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  36298. {
  36299. protected:
  36300. SynthesiserSound();
  36301. public:
  36302. /** Destructor. */
  36303. virtual ~SynthesiserSound();
  36304. /** Returns true if this sound should be played when a given midi note is pressed.
  36305. The Synthesiser will use this information when deciding which sounds to trigger
  36306. for a given note.
  36307. */
  36308. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  36309. /** Returns true if the sound should be triggered by midi events on a given channel.
  36310. The Synthesiser will use this information when deciding which sounds to trigger
  36311. for a given note.
  36312. */
  36313. virtual bool appliesToChannel (const int midiChannel) = 0;
  36314. /**
  36315. */
  36316. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  36317. private:
  36318. JUCE_LEAK_DETECTOR (SynthesiserSound);
  36319. };
  36320. /**
  36321. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  36322. A voice plays a single sound at a time, and a synthesiser holds an array of
  36323. voices so that it can play polyphonically.
  36324. @see Synthesiser, SynthesiserSound
  36325. */
  36326. class JUCE_API SynthesiserVoice
  36327. {
  36328. public:
  36329. /** Creates a voice. */
  36330. SynthesiserVoice();
  36331. /** Destructor. */
  36332. virtual ~SynthesiserVoice();
  36333. /** Returns the midi note that this voice is currently playing.
  36334. Returns a value less than 0 if no note is playing.
  36335. */
  36336. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  36337. /** Returns the sound that this voice is currently playing.
  36338. Returns 0 if it's not playing.
  36339. */
  36340. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  36341. /** Must return true if this voice object is capable of playing the given sound.
  36342. If there are different classes of sound, and different classes of voice, a voice can
  36343. choose which ones it wants to take on.
  36344. A typical implementation of this method may just return true if there's only one type
  36345. of voice and sound, or it might check the type of the sound object passed-in and
  36346. see if it's one that it understands.
  36347. */
  36348. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  36349. /** Called to start a new note.
  36350. This will be called during the rendering callback, so must be fast and thread-safe.
  36351. */
  36352. virtual void startNote (const int midiNoteNumber,
  36353. const float velocity,
  36354. SynthesiserSound* sound,
  36355. const int currentPitchWheelPosition) = 0;
  36356. /** Called to stop a note.
  36357. This will be called during the rendering callback, so must be fast and thread-safe.
  36358. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  36359. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  36360. and allow the synth to reassign it another sound.
  36361. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  36362. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  36363. finishes playing (during the rendering callback), it must make sure that it calls
  36364. clearCurrentNote().
  36365. */
  36366. virtual void stopNote (const bool allowTailOff) = 0;
  36367. /** Called to let the voice know that the pitch wheel has been moved.
  36368. This will be called during the rendering callback, so must be fast and thread-safe.
  36369. */
  36370. virtual void pitchWheelMoved (const int newValue) = 0;
  36371. /** Called to let the voice know that a midi controller has been moved.
  36372. This will be called during the rendering callback, so must be fast and thread-safe.
  36373. */
  36374. virtual void controllerMoved (const int controllerNumber,
  36375. const int newValue) = 0;
  36376. /** Renders the next block of data for this voice.
  36377. The output audio data must be added to the current contents of the buffer provided.
  36378. Only the region of the buffer between startSample and (startSample + numSamples)
  36379. should be altered by this method.
  36380. If the voice is currently silent, it should just return without doing anything.
  36381. If the sound that the voice is playing finishes during the course of this rendered
  36382. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  36383. The size of the blocks that are rendered can change each time it is called, and may
  36384. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  36385. the voice's methods will be called to tell it about note and controller events.
  36386. */
  36387. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  36388. int startSample,
  36389. int numSamples) = 0;
  36390. /** Returns true if the voice is currently playing a sound which is mapped to the given
  36391. midi channel.
  36392. If it's not currently playing, this will return false.
  36393. */
  36394. bool isPlayingChannel (int midiChannel) const;
  36395. /** Changes the voice's reference sample rate.
  36396. The rate is set so that subclasses know the output rate and can set their pitch
  36397. accordingly.
  36398. This method is called by the synth, and subclasses can access the current rate with
  36399. the currentSampleRate member.
  36400. */
  36401. void setCurrentPlaybackSampleRate (double newRate);
  36402. protected:
  36403. /** Returns the current target sample rate at which rendering is being done.
  36404. This is available for subclasses so they can pitch things correctly.
  36405. */
  36406. double getSampleRate() const { return currentSampleRate; }
  36407. /** Resets the state of this voice after a sound has finished playing.
  36408. The subclass must call this when it finishes playing a note and becomes available
  36409. to play new ones.
  36410. It must either call it in the stopNote() method, or if the voice is tailing off,
  36411. then it should call it later during the renderNextBlock method, as soon as it
  36412. finishes its tail-off.
  36413. It can also be called at any time during the render callback if the sound happens
  36414. to have finished, e.g. if it's playing a sample and the sample finishes.
  36415. */
  36416. void clearCurrentNote();
  36417. private:
  36418. friend class Synthesiser;
  36419. double currentSampleRate;
  36420. int currentlyPlayingNote;
  36421. uint32 noteOnTime;
  36422. SynthesiserSound::Ptr currentlyPlayingSound;
  36423. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  36424. };
  36425. /**
  36426. Base class for a musical device that can play sounds.
  36427. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  36428. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  36429. which can play back one of these sounds.
  36430. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  36431. set of sounds, and a set of voices it can use to play them. If you only give it
  36432. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  36433. have available.
  36434. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  36435. events that go in will be scanned for note on/off messages, and these are used to
  36436. start and stop the voices playing the appropriate sounds.
  36437. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  36438. noteOff() and other controller methods.
  36439. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  36440. what the target playback rate is. This value is passed on to the voices so that
  36441. they can pitch their output correctly.
  36442. */
  36443. class JUCE_API Synthesiser
  36444. {
  36445. public:
  36446. /** Creates a new synthesiser.
  36447. You'll need to add some sounds and voices before it'll make any sound..
  36448. */
  36449. Synthesiser();
  36450. /** Destructor. */
  36451. virtual ~Synthesiser();
  36452. /** Deletes all voices. */
  36453. void clearVoices();
  36454. /** Returns the number of voices that have been added. */
  36455. int getNumVoices() const { return voices.size(); }
  36456. /** Returns one of the voices that have been added. */
  36457. SynthesiserVoice* getVoice (int index) const;
  36458. /** Adds a new voice to the synth.
  36459. All the voices should be the same class of object and are treated equally.
  36460. The object passed in will be managed by the synthesiser, which will delete
  36461. it later on when no longer needed. The caller should not retain a pointer to the
  36462. voice.
  36463. */
  36464. void addVoice (SynthesiserVoice* newVoice);
  36465. /** Deletes one of the voices. */
  36466. void removeVoice (int index);
  36467. /** Deletes all sounds. */
  36468. void clearSounds();
  36469. /** Returns the number of sounds that have been added to the synth. */
  36470. int getNumSounds() const { return sounds.size(); }
  36471. /** Returns one of the sounds. */
  36472. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  36473. /** Adds a new sound to the synthesiser.
  36474. The object passed in is reference counted, so will be deleted when it is removed
  36475. from the synthesiser, and when no voices are still using it.
  36476. */
  36477. void addSound (const SynthesiserSound::Ptr& newSound);
  36478. /** Removes and deletes one of the sounds. */
  36479. void removeSound (int index);
  36480. /** If set to true, then the synth will try to take over an existing voice if
  36481. it runs out and needs to play another note.
  36482. The value of this boolean is passed into findFreeVoice(), so the result will
  36483. depend on the implementation of this method.
  36484. */
  36485. void setNoteStealingEnabled (bool shouldStealNotes);
  36486. /** Returns true if note-stealing is enabled.
  36487. @see setNoteStealingEnabled
  36488. */
  36489. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  36490. /** Triggers a note-on event.
  36491. The default method here will find all the sounds that want to be triggered by
  36492. this note/channel. For each sound, it'll try to find a free voice, and use the
  36493. voice to start playing the sound.
  36494. Subclasses might want to override this if they need a more complex algorithm.
  36495. This method will be called automatically according to the midi data passed into
  36496. renderNextBlock(), but may be called explicitly too.
  36497. */
  36498. virtual void noteOn (int midiChannel,
  36499. int midiNoteNumber,
  36500. float velocity);
  36501. /** Triggers a note-off event.
  36502. This will turn off any voices that are playing a sound for the given note/channel.
  36503. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36504. (if they can do). If this is false, the notes will all be cut off immediately.
  36505. This method will be called automatically according to the midi data passed into
  36506. renderNextBlock(), but may be called explicitly too.
  36507. */
  36508. virtual void noteOff (int midiChannel,
  36509. int midiNoteNumber,
  36510. bool allowTailOff);
  36511. /** Turns off all notes.
  36512. This will turn off any voices that are playing a sound on the given midi channel.
  36513. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  36514. which channel they're playing.
  36515. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36516. (if they can do). If this is false, the notes will all be cut off immediately.
  36517. This method will be called automatically according to the midi data passed into
  36518. renderNextBlock(), but may be called explicitly too.
  36519. */
  36520. virtual void allNotesOff (int midiChannel,
  36521. bool allowTailOff);
  36522. /** Sends a pitch-wheel message.
  36523. This will send a pitch-wheel message to any voices that are playing sounds on
  36524. the given midi channel.
  36525. This method will be called automatically according to the midi data passed into
  36526. renderNextBlock(), but may be called explicitly too.
  36527. @param midiChannel the midi channel for the event
  36528. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  36529. */
  36530. virtual void handlePitchWheel (int midiChannel,
  36531. int wheelValue);
  36532. /** Sends a midi controller message.
  36533. This will send a midi controller message to any voices that are playing sounds on
  36534. the given midi channel.
  36535. This method will be called automatically according to the midi data passed into
  36536. renderNextBlock(), but may be called explicitly too.
  36537. @param midiChannel the midi channel for the event
  36538. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  36539. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  36540. */
  36541. virtual void handleController (int midiChannel,
  36542. int controllerNumber,
  36543. int controllerValue);
  36544. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  36545. render.
  36546. This value is propagated to the voices so that they can use it to render the correct
  36547. pitches.
  36548. */
  36549. void setCurrentPlaybackSampleRate (double sampleRate);
  36550. /** Creates the next block of audio output.
  36551. This will process the next numSamples of data from all the voices, and add that output
  36552. to the audio block supplied, starting from the offset specified. Note that the
  36553. data will be added to the current contents of the buffer, so you should clear it
  36554. before calling this method if necessary.
  36555. The midi events in the inputMidi buffer are parsed for note and controller events,
  36556. and these are used to trigger the voices. Note that the startSample offset applies
  36557. both to the audio output buffer and the midi input buffer, so any midi events
  36558. with timestamps outside the specified region will be ignored.
  36559. */
  36560. void renderNextBlock (AudioSampleBuffer& outputAudio,
  36561. const MidiBuffer& inputMidi,
  36562. int startSample,
  36563. int numSamples);
  36564. protected:
  36565. /** This is used to control access to the rendering callback and the note trigger methods. */
  36566. CriticalSection lock;
  36567. OwnedArray <SynthesiserVoice> voices;
  36568. ReferenceCountedArray <SynthesiserSound> sounds;
  36569. /** The last pitch-wheel values for each midi channel. */
  36570. int lastPitchWheelValues [16];
  36571. /** Searches through the voices to find one that's not currently playing, and which
  36572. can play the given sound.
  36573. Returns 0 if all voices are busy and stealing isn't enabled.
  36574. This can be overridden to implement custom voice-stealing algorithms.
  36575. */
  36576. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  36577. const bool stealIfNoneAvailable) const;
  36578. /** Starts a specified voice playing a particular sound.
  36579. You'll probably never need to call this, it's used internally by noteOn(), but
  36580. may be needed by subclasses for custom behaviours.
  36581. */
  36582. void startVoice (SynthesiserVoice* voice,
  36583. SynthesiserSound* sound,
  36584. int midiChannel,
  36585. int midiNoteNumber,
  36586. float velocity);
  36587. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  36588. // Temporary method here to cause a compiler error - note the new parameters for this method.
  36589. int findFreeVoice (const bool) const { return 0; }
  36590. #endif
  36591. private:
  36592. double sampleRate;
  36593. uint32 lastNoteOnCounter;
  36594. bool shouldStealNotes;
  36595. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  36596. };
  36597. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  36598. /*** End of inlined file: juce_Synthesiser.h ***/
  36599. /**
  36600. A subclass of SynthesiserSound that represents a sampled audio clip.
  36601. This is a pretty basic sampler, and just attempts to load the whole audio stream
  36602. into memory.
  36603. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36604. give it some SampledSound objects to play.
  36605. @see SamplerVoice, Synthesiser, SynthesiserSound
  36606. */
  36607. class JUCE_API SamplerSound : public SynthesiserSound
  36608. {
  36609. public:
  36610. /** Creates a sampled sound from an audio reader.
  36611. This will attempt to load the audio from the source into memory and store
  36612. it in this object.
  36613. @param name a name for the sample
  36614. @param source the audio to load. This object can be safely deleted by the
  36615. caller after this constructor returns
  36616. @param midiNotes the set of midi keys that this sound should be played on. This
  36617. is used by the SynthesiserSound::appliesToNote() method
  36618. @param midiNoteForNormalPitch the midi note at which the sample should be played
  36619. with its natural rate. All other notes will be pitched
  36620. up or down relative to this one
  36621. @param attackTimeSecs the attack (fade-in) time, in seconds
  36622. @param releaseTimeSecs the decay (fade-out) time, in seconds
  36623. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  36624. source, in seconds
  36625. */
  36626. SamplerSound (const String& name,
  36627. AudioFormatReader& source,
  36628. const BigInteger& midiNotes,
  36629. int midiNoteForNormalPitch,
  36630. double attackTimeSecs,
  36631. double releaseTimeSecs,
  36632. double maxSampleLengthSeconds);
  36633. /** Destructor. */
  36634. ~SamplerSound();
  36635. /** Returns the sample's name */
  36636. const String& getName() const { return name; }
  36637. /** Returns the audio sample data.
  36638. This could be 0 if there was a problem loading it.
  36639. */
  36640. AudioSampleBuffer* getAudioData() const { return data; }
  36641. bool appliesToNote (const int midiNoteNumber);
  36642. bool appliesToChannel (const int midiChannel);
  36643. private:
  36644. friend class SamplerVoice;
  36645. String name;
  36646. ScopedPointer <AudioSampleBuffer> data;
  36647. double sourceSampleRate;
  36648. BigInteger midiNotes;
  36649. int length, attackSamples, releaseSamples;
  36650. int midiRootNote;
  36651. JUCE_LEAK_DETECTOR (SamplerSound);
  36652. };
  36653. /**
  36654. A subclass of SynthesiserVoice that can play a SamplerSound.
  36655. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36656. give it some SampledSound objects to play.
  36657. @see SamplerSound, Synthesiser, SynthesiserVoice
  36658. */
  36659. class JUCE_API SamplerVoice : public SynthesiserVoice
  36660. {
  36661. public:
  36662. /** Creates a SamplerVoice.
  36663. */
  36664. SamplerVoice();
  36665. /** Destructor. */
  36666. ~SamplerVoice();
  36667. bool canPlaySound (SynthesiserSound* sound);
  36668. void startNote (const int midiNoteNumber,
  36669. const float velocity,
  36670. SynthesiserSound* sound,
  36671. const int currentPitchWheelPosition);
  36672. void stopNote (const bool allowTailOff);
  36673. void pitchWheelMoved (const int newValue);
  36674. void controllerMoved (const int controllerNumber,
  36675. const int newValue);
  36676. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  36677. private:
  36678. double pitchRatio;
  36679. double sourceSamplePosition;
  36680. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  36681. bool isInAttack, isInRelease;
  36682. JUCE_LEAK_DETECTOR (SamplerVoice);
  36683. };
  36684. #endif // __JUCE_SAMPLER_JUCEHEADER__
  36685. /*** End of inlined file: juce_Sampler.h ***/
  36686. #endif
  36687. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36688. #endif
  36689. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36690. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  36691. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36692. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36693. /** Manages a list of ActionListeners, and can send them messages.
  36694. To quickly add methods to your class that can add/remove action
  36695. listeners and broadcast to them, you can derive from this.
  36696. @see ActionListener, ChangeListener
  36697. */
  36698. class JUCE_API ActionBroadcaster
  36699. {
  36700. public:
  36701. /** Creates an ActionBroadcaster. */
  36702. ActionBroadcaster();
  36703. /** Destructor. */
  36704. virtual ~ActionBroadcaster();
  36705. /** Adds a listener to the list.
  36706. Trying to add a listener that's already on the list will have no effect.
  36707. */
  36708. void addActionListener (ActionListener* listener);
  36709. /** Removes a listener from the list.
  36710. If the listener isn't on the list, this won't have any effect.
  36711. */
  36712. void removeActionListener (ActionListener* listener);
  36713. /** Removes all listeners from the list. */
  36714. void removeAllActionListeners();
  36715. /** Broadcasts a message to all the registered listeners.
  36716. @see ActionListener::actionListenerCallback
  36717. */
  36718. void sendActionMessage (const String& message) const;
  36719. private:
  36720. class CallbackReceiver : public MessageListener
  36721. {
  36722. public:
  36723. CallbackReceiver();
  36724. void handleMessage (const Message&);
  36725. ActionBroadcaster* owner;
  36726. };
  36727. friend class CallbackReceiver;
  36728. CallbackReceiver callback;
  36729. SortedSet <ActionListener*> actionListeners;
  36730. CriticalSection actionListenerLock;
  36731. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  36732. };
  36733. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36734. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  36735. #endif
  36736. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  36737. #endif
  36738. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  36739. #endif
  36740. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  36741. #endif
  36742. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  36743. #endif
  36744. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  36745. #endif
  36746. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36747. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  36748. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36749. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36750. class InterprocessConnectionServer;
  36751. /**
  36752. Manages a simple two-way messaging connection to another process, using either
  36753. a socket or a named pipe as the transport medium.
  36754. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  36755. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  36756. and incoming messages will result in a callback via the messageReceived()
  36757. method.
  36758. To open a pipe and wait for another client to connect to it, use the createPipe()
  36759. method.
  36760. To act as a socket server and create connections for one or more client, see the
  36761. InterprocessConnectionServer class.
  36762. @see InterprocessConnectionServer, Socket, NamedPipe
  36763. */
  36764. class JUCE_API InterprocessConnection : public Thread,
  36765. private MessageListener
  36766. {
  36767. public:
  36768. /** Creates a connection.
  36769. Connections are created manually, connecting them with the connectToSocket()
  36770. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  36771. when a client wants to connect.
  36772. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  36773. connectionLost() and messageReceived() methods will
  36774. always be made using the message thread; if false,
  36775. these will be called immediately on the connection's
  36776. own thread.
  36777. @param magicMessageHeaderNumber a magic number to use in the header to check the
  36778. validity of the data blocks being sent and received. This
  36779. can be any number, but the sender and receiver must obviously
  36780. use matching values or they won't recognise each other.
  36781. */
  36782. InterprocessConnection (bool callbacksOnMessageThread = true,
  36783. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  36784. /** Destructor. */
  36785. ~InterprocessConnection();
  36786. /** Tries to connect this object to a socket.
  36787. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  36788. object waiting to receive client connections on this port number.
  36789. @param hostName the host computer, either a network address or name
  36790. @param portNumber the socket port number to try to connect to
  36791. @param timeOutMillisecs how long to keep trying before giving up
  36792. @returns true if the connection is established successfully
  36793. @see Socket
  36794. */
  36795. bool connectToSocket (const String& hostName,
  36796. int portNumber,
  36797. int timeOutMillisecs);
  36798. /** Tries to connect the object to an existing named pipe.
  36799. For this to work, another process on the same computer must already have opened
  36800. an InterprocessConnection object and used createPipe() to create a pipe for this
  36801. to connect to.
  36802. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36803. @returns true if it connects successfully.
  36804. @see createPipe, NamedPipe
  36805. */
  36806. bool connectToPipe (const String& pipeName,
  36807. int pipeReceiveMessageTimeoutMs = -1);
  36808. /** Tries to create a new pipe for other processes to connect to.
  36809. This creates a pipe with the given name, so that other processes can use
  36810. connectToPipe() to connect to the other end.
  36811. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36812. If another process is already using this pipe, this will fail and return false.
  36813. */
  36814. bool createPipe (const String& pipeName,
  36815. int pipeReceiveMessageTimeoutMs = -1);
  36816. /** Disconnects and closes any currently-open sockets or pipes. */
  36817. void disconnect();
  36818. /** True if a socket or pipe is currently active. */
  36819. bool isConnected() const;
  36820. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  36821. StreamingSocket* getSocket() const throw() { return socket; }
  36822. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  36823. NamedPipe* getPipe() const throw() { return pipe; }
  36824. /** Returns the name of the machine at the other end of this connection.
  36825. This will return an empty string if the other machine isn't known for
  36826. some reason.
  36827. */
  36828. const String getConnectedHostName() const;
  36829. /** Tries to send a message to the other end of this connection.
  36830. This will fail if it's not connected, or if there's some kind of write error. If
  36831. it succeeds, the connection object at the other end will receive the message by
  36832. a callback to its messageReceived() method.
  36833. @see messageReceived
  36834. */
  36835. bool sendMessage (const MemoryBlock& message);
  36836. /** Called when the connection is first connected.
  36837. If the connection was created with the callbacksOnMessageThread flag set, then
  36838. this will be called on the message thread; otherwise it will be called on a server
  36839. thread.
  36840. */
  36841. virtual void connectionMade() = 0;
  36842. /** Called when the connection is broken.
  36843. If the connection was created with the callbacksOnMessageThread flag set, then
  36844. this will be called on the message thread; otherwise it will be called on a server
  36845. thread.
  36846. */
  36847. virtual void connectionLost() = 0;
  36848. /** Called when a message arrives.
  36849. When the object at the other end of this connection sends us a message with sendMessage(),
  36850. this callback is used to deliver it to us.
  36851. If the connection was created with the callbacksOnMessageThread flag set, then
  36852. this will be called on the message thread; otherwise it will be called on a server
  36853. thread.
  36854. @see sendMessage
  36855. */
  36856. virtual void messageReceived (const MemoryBlock& message) = 0;
  36857. private:
  36858. CriticalSection pipeAndSocketLock;
  36859. ScopedPointer <StreamingSocket> socket;
  36860. ScopedPointer <NamedPipe> pipe;
  36861. bool callbackConnectionState;
  36862. const bool useMessageThread;
  36863. const uint32 magicMessageHeader;
  36864. int pipeReceiveMessageTimeout;
  36865. friend class InterprocessConnectionServer;
  36866. void initialiseWithSocket (StreamingSocket* socket_);
  36867. void initialiseWithPipe (NamedPipe* pipe_);
  36868. void handleMessage (const Message& message);
  36869. void connectionMadeInt();
  36870. void connectionLostInt();
  36871. void deliverDataInt (const MemoryBlock& data);
  36872. bool readNextMessageInt();
  36873. void run();
  36874. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  36875. };
  36876. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36877. /*** End of inlined file: juce_InterprocessConnection.h ***/
  36878. #endif
  36879. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36880. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  36881. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36882. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36883. /**
  36884. An object that waits for client sockets to connect to a port on this host, and
  36885. creates InterprocessConnection objects for each one.
  36886. To use this, create a class derived from it which implements the createConnectionObject()
  36887. method, so that it creates suitable connection objects for each client that tries
  36888. to connect.
  36889. @see InterprocessConnection
  36890. */
  36891. class JUCE_API InterprocessConnectionServer : private Thread
  36892. {
  36893. public:
  36894. /** Creates an uninitialised server object.
  36895. */
  36896. InterprocessConnectionServer();
  36897. /** Destructor. */
  36898. ~InterprocessConnectionServer();
  36899. /** Starts an internal thread which listens on the given port number.
  36900. While this is running, in another process tries to connect with the
  36901. InterprocessConnection::connectToSocket() method, this object will call
  36902. createConnectionObject() to create a connection to that client.
  36903. Use stop() to stop the thread running.
  36904. @see createConnectionObject, stop
  36905. */
  36906. bool beginWaitingForSocket (int portNumber);
  36907. /** Terminates the listener thread, if it's active.
  36908. @see beginWaitingForSocket
  36909. */
  36910. void stop();
  36911. protected:
  36912. /** Creates a suitable connection object for a client process that wants to
  36913. connect to this one.
  36914. This will be called by the listener thread when a client process tries
  36915. to connect, and must return a new InterprocessConnection object that will
  36916. then run as this end of the connection.
  36917. @see InterprocessConnection
  36918. */
  36919. virtual InterprocessConnection* createConnectionObject() = 0;
  36920. private:
  36921. ScopedPointer <StreamingSocket> socket;
  36922. void run();
  36923. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  36924. };
  36925. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36926. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  36927. #endif
  36928. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  36929. #endif
  36930. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  36931. #endif
  36932. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  36933. #endif
  36934. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36935. /*** Start of inlined file: juce_MessageManager.h ***/
  36936. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36937. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36938. class Component;
  36939. class MessageManagerLock;
  36940. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  36941. */
  36942. typedef void* (MessageCallbackFunction) (void* userData);
  36943. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  36944. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  36945. */
  36946. class JUCE_API MessageManager
  36947. {
  36948. public:
  36949. /** Returns the global instance of the MessageManager. */
  36950. static MessageManager* getInstance() throw();
  36951. /** Runs the event dispatch loop until a stop message is posted.
  36952. This method is only intended to be run by the application's startup routine,
  36953. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  36954. @see stopDispatchLoop
  36955. */
  36956. void runDispatchLoop();
  36957. /** Sends a signal that the dispatch loop should terminate.
  36958. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  36959. will be interrupted and will return.
  36960. @see runDispatchLoop
  36961. */
  36962. void stopDispatchLoop();
  36963. /** Returns true if the stopDispatchLoop() method has been called.
  36964. */
  36965. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  36966. #if JUCE_MODAL_LOOPS_PERMITTED
  36967. /** Synchronously dispatches messages until a given time has elapsed.
  36968. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  36969. otherwise returns true.
  36970. */
  36971. bool runDispatchLoopUntil (int millisecondsToRunFor);
  36972. #endif
  36973. /** Calls a function using the message-thread.
  36974. This can be used by any thread to cause this function to be called-back
  36975. by the message thread. If it's the message-thread that's calling this method,
  36976. then the function will just be called; if another thread is calling, a message
  36977. will be posted to the queue, and this method will block until that message
  36978. is delivered, the function is called, and the result is returned.
  36979. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  36980. thread has a critical section locked, which an unrelated message callback then tries to lock
  36981. before the message thread gets round to processing this callback.
  36982. @param callback the function to call - its signature must be @code
  36983. void* myCallbackFunction (void*) @endcode
  36984. @param userData a user-defined pointer that will be passed to the function that gets called
  36985. @returns the value that the callback function returns.
  36986. @see MessageManagerLock
  36987. */
  36988. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  36989. void* userData);
  36990. /** Returns true if the caller-thread is the message thread. */
  36991. bool isThisTheMessageThread() const throw();
  36992. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  36993. (Best to ignore this method unless you really know what you're doing..)
  36994. @see getCurrentMessageThread
  36995. */
  36996. void setCurrentThreadAsMessageThread();
  36997. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  36998. (Best to ignore this method unless you really know what you're doing..)
  36999. @see setCurrentMessageThread
  37000. */
  37001. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  37002. /** Returns true if the caller thread has currenltly got the message manager locked.
  37003. see the MessageManagerLock class for more info about this.
  37004. This will be true if the caller is the message thread, because that automatically
  37005. gains a lock while a message is being dispatched.
  37006. */
  37007. bool currentThreadHasLockedMessageManager() const throw();
  37008. /** Sends a message to all other JUCE applications that are running.
  37009. @param messageText the string that will be passed to the actionListenerCallback()
  37010. method of the broadcast listeners in the other app.
  37011. @see registerBroadcastListener, ActionListener
  37012. */
  37013. static void broadcastMessage (const String& messageText);
  37014. /** Registers a listener to get told about broadcast messages.
  37015. The actionListenerCallback() callback's string parameter
  37016. is the message passed into broadcastMessage().
  37017. @see broadcastMessage
  37018. */
  37019. void registerBroadcastListener (ActionListener* listener);
  37020. /** Deregisters a broadcast listener. */
  37021. void deregisterBroadcastListener (ActionListener* listener);
  37022. /** @internal */
  37023. void deliverMessage (Message*);
  37024. /** @internal */
  37025. void deliverBroadcastMessage (const String&);
  37026. /** @internal */
  37027. ~MessageManager() throw();
  37028. private:
  37029. MessageManager() throw();
  37030. friend class MessageListener;
  37031. friend class ChangeBroadcaster;
  37032. friend class ActionBroadcaster;
  37033. friend class CallbackMessage;
  37034. static MessageManager* instance;
  37035. SortedSet <const MessageListener*> messageListeners;
  37036. ScopedPointer <ActionBroadcaster> broadcaster;
  37037. friend class JUCEApplication;
  37038. bool quitMessagePosted, quitMessageReceived;
  37039. Thread::ThreadID messageThreadId;
  37040. friend class MessageManagerLock;
  37041. Thread::ThreadID volatile threadWithLock;
  37042. CriticalSection lockingLock;
  37043. void postMessageToQueue (Message* message);
  37044. static bool postMessageToSystemQueue (Message*);
  37045. static void* exitModalLoopCallback (void*);
  37046. static void doPlatformSpecificInitialisation();
  37047. static void doPlatformSpecificShutdown();
  37048. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  37049. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  37050. };
  37051. /** Used to make sure that the calling thread has exclusive access to the message loop.
  37052. Because it's not thread-safe to call any of the Component or other UI classes
  37053. from threads other than the message thread, one of these objects can be used to
  37054. lock the message loop and allow this to be done. The message thread will be
  37055. suspended for the lifetime of the MessageManagerLock object, so create one on
  37056. the stack like this: @code
  37057. void MyThread::run()
  37058. {
  37059. someData = 1234;
  37060. const MessageManagerLock mmLock;
  37061. // the event loop will now be locked so it's safe to make a few calls..
  37062. myComponent->setBounds (newBounds);
  37063. myComponent->repaint();
  37064. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  37065. }
  37066. @endcode
  37067. Obviously be careful not to create one of these and leave it lying around, or
  37068. your app will grind to a halt!
  37069. Another caveat is that using this in conjunction with other CriticalSections
  37070. can create lots of interesting ways of producing a deadlock! In particular, if
  37071. your message thread calls stopThread() for a thread that uses these locks,
  37072. you'll get an (occasional) deadlock..
  37073. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  37074. */
  37075. class JUCE_API MessageManagerLock
  37076. {
  37077. public:
  37078. /** Tries to acquire a lock on the message manager.
  37079. The constructor attempts to gain a lock on the message loop, and the lock will be
  37080. kept for the lifetime of this object.
  37081. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  37082. this method will keep checking whether the thread has been given the
  37083. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  37084. without gaining the lock. If you pass a thread, you must check whether the lock was
  37085. successful by calling lockWasGained(). If this is false, your thread is being told to
  37086. die, so you should take evasive action.
  37087. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  37088. careful when doing this, because it's very easy to deadlock if your message thread
  37089. attempts to call stopThread() on a thread just as that thread attempts to get the
  37090. message lock.
  37091. If the calling thread already has the lock, nothing will be done, so it's safe and
  37092. quick to use these locks recursively.
  37093. E.g.
  37094. @code
  37095. void run()
  37096. {
  37097. ...
  37098. while (! threadShouldExit())
  37099. {
  37100. MessageManagerLock mml (Thread::getCurrentThread());
  37101. if (! mml.lockWasGained())
  37102. return; // another thread is trying to kill us!
  37103. ..do some locked stuff here..
  37104. }
  37105. ..and now the MM is now unlocked..
  37106. }
  37107. @endcode
  37108. */
  37109. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  37110. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  37111. instead of a thread.
  37112. See the MessageManagerLock (Thread*) constructor for details on how this works.
  37113. */
  37114. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  37115. /** Releases the current thread's lock on the message manager.
  37116. Make sure this object is created and deleted by the same thread,
  37117. otherwise there are no guarantees what will happen!
  37118. */
  37119. ~MessageManagerLock() throw();
  37120. /** Returns true if the lock was successfully acquired.
  37121. (See the constructor that takes a Thread for more info).
  37122. */
  37123. bool lockWasGained() const throw() { return locked; }
  37124. private:
  37125. class BlockingMessage;
  37126. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  37127. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  37128. bool locked;
  37129. void init (Thread* thread, ThreadPoolJob* job);
  37130. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  37131. };
  37132. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  37133. /*** End of inlined file: juce_MessageManager.h ***/
  37134. #endif
  37135. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  37136. /*** Start of inlined file: juce_MultiTimer.h ***/
  37137. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  37138. #define __JUCE_MULTITIMER_JUCEHEADER__
  37139. /**
  37140. A type of timer class that can run multiple timers with different frequencies,
  37141. all of which share a single callback.
  37142. This class is very similar to the Timer class, but allows you run multiple
  37143. separate timers, where each one has a unique ID number. The methods in this
  37144. class are exactly equivalent to those in Timer, but with the addition of
  37145. this ID number.
  37146. To use it, you need to create a subclass of MultiTimer, implementing the
  37147. timerCallback() method. Then you can start timers with startTimer(), and
  37148. each time the callback is triggered, it passes in the ID of the timer that
  37149. caused it.
  37150. @see Timer
  37151. */
  37152. class JUCE_API MultiTimer
  37153. {
  37154. protected:
  37155. /** Creates a MultiTimer.
  37156. When created, no timers are running, so use startTimer() to start things off.
  37157. */
  37158. MultiTimer() throw();
  37159. /** Creates a copy of another timer.
  37160. Note that this timer will not contain any running timers, even if the one you're
  37161. copying from was running.
  37162. */
  37163. MultiTimer (const MultiTimer& other) throw();
  37164. public:
  37165. /** Destructor. */
  37166. virtual ~MultiTimer();
  37167. /** The user-defined callback routine that actually gets called by each of the
  37168. timers that are running.
  37169. It's perfectly ok to call startTimer() or stopTimer() from within this
  37170. callback to change the subsequent intervals.
  37171. */
  37172. virtual void timerCallback (int timerId) = 0;
  37173. /** Starts a timer and sets the length of interval required.
  37174. If the timer is already started, this will reset it, so the
  37175. time between calling this method and the next timer callback
  37176. will not be less than the interval length passed in.
  37177. @param timerId a unique Id number that identifies the timer to
  37178. start. This is the id that will be passed back
  37179. to the timerCallback() method when this timer is
  37180. triggered
  37181. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  37182. rounded up to 1)
  37183. */
  37184. void startTimer (int timerId, int intervalInMilliseconds) throw();
  37185. /** Stops a timer.
  37186. If a timer has been started with the given ID number, it will be cancelled.
  37187. No more callbacks will be made for the specified timer after this method returns.
  37188. If this is called from a different thread, any callbacks that may
  37189. be currently executing may be allowed to finish before the method
  37190. returns.
  37191. */
  37192. void stopTimer (int timerId) throw();
  37193. /** Checks whether a timer has been started for a specified ID.
  37194. @returns true if a timer with the given ID is running.
  37195. */
  37196. bool isTimerRunning (int timerId) const throw();
  37197. /** Returns the interval for a specified timer ID.
  37198. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  37199. is running for the ID number specified.
  37200. */
  37201. int getTimerInterval (int timerId) const throw();
  37202. private:
  37203. class MultiTimerCallback;
  37204. SpinLock timerListLock;
  37205. OwnedArray <MultiTimerCallback> timers;
  37206. MultiTimer& operator= (const MultiTimer&);
  37207. };
  37208. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  37209. /*** End of inlined file: juce_MultiTimer.h ***/
  37210. #endif
  37211. #ifndef __JUCE_TIMER_JUCEHEADER__
  37212. #endif
  37213. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  37214. /*** Start of inlined file: juce_ArrowButton.h ***/
  37215. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  37216. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  37217. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  37218. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37219. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37220. /**
  37221. An effect filter that adds a drop-shadow behind the image's content.
  37222. (This will only work on images/components that aren't opaque, of course).
  37223. When added to a component, this effect will draw a soft-edged
  37224. shadow based on what gets drawn inside it. The shadow will also
  37225. be applied to the component's children.
  37226. For speed, this doesn't use a proper gaussian blur, but cheats by
  37227. using a simple bilinear filter. If you need a really high-quality
  37228. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  37229. @see Component::setComponentEffect
  37230. */
  37231. class JUCE_API DropShadowEffect : public ImageEffectFilter
  37232. {
  37233. public:
  37234. /** Creates a default drop-shadow effect.
  37235. To customise the shadow's appearance, use the setShadowProperties()
  37236. method.
  37237. */
  37238. DropShadowEffect();
  37239. /** Destructor. */
  37240. ~DropShadowEffect();
  37241. /** Sets up parameters affecting the shadow's appearance.
  37242. @param newRadius the (approximate) radius of the blur used
  37243. @param newOpacity the opacity with which the shadow is rendered
  37244. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  37245. component's contents
  37246. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  37247. component's contents
  37248. */
  37249. void setShadowProperties (float newRadius,
  37250. float newOpacity,
  37251. int newShadowOffsetX,
  37252. int newShadowOffsetY);
  37253. /** @internal */
  37254. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  37255. private:
  37256. int offsetX, offsetY;
  37257. float radius, opacity;
  37258. JUCE_LEAK_DETECTOR (DropShadowEffect);
  37259. };
  37260. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  37261. /*** End of inlined file: juce_DropShadowEffect.h ***/
  37262. /**
  37263. A button with an arrow in it.
  37264. @see Button
  37265. */
  37266. class JUCE_API ArrowButton : public Button
  37267. {
  37268. public:
  37269. /** Creates an ArrowButton.
  37270. @param buttonName the name to give the button
  37271. @param arrowDirection the direction the arrow should point in, where 0.0 is
  37272. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  37273. @param arrowColour the colour to use for the arrow
  37274. */
  37275. ArrowButton (const String& buttonName,
  37276. float arrowDirection,
  37277. const Colour& arrowColour);
  37278. /** Destructor. */
  37279. ~ArrowButton();
  37280. protected:
  37281. /** @internal */
  37282. void paintButton (Graphics& g,
  37283. bool isMouseOverButton,
  37284. bool isButtonDown);
  37285. /** @internal */
  37286. void buttonStateChanged();
  37287. private:
  37288. Colour colour;
  37289. DropShadowEffect shadow;
  37290. Path path;
  37291. int offset;
  37292. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  37293. };
  37294. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  37295. /*** End of inlined file: juce_ArrowButton.h ***/
  37296. #endif
  37297. #ifndef __JUCE_BUTTON_JUCEHEADER__
  37298. #endif
  37299. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37300. /*** Start of inlined file: juce_DrawableButton.h ***/
  37301. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37302. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37303. /*** Start of inlined file: juce_Drawable.h ***/
  37304. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  37305. #define __JUCE_DRAWABLE_JUCEHEADER__
  37306. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  37307. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37308. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37309. /**
  37310. Expresses a coordinate as a dynamically evaluated expression.
  37311. @see RelativePoint, RelativeRectangle
  37312. */
  37313. class JUCE_API RelativeCoordinate
  37314. {
  37315. public:
  37316. /** Creates a zero coordinate. */
  37317. RelativeCoordinate();
  37318. RelativeCoordinate (const Expression& expression);
  37319. RelativeCoordinate (const RelativeCoordinate& other);
  37320. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  37321. /** Creates an absolute position from the parent origin on either the X or Y axis.
  37322. @param absoluteDistanceFromOrigin the distance from the origin
  37323. */
  37324. RelativeCoordinate (double absoluteDistanceFromOrigin);
  37325. /** Recreates a coordinate from a string description.
  37326. The string will be parsed by ExpressionParser::parse().
  37327. @param stringVersion the expression to use
  37328. @see toString
  37329. */
  37330. RelativeCoordinate (const String& stringVersion);
  37331. /** Destructor. */
  37332. ~RelativeCoordinate();
  37333. bool operator== (const RelativeCoordinate& other) const throw();
  37334. bool operator!= (const RelativeCoordinate& other) const throw();
  37335. /** Calculates the absolute position of this coordinate.
  37336. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  37337. be needed to calculate the result.
  37338. */
  37339. double resolve (const Expression::Scope* evaluationScope) const;
  37340. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  37341. This will recursively check any coordinates upon which this one depends.
  37342. */
  37343. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  37344. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  37345. bool isRecursive (const Expression::Scope* evaluationScope) const;
  37346. /** Returns true if this coordinate depends on any other coordinates for its position. */
  37347. bool isDynamic() const;
  37348. /** Changes the value of this coord to make it resolve to the specified position.
  37349. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  37350. or relative position to whatever value is necessary to make its resultant position
  37351. match the position that is provided.
  37352. */
  37353. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  37354. /** Returns the expression that defines this coordinate. */
  37355. const Expression& getExpression() const { return term; }
  37356. /** Returns a string which represents this coordinate.
  37357. For details of the string syntax, see the constructor notes.
  37358. */
  37359. const String toString() const;
  37360. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  37361. As well as avoiding using string literals in your code, using these preset values
  37362. has the advantage that all instances of the same string will share the same, reference-counted
  37363. String object, so if you have thousands of points which all refer to the same
  37364. anchor points, this can save a significant amount of memory allocation.
  37365. */
  37366. struct Strings
  37367. {
  37368. static const String parent; /**< "parent" */
  37369. static const String left; /**< "left" */
  37370. static const String right; /**< "right" */
  37371. static const String top; /**< "top" */
  37372. static const String bottom; /**< "bottom" */
  37373. static const String x; /**< "x" */
  37374. static const String y; /**< "y" */
  37375. static const String width; /**< "width" */
  37376. static const String height; /**< "height" */
  37377. };
  37378. struct StandardStrings
  37379. {
  37380. enum Type
  37381. {
  37382. left, right, top, bottom,
  37383. x, y, width, height,
  37384. parent,
  37385. unknown
  37386. };
  37387. static Type getTypeOf (const String& s) throw();
  37388. };
  37389. private:
  37390. Expression term;
  37391. };
  37392. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  37393. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  37394. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37395. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37396. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37397. /*** Start of inlined file: juce_RelativePoint.h ***/
  37398. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  37399. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  37400. /**
  37401. An X-Y position stored as a pair of RelativeCoordinate values.
  37402. @see RelativeCoordinate, RelativeRectangle
  37403. */
  37404. class JUCE_API RelativePoint
  37405. {
  37406. public:
  37407. /** Creates a point at the origin. */
  37408. RelativePoint();
  37409. /** Creates an absolute point, relative to the origin. */
  37410. RelativePoint (const Point<float>& absolutePoint);
  37411. /** Creates an absolute point, relative to the origin. */
  37412. RelativePoint (float absoluteX, float absoluteY);
  37413. /** Creates an absolute point from two coordinates. */
  37414. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  37415. /** Creates a point from a stringified representation.
  37416. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  37417. strings is explained in the RelativeCoordinate class.
  37418. @see toString
  37419. */
  37420. RelativePoint (const String& stringVersion);
  37421. bool operator== (const RelativePoint& other) const throw();
  37422. bool operator!= (const RelativePoint& other) const throw();
  37423. /** Calculates the absolute position of this point.
  37424. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  37425. be needed to calculate the result.
  37426. */
  37427. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  37428. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  37429. Calling this will leave any anchor points unchanged, but will set any absolute
  37430. or relative positions to whatever values are necessary to make the resultant position
  37431. match the position that is provided.
  37432. */
  37433. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  37434. /** Returns a string which represents this point.
  37435. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  37436. coordinates, see the RelativeCoordinate constructor notes.
  37437. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  37438. */
  37439. const String toString() const;
  37440. /** Returns true if this point depends on any other coordinates for its position. */
  37441. bool isDynamic() const;
  37442. // The actual X and Y coords...
  37443. RelativeCoordinate x, y;
  37444. };
  37445. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  37446. /*** End of inlined file: juce_RelativePoint.h ***/
  37447. /*** Start of inlined file: juce_MarkerList.h ***/
  37448. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  37449. #define __JUCE_MARKERLIST_JUCEHEADER__
  37450. class Component;
  37451. /**
  37452. Holds a set of named marker points along a one-dimensional axis.
  37453. This class is used to store sets of X and Y marker points in components.
  37454. @see Component::getMarkers().
  37455. */
  37456. class JUCE_API MarkerList
  37457. {
  37458. public:
  37459. /** Creates an empty marker list. */
  37460. MarkerList();
  37461. /** Creates a copy of another marker list. */
  37462. MarkerList (const MarkerList& other);
  37463. /** Copies another marker list to this one. */
  37464. MarkerList& operator= (const MarkerList& other);
  37465. /** Destructor. */
  37466. ~MarkerList();
  37467. /** Represents a marker in a MarkerList. */
  37468. class JUCE_API Marker
  37469. {
  37470. public:
  37471. /** Creates a copy of another Marker. */
  37472. Marker (const Marker& other);
  37473. /** Creates a Marker with a given name and position. */
  37474. Marker (const String& name, const RelativeCoordinate& position);
  37475. /** The marker's name. */
  37476. String name;
  37477. /** The marker's position.
  37478. The expression used to define the coordinate may use the names of other
  37479. markers, so that markers can be linked in arbitrary ways, but be careful
  37480. not to create recursive loops of markers whose positions are based on each
  37481. other! It can also refer to "parent.right" and "parent.bottom" so that you
  37482. can set markers which are relative to the size of the component that contains
  37483. them.
  37484. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  37485. */
  37486. RelativeCoordinate position;
  37487. /** Returns true if both the names and positions of these two markers match. */
  37488. bool operator== (const Marker&) const throw();
  37489. /** Returns true if either the name or position of these two markers differ. */
  37490. bool operator!= (const Marker&) const throw();
  37491. };
  37492. /** Returns the number of markers in the list. */
  37493. int getNumMarkers() const throw();
  37494. /** Returns one of the markers in the list, by its index. */
  37495. const Marker* getMarker (int index) const throw();
  37496. /** Returns a named marker, or 0 if no such name is found.
  37497. Note that name comparisons are case-sensitive.
  37498. */
  37499. const Marker* getMarker (const String& name) const throw();
  37500. /** Evaluates the given marker and returns its absolute position.
  37501. The parent component must be supplied in case the marker's expression refers to
  37502. the size of its parent component.
  37503. */
  37504. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  37505. /** Sets the position of a marker.
  37506. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  37507. new marker is added.
  37508. */
  37509. void setMarker (const String& name, const RelativeCoordinate& position);
  37510. /** Deletes the marker at the given list index. */
  37511. void removeMarker (int index);
  37512. /** Deletes the marker with the given name. */
  37513. void removeMarker (const String& name);
  37514. /** Returns true if all the markers in these two lists match exactly. */
  37515. bool operator== (const MarkerList& other) const throw();
  37516. /** Returns true if not all the markers in these two lists match exactly. */
  37517. bool operator!= (const MarkerList& other) const throw();
  37518. /**
  37519. A class for receiving events when changes are made to a MarkerList.
  37520. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  37521. method, and it will be called when markers are moved, added, or deleted.
  37522. @see MarkerList::addListener, MarkerList::removeListener
  37523. */
  37524. class JUCE_API Listener
  37525. {
  37526. public:
  37527. /** Destructor. */
  37528. virtual ~Listener() {}
  37529. /** Called when something in the given marker list changes. */
  37530. virtual void markersChanged (MarkerList* markerList) = 0;
  37531. /** Called when the given marker list is being deleted. */
  37532. virtual void markerListBeingDeleted (MarkerList* markerList);
  37533. };
  37534. /** Registers a listener that will be called when the markers are changed. */
  37535. void addListener (Listener* listener);
  37536. /** Deregisters a previously-registered listener. */
  37537. void removeListener (Listener* listener);
  37538. /** Synchronously calls markersChanged() on all the registered listeners. */
  37539. void markersHaveChanged();
  37540. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  37541. class ValueTreeWrapper
  37542. {
  37543. public:
  37544. ValueTreeWrapper (const ValueTree& state);
  37545. ValueTree& getState() throw() { return state; }
  37546. int getNumMarkers() const;
  37547. const ValueTree getMarkerState (int index) const;
  37548. const ValueTree getMarkerState (const String& name) const;
  37549. bool containsMarker (const ValueTree& state) const;
  37550. const MarkerList::Marker getMarker (const ValueTree& state) const;
  37551. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  37552. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  37553. void applyTo (MarkerList& markerList);
  37554. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  37555. static const Identifier markerTag, nameProperty, posProperty;
  37556. private:
  37557. ValueTree state;
  37558. };
  37559. private:
  37560. OwnedArray<Marker> markers;
  37561. ListenerList<Listener> listeners;
  37562. JUCE_LEAK_DETECTOR (MarkerList);
  37563. };
  37564. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  37565. /*** End of inlined file: juce_MarkerList.h ***/
  37566. /**
  37567. Base class for Component::Positioners that are based upon relative coordinates.
  37568. */
  37569. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  37570. public ComponentListener,
  37571. public MarkerList::Listener
  37572. {
  37573. public:
  37574. RelativeCoordinatePositionerBase (Component& component_);
  37575. ~RelativeCoordinatePositionerBase();
  37576. void componentMovedOrResized (Component&, bool, bool);
  37577. void componentParentHierarchyChanged (Component&);
  37578. void componentChildrenChanged (Component& component);
  37579. void componentBeingDeleted (Component& component);
  37580. void markersChanged (MarkerList*);
  37581. void markerListBeingDeleted (MarkerList* markerList);
  37582. void apply();
  37583. bool addCoordinate (const RelativeCoordinate& coord);
  37584. bool addPoint (const RelativePoint& point);
  37585. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  37586. class ComponentScope : public Expression::Scope
  37587. {
  37588. public:
  37589. ComponentScope (Component& component_);
  37590. const Expression getSymbolValue (const String& symbol) const;
  37591. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  37592. const String getScopeUID() const;
  37593. protected:
  37594. Component& component;
  37595. Component* findSiblingComponent (const String& componentID) const;
  37596. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  37597. private:
  37598. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  37599. };
  37600. protected:
  37601. virtual bool registerCoordinates() = 0;
  37602. virtual void applyToComponentBounds() = 0;
  37603. private:
  37604. class DependencyFinderScope;
  37605. friend class DependencyFinderScope;
  37606. Array <Component*> sourceComponents;
  37607. Array <MarkerList*> sourceMarkerLists;
  37608. bool registeredOk;
  37609. void registerComponentListener (Component& comp);
  37610. void registerMarkerListListener (MarkerList* const list);
  37611. void unregisterListeners();
  37612. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  37613. };
  37614. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37615. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37616. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  37617. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37618. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37619. /**
  37620. Loads and maintains a tree of Components from a ValueTree that represents them.
  37621. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  37622. this class lets you register a set of type-handlers for the different components that
  37623. are involved, and then uses these types to re-create a set of components from its
  37624. stored state.
  37625. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  37626. then use registerTypeHandler() to give it a set of type handlers that can cope with
  37627. all the items in your tree. Then you can call getComponent() to build the component.
  37628. Once you've got the component you can either take it and delete the ComponentBuilder
  37629. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  37630. ValueTree and automatically update the component to reflect these changes.
  37631. */
  37632. class JUCE_API ComponentBuilder : public ValueTree::Listener
  37633. {
  37634. public:
  37635. /** Creates a ComponentBuilder that will use the given state.
  37636. Once you've created your builder, you should use registerTypeHandler() to register some
  37637. type handlers for it, and then you can call createComponent() or getManagedComponent()
  37638. to get the actual component.
  37639. */
  37640. explicit ComponentBuilder (const ValueTree& state);
  37641. /** Destructor. */
  37642. ~ComponentBuilder();
  37643. /** Returns the ValueTree that this builder is working with. */
  37644. ValueTree& getState() throw() { return state; }
  37645. /** Returns the ValueTree that this builder is working with. */
  37646. const ValueTree& getState() const throw() { return state; }
  37647. /** Returns the builder's component (creating it if necessary).
  37648. The first time that this method is called, the builder will attempt to create a component
  37649. from the ValueTree, so you must have registered some suitable type handlers before calling
  37650. this. If there's a problem and the component can't be created, this method returns 0.
  37651. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  37652. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  37653. when the builder is destroyed. If you want to get a component that you can delete yourself,
  37654. call createComponent() instead.
  37655. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  37656. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  37657. as they may be changed or removed.
  37658. */
  37659. Component* getManagedComponent();
  37660. /** Creates and returns a new instance of the component that the ValueTree represents.
  37661. The caller is responsible for using and deleting the object that is returned. Unlike
  37662. getManagedComponent(), the component that is returned will not be updated by the builder.
  37663. */
  37664. Component* createComponent();
  37665. /**
  37666. The class is a base class for objects that manage the loading of a type of component
  37667. from a ValueTree.
  37668. To store and re-load a tree of components as a ValueTree, each component type must have
  37669. a TypeHandler to represent it.
  37670. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  37671. */
  37672. class JUCE_API TypeHandler
  37673. {
  37674. public:
  37675. /** Creates a TypeHandler.
  37676. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  37677. */
  37678. explicit TypeHandler (const Identifier& valueTreeType);
  37679. /** Destructor. */
  37680. virtual ~TypeHandler();
  37681. /** Returns the type of the ValueTrees that this handler can parse. */
  37682. const Identifier& getType() const throw() { return valueTreeType; }
  37683. /** Returns the builder that this type is registered with. */
  37684. ComponentBuilder* getBuilder() const throw();
  37685. /** This method must create a new component from the given state, add it to the specified
  37686. parent component (which may be null), and return it.
  37687. The ValueTree will have been pre-checked to make sure that its type matches the type
  37688. that this handler supports.
  37689. There's no need to set the new Component's ID to match that of the state - the builder
  37690. will take care of that itself.
  37691. */
  37692. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  37693. /** This method must update an existing component from a new ValueTree state.
  37694. A component that has been created with addNewComponentFromState() may need to be updated
  37695. if the ValueTree changes, so this method is used to do that. Your implementation must do
  37696. whatever's necessary to update the component from the new state provided.
  37697. The ValueTree will have been pre-checked to make sure that its type matches the type
  37698. that this handler supports, and the component will have been created by this type's
  37699. addNewComponentFromState() method.
  37700. */
  37701. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  37702. private:
  37703. friend class ComponentBuilder;
  37704. ComponentBuilder* builder;
  37705. const Identifier valueTreeType;
  37706. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  37707. };
  37708. /** Adds a type handler that the builder can use when trying to load components.
  37709. @see Drawable::registerDrawableTypeHandlers()
  37710. */
  37711. void registerTypeHandler (TypeHandler* type);
  37712. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  37713. TypeHandler* getHandlerForState (const ValueTree& state) const;
  37714. /** Returns the number of registered type handlers.
  37715. @see getHandler, registerTypeHandler
  37716. */
  37717. int getNumHandlers() const throw();
  37718. /** Returns one of the registered type handlers.
  37719. @see getNumHandlers, registerTypeHandler
  37720. */
  37721. TypeHandler* getHandler (int index) const throw();
  37722. /** This class is used when references to images need to be stored in ValueTrees.
  37723. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  37724. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  37725. your app.
  37726. When you're loading components from a ValueTree that may need a way of loading images, you
  37727. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  37728. trying to load the component.
  37729. @see ComponentBuilder::setImageProvider()
  37730. */
  37731. class JUCE_API ImageProvider
  37732. {
  37733. public:
  37734. ImageProvider() {}
  37735. virtual ~ImageProvider() {}
  37736. /** Retrieves the image associated with this identifier, which could be any
  37737. kind of string, number, filename, etc.
  37738. The image that is returned will be owned by the caller, but it may come
  37739. from the ImageCache.
  37740. */
  37741. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  37742. /** Returns an identifier to be used to refer to a given image.
  37743. This is used when a reference to an image is stored in a ValueTree.
  37744. */
  37745. virtual const var getIdentifierForImage (const Image& image) = 0;
  37746. };
  37747. /** Gives the builder an ImageProvider object that the type handlers can use when
  37748. loading images from stored references.
  37749. The object that is passed in is not owned by the builder, so the caller must delete
  37750. it when it is no longer needed, but not while the builder may still be using it. To
  37751. clear the image provider, just call setImageProvider (0).
  37752. */
  37753. void setImageProvider (ImageProvider* newImageProvider) throw();
  37754. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  37755. ImageProvider* getImageProvider() const throw();
  37756. /** Updates the children of a parent component by updating them from the children of
  37757. a given ValueTree.
  37758. */
  37759. void updateChildComponents (Component& parent, const ValueTree& children);
  37760. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  37761. for that component.
  37762. */
  37763. static const Identifier idProperty;
  37764. /** @internal */
  37765. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  37766. /** @internal */
  37767. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  37768. /** @internal */
  37769. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  37770. /** @internal */
  37771. void valueTreeChildOrderChanged (ValueTree& parentTree);
  37772. /** @internal */
  37773. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  37774. private:
  37775. ValueTree state;
  37776. OwnedArray <TypeHandler> types;
  37777. ScopedPointer<Component> component;
  37778. ImageProvider* imageProvider;
  37779. #if JUCE_DEBUG
  37780. WeakReference<Component> componentRef;
  37781. #endif
  37782. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  37783. };
  37784. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37785. /*** End of inlined file: juce_ComponentBuilder.h ***/
  37786. class DrawableComposite;
  37787. /**
  37788. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  37789. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37790. */
  37791. class JUCE_API Drawable : public Component
  37792. {
  37793. protected:
  37794. /** The base class can't be instantiated directly.
  37795. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37796. */
  37797. Drawable();
  37798. public:
  37799. /** Destructor. */
  37800. virtual ~Drawable();
  37801. /** Creates a deep copy of this Drawable object.
  37802. Use this to create a new copy of this and any sub-objects in the tree.
  37803. */
  37804. virtual Drawable* createCopy() const = 0;
  37805. /** Renders this Drawable object.
  37806. Note that the preferred way to render a drawable in future is by using it
  37807. as a component and adding it to a parent, so you might want to consider that
  37808. before using this method.
  37809. @see drawWithin
  37810. */
  37811. void draw (Graphics& g, float opacity,
  37812. const AffineTransform& transform = AffineTransform::identity) const;
  37813. /** Renders the Drawable at a given offset within the Graphics context.
  37814. The co-ordinates passed-in are used to translate the object relative to its own
  37815. origin before drawing it - this is basically a quick way of saying:
  37816. @code
  37817. draw (g, AffineTransform::translation (x, y)).
  37818. @endcode
  37819. Note that the preferred way to render a drawable in future is by using it
  37820. as a component and adding it to a parent, so you might want to consider that
  37821. before using this method.
  37822. */
  37823. void drawAt (Graphics& g, float x, float y, float opacity) const;
  37824. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  37825. changing its aspect-ratio.
  37826. The object can placed arbitrarily within the rectangle based on a Justification type,
  37827. and can either be made as big as possible, or just reduced to fit.
  37828. Note that the preferred way to render a drawable in future is by using it
  37829. as a component and adding it to a parent, so you might want to consider that
  37830. before using this method.
  37831. @param g the graphics context to render onto
  37832. @param destArea the target rectangle to fit the drawable into
  37833. @param placement defines the alignment and rescaling to use to fit
  37834. this object within the target rectangle.
  37835. @param opacity the opacity to use, in the range 0 to 1.0
  37836. */
  37837. void drawWithin (Graphics& g,
  37838. const Rectangle<float>& destArea,
  37839. const RectanglePlacement& placement,
  37840. float opacity) const;
  37841. /** Resets any transformations on this drawable, and positions its origin within
  37842. its parent component.
  37843. */
  37844. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  37845. /** Sets a transform for this drawable that will position it within the specified
  37846. area of its parent component.
  37847. */
  37848. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  37849. /** Returns the DrawableComposite that contains this object, if there is one. */
  37850. DrawableComposite* getParent() const;
  37851. /** Tries to turn some kind of image file into a drawable.
  37852. The data could be an image that the ImageFileFormat class understands, or it
  37853. could be SVG.
  37854. */
  37855. static Drawable* createFromImageData (const void* data, size_t numBytes);
  37856. /** Tries to turn a stream containing some kind of image data into a drawable.
  37857. The data could be an image that the ImageFileFormat class understands, or it
  37858. could be SVG.
  37859. */
  37860. static Drawable* createFromImageDataStream (InputStream& dataSource);
  37861. /** Tries to turn a file containing some kind of image data into a drawable.
  37862. The data could be an image that the ImageFileFormat class understands, or it
  37863. could be SVG.
  37864. */
  37865. static Drawable* createFromImageFile (const File& file);
  37866. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  37867. into a Drawable tree.
  37868. The object returned must be deleted by the caller. If something goes wrong
  37869. while parsing, it may return 0.
  37870. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  37871. implementation, but it can return the basic vector objects.
  37872. */
  37873. static Drawable* createFromSVG (const XmlElement& svgDocument);
  37874. /** Tries to create a Drawable from a previously-saved ValueTree.
  37875. The ValueTree must have been created by the createValueTree() method.
  37876. If there are any images used within the drawable, you'll need to provide a valid
  37877. ImageProvider object that can be used to retrieve these images from whatever type
  37878. of identifier is used to represent them.
  37879. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  37880. */
  37881. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  37882. /** Creates a ValueTree to represent this Drawable.
  37883. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  37884. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  37885. object that can be used to create storable representations of them.
  37886. */
  37887. virtual const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  37888. /** Returns the area that this drawble covers.
  37889. The result is expressed in this drawable's own coordinate space, and does not take
  37890. into account any transforms that may be applied to the component.
  37891. */
  37892. virtual const Rectangle<float> getDrawableBounds() const = 0;
  37893. /** Internal class used to manage ValueTrees that represent Drawables. */
  37894. class ValueTreeWrapperBase
  37895. {
  37896. public:
  37897. ValueTreeWrapperBase (const ValueTree& state);
  37898. ValueTree& getState() throw() { return state; }
  37899. const String getID() const;
  37900. void setID (const String& newID);
  37901. ValueTree state;
  37902. };
  37903. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  37904. load all the different Drawable types from a saved state.
  37905. @see ComponentBuilder::registerTypeHandler()
  37906. */
  37907. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  37908. protected:
  37909. friend class DrawableComposite;
  37910. friend class DrawableShape;
  37911. /** @internal */
  37912. void transformContextToCorrectOrigin (Graphics& g);
  37913. /** @internal */
  37914. void parentHierarchyChanged();
  37915. /** @internal */
  37916. void setBoundsToEnclose (const Rectangle<float>& area);
  37917. Point<int> originRelativeToComponent;
  37918. #ifndef DOXYGEN
  37919. /** Internal utility class used by Drawables. */
  37920. template <class DrawableType>
  37921. class Positioner : public RelativeCoordinatePositionerBase
  37922. {
  37923. public:
  37924. Positioner (DrawableType& component_)
  37925. : RelativeCoordinatePositionerBase (component_),
  37926. owner (component_)
  37927. {}
  37928. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  37929. void applyToComponentBounds()
  37930. {
  37931. ComponentScope scope (getComponent());
  37932. owner.recalculateCoordinates (&scope);
  37933. }
  37934. void applyNewBounds (const Rectangle<int>&)
  37935. {
  37936. jassertfalse; // drawables can't be resized directly!
  37937. }
  37938. private:
  37939. DrawableType& owner;
  37940. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  37941. };
  37942. #endif
  37943. private:
  37944. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  37945. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  37946. };
  37947. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  37948. /*** End of inlined file: juce_Drawable.h ***/
  37949. /**
  37950. A button that displays a Drawable.
  37951. Up to three Drawable objects can be given to this button, to represent the
  37952. 'normal', 'over' and 'down' states.
  37953. @see Button
  37954. */
  37955. class JUCE_API DrawableButton : public Button
  37956. {
  37957. public:
  37958. enum ButtonStyle
  37959. {
  37960. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  37961. ImageRaw, /**< The button will just display the images in their normal size and position.
  37962. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  37963. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  37964. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  37965. };
  37966. /** Creates a DrawableButton.
  37967. After creating one of these, use setImages() to specify the drawables to use.
  37968. @param buttonName the name to give the component
  37969. @param buttonStyle the layout to use
  37970. @see ButtonStyle, setButtonStyle, setImages
  37971. */
  37972. DrawableButton (const String& buttonName,
  37973. ButtonStyle buttonStyle);
  37974. /** Destructor. */
  37975. ~DrawableButton();
  37976. /** Sets up the images to draw for the various button states.
  37977. The button will keep its own internal copies of these drawables.
  37978. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  37979. will be made of the object passed-in if it is non-zero.
  37980. @param overImage the thing to draw for the button's 'over' state - if this is
  37981. zero, the button's normal image will be used when the mouse is
  37982. over it. An internal copy will be made of the object passed-in
  37983. if it is non-zero.
  37984. @param downImage the thing to draw for the button's 'down' state - if this is
  37985. zero, the 'over' image will be used instead (or the normal image
  37986. as a last resort). An internal copy will be made of the object
  37987. passed-in if it is non-zero.
  37988. @param disabledImage an image to draw when the button is disabled. If this is zero,
  37989. the normal image will be drawn with a reduced opacity instead.
  37990. An internal copy will be made of the object passed-in if it is
  37991. non-zero.
  37992. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  37993. state is 'on'. If this is 0, the normal image is used instead
  37994. @param overImageOn same as the overImage, but this is used when the button's toggle
  37995. state is 'on'. If this is 0, the normalImageOn is drawn instead
  37996. @param downImageOn same as the downImage, but this is used when the button's toggle
  37997. state is 'on'. If this is 0, the overImageOn is drawn instead
  37998. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  37999. state is 'on'. If this is 0, the normal image will be drawn instead
  38000. with a reduced opacity
  38001. */
  38002. void setImages (const Drawable* normalImage,
  38003. const Drawable* overImage = 0,
  38004. const Drawable* downImage = 0,
  38005. const Drawable* disabledImage = 0,
  38006. const Drawable* normalImageOn = 0,
  38007. const Drawable* overImageOn = 0,
  38008. const Drawable* downImageOn = 0,
  38009. const Drawable* disabledImageOn = 0);
  38010. /** Changes the button's style.
  38011. @see ButtonStyle
  38012. */
  38013. void setButtonStyle (ButtonStyle newStyle);
  38014. /** Changes the button's background colours.
  38015. The toggledOffColour is the colour to use when the button's toggle state
  38016. is off, and toggledOnColour when it's on.
  38017. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  38018. used to fill the background of the component.
  38019. For an ImageOnButtonBackground style, the colour is used to draw the
  38020. button's lozenge shape and exactly how the colour's used will depend
  38021. on the LookAndFeel.
  38022. */
  38023. void setBackgroundColours (const Colour& toggledOffColour,
  38024. const Colour& toggledOnColour);
  38025. /** Returns the current background colour being used.
  38026. @see setBackgroundColour
  38027. */
  38028. const Colour& getBackgroundColour() const throw();
  38029. /** Gives the button an optional amount of space around the edge of the drawable.
  38030. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  38031. ones on a button background. If the button is too small for the given gap, a
  38032. smaller gap will be used.
  38033. By default there's a gap of about 3 pixels.
  38034. */
  38035. void setEdgeIndent (int numPixelsIndent);
  38036. /** Returns the image that the button is currently displaying. */
  38037. Drawable* getCurrentImage() const throw();
  38038. Drawable* getNormalImage() const throw();
  38039. Drawable* getOverImage() const throw();
  38040. Drawable* getDownImage() const throw();
  38041. /** A set of colour IDs to use to change the colour of various aspects of the link.
  38042. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38043. methods.
  38044. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38045. */
  38046. enum ColourIds
  38047. {
  38048. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  38049. };
  38050. protected:
  38051. /** @internal */
  38052. void paintButton (Graphics& g,
  38053. bool isMouseOverButton,
  38054. bool isButtonDown);
  38055. /** @internal */
  38056. void buttonStateChanged();
  38057. /** @internal */
  38058. void resized();
  38059. private:
  38060. ButtonStyle style;
  38061. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  38062. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  38063. Drawable* currentImage;
  38064. Colour backgroundOff, backgroundOn;
  38065. int edgeIndent;
  38066. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  38067. };
  38068. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  38069. /*** End of inlined file: juce_DrawableButton.h ***/
  38070. #endif
  38071. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38072. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  38073. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38074. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38075. /**
  38076. A button showing an underlined weblink, that will launch the link
  38077. when it's clicked.
  38078. @see Button
  38079. */
  38080. class JUCE_API HyperlinkButton : public Button
  38081. {
  38082. public:
  38083. /** Creates a HyperlinkButton.
  38084. @param linkText the text that will be displayed in the button - this is
  38085. also set as the Component's name, but the text can be
  38086. changed later with the Button::getButtonText() method
  38087. @param linkURL the URL to launch when the user clicks the button
  38088. */
  38089. HyperlinkButton (const String& linkText,
  38090. const URL& linkURL);
  38091. /** Destructor. */
  38092. ~HyperlinkButton();
  38093. /** Changes the font to use for the text.
  38094. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  38095. to match the size of the component.
  38096. */
  38097. void setFont (const Font& newFont,
  38098. bool resizeToMatchComponentHeight,
  38099. const Justification& justificationType = Justification::horizontallyCentred);
  38100. /** A set of colour IDs to use to change the colour of various aspects of the link.
  38101. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38102. methods.
  38103. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38104. */
  38105. enum ColourIds
  38106. {
  38107. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  38108. };
  38109. /** Changes the URL that the button will trigger. */
  38110. void setURL (const URL& newURL) throw();
  38111. /** Returns the URL that the button will trigger. */
  38112. const URL& getURL() const throw() { return url; }
  38113. /** Resizes the button horizontally to fit snugly around the text.
  38114. This won't affect the button's height.
  38115. */
  38116. void changeWidthToFitText();
  38117. protected:
  38118. /** @internal */
  38119. void clicked();
  38120. /** @internal */
  38121. void colourChanged();
  38122. /** @internal */
  38123. void paintButton (Graphics& g,
  38124. bool isMouseOverButton,
  38125. bool isButtonDown);
  38126. private:
  38127. URL url;
  38128. Font font;
  38129. bool resizeFont;
  38130. Justification justification;
  38131. const Font getFontToUse() const;
  38132. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  38133. };
  38134. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  38135. /*** End of inlined file: juce_HyperlinkButton.h ***/
  38136. #endif
  38137. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  38138. /*** Start of inlined file: juce_ImageButton.h ***/
  38139. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  38140. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  38141. /**
  38142. As the title suggests, this is a button containing an image.
  38143. The colour and transparency of the image can be set to vary when the
  38144. button state changes.
  38145. @see Button, ShapeButton, TextButton
  38146. */
  38147. class JUCE_API ImageButton : public Button
  38148. {
  38149. public:
  38150. /** Creates an ImageButton.
  38151. Use setImage() to specify the image to use. The colours and opacities that
  38152. are specified here can be changed later using setDrawingOptions().
  38153. @param name the name to give the component
  38154. */
  38155. explicit ImageButton (const String& name);
  38156. /** Destructor. */
  38157. ~ImageButton();
  38158. /** Sets up the images to draw in various states.
  38159. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  38160. resized to the same dimensions as the normal image
  38161. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  38162. button when the button's size changes
  38163. @param preserveImageProportions if true then any rescaling of the image to fit
  38164. the button will keep the image's x and y proportions
  38165. correct - i.e. it won't distort its shape, although
  38166. this might create gaps around the edges
  38167. @param normalImage the image to use when the button is in its normal state.
  38168. button no longer needs it.
  38169. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  38170. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  38171. normal image - if this colour is transparent, no overlay
  38172. will be drawn. The overlay will be drawn over the top of the
  38173. image, so you can basically add a solid or semi-transparent
  38174. colour to the image to brighten or darken it
  38175. @param overImage the image to use when the mouse is over the button. If
  38176. you want to use the same image as was set in the normalImage
  38177. parameter, this value can be a null image.
  38178. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  38179. is over the button
  38180. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  38181. image when the mouse is over - if this colour is transparent,
  38182. no overlay will be drawn
  38183. @param downImage an image to use when the button is pressed down. If set
  38184. to a null image, the 'over' image will be drawn instead (or the
  38185. normal image if there isn't an 'over' image either).
  38186. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  38187. is pressed
  38188. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  38189. image when the button is pressed down - if this colour is
  38190. transparent, no overlay will be drawn
  38191. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  38192. whenever it's inside the button's bounding rectangle. If
  38193. set to values higher than 0, the mouse will only be
  38194. considered to be over the image when the value of the
  38195. image's alpha channel at that position is greater than
  38196. this level.
  38197. */
  38198. void setImages (bool resizeButtonNowToFitThisImage,
  38199. bool rescaleImagesWhenButtonSizeChanges,
  38200. bool preserveImageProportions,
  38201. const Image& normalImage,
  38202. float imageOpacityWhenNormal,
  38203. const Colour& overlayColourWhenNormal,
  38204. const Image& overImage,
  38205. float imageOpacityWhenOver,
  38206. const Colour& overlayColourWhenOver,
  38207. const Image& downImage,
  38208. float imageOpacityWhenDown,
  38209. const Colour& overlayColourWhenDown,
  38210. float hitTestAlphaThreshold = 0.0f);
  38211. /** Returns the currently set 'normal' image. */
  38212. const Image getNormalImage() const;
  38213. /** Returns the image that's drawn when the mouse is over the button.
  38214. If a valid 'over' image has been set, this will return it; otherwise it'll
  38215. just return the normal image.
  38216. */
  38217. const Image getOverImage() const;
  38218. /** Returns the image that's drawn when the button is held down.
  38219. If a valid 'down' image has been set, this will return it; otherwise it'll
  38220. return the 'over' image or normal image, depending on what's available.
  38221. */
  38222. const Image getDownImage() const;
  38223. protected:
  38224. /** @internal */
  38225. bool hitTest (int x, int y);
  38226. /** @internal */
  38227. void paintButton (Graphics& g,
  38228. bool isMouseOverButton,
  38229. bool isButtonDown);
  38230. private:
  38231. bool scaleImageToFit, preserveProportions;
  38232. unsigned char alphaThreshold;
  38233. int imageX, imageY, imageW, imageH;
  38234. Image normalImage, overImage, downImage;
  38235. float normalOpacity, overOpacity, downOpacity;
  38236. Colour normalOverlay, overOverlay, downOverlay;
  38237. const Image getCurrentImage() const;
  38238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  38239. };
  38240. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  38241. /*** End of inlined file: juce_ImageButton.h ***/
  38242. #endif
  38243. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  38244. /*** Start of inlined file: juce_ShapeButton.h ***/
  38245. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  38246. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  38247. /**
  38248. A button that contains a filled shape.
  38249. @see Button, ImageButton, TextButton, ArrowButton
  38250. */
  38251. class JUCE_API ShapeButton : public Button
  38252. {
  38253. public:
  38254. /** Creates a ShapeButton.
  38255. @param name a name to give the component - see Component::setName()
  38256. @param normalColour the colour to fill the shape with when the mouse isn't over
  38257. @param overColour the colour to use when the mouse is over the shape
  38258. @param downColour the colour to use when the button is in the pressed-down state
  38259. */
  38260. ShapeButton (const String& name,
  38261. const Colour& normalColour,
  38262. const Colour& overColour,
  38263. const Colour& downColour);
  38264. /** Destructor. */
  38265. ~ShapeButton();
  38266. /** Sets the shape to use.
  38267. @param newShape the shape to use
  38268. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  38269. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  38270. the button is resized
  38271. @param hasDropShadow if true, the button will be given a drop-shadow effect
  38272. */
  38273. void setShape (const Path& newShape,
  38274. bool resizeNowToFitThisShape,
  38275. bool maintainShapeProportions,
  38276. bool hasDropShadow);
  38277. /** Set the colours to use for drawing the shape.
  38278. @param normalColour the colour to fill the shape with when the mouse isn't over
  38279. @param overColour the colour to use when the mouse is over the shape
  38280. @param downColour the colour to use when the button is in the pressed-down state
  38281. */
  38282. void setColours (const Colour& normalColour,
  38283. const Colour& overColour,
  38284. const Colour& downColour);
  38285. /** Sets up an outline to draw around the shape.
  38286. @param outlineColour the colour to use
  38287. @param outlineStrokeWidth the thickness of line to draw
  38288. */
  38289. void setOutline (const Colour& outlineColour,
  38290. float outlineStrokeWidth);
  38291. protected:
  38292. /** @internal */
  38293. void paintButton (Graphics& g,
  38294. bool isMouseOverButton,
  38295. bool isButtonDown);
  38296. private:
  38297. Colour normalColour, overColour, downColour, outlineColour;
  38298. DropShadowEffect shadow;
  38299. Path shape;
  38300. bool maintainShapeProportions;
  38301. float outlineWidth;
  38302. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  38303. };
  38304. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  38305. /*** End of inlined file: juce_ShapeButton.h ***/
  38306. #endif
  38307. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  38308. #endif
  38309. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38310. /*** Start of inlined file: juce_ToggleButton.h ***/
  38311. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38312. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38313. /**
  38314. A button that can be toggled on/off.
  38315. All buttons can be toggle buttons, but this lets you create one of the
  38316. standard ones which has a tick-box and a text label next to it.
  38317. @see Button, DrawableButton, TextButton
  38318. */
  38319. class JUCE_API ToggleButton : public Button
  38320. {
  38321. public:
  38322. /** Creates a ToggleButton.
  38323. @param buttonText the text to put in the button (the component's name is also
  38324. initially set to this string, but these can be changed later
  38325. using the setName() and setButtonText() methods)
  38326. */
  38327. explicit ToggleButton (const String& buttonText = String::empty);
  38328. /** Destructor. */
  38329. ~ToggleButton();
  38330. /** Resizes the button to fit neatly around its current text.
  38331. The button's height won't be affected, only its width.
  38332. */
  38333. void changeWidthToFitText();
  38334. /** A set of colour IDs to use to change the colour of various aspects of the button.
  38335. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38336. methods.
  38337. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38338. */
  38339. enum ColourIds
  38340. {
  38341. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  38342. };
  38343. protected:
  38344. /** @internal */
  38345. void paintButton (Graphics& g,
  38346. bool isMouseOverButton,
  38347. bool isButtonDown);
  38348. /** @internal */
  38349. void colourChanged();
  38350. private:
  38351. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  38352. };
  38353. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  38354. /*** End of inlined file: juce_ToggleButton.h ***/
  38355. #endif
  38356. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38357. /*** Start of inlined file: juce_ToolbarButton.h ***/
  38358. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38359. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38360. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  38361. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38362. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38363. /*** Start of inlined file: juce_Toolbar.h ***/
  38364. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  38365. #define __JUCE_TOOLBAR_JUCEHEADER__
  38366. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  38367. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38368. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38369. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  38370. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38371. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38372. /**
  38373. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  38374. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  38375. derive your component from this class, and make sure that it is somewhere inside a
  38376. DragAndDropContainer component.
  38377. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38378. the operating system onto your component, you don't need any of these classes: instead
  38379. see the FileDragAndDropTarget class.
  38380. @see DragAndDropContainer, FileDragAndDropTarget
  38381. */
  38382. class JUCE_API DragAndDropTarget
  38383. {
  38384. public:
  38385. /** Destructor. */
  38386. virtual ~DragAndDropTarget() {}
  38387. /** Callback to check whether this target is interested in the type of object being
  38388. dragged.
  38389. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38390. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38391. @returns true if this component wants to receive the other callbacks regarging this
  38392. type of object; if it returns false, no other callbacks will be made.
  38393. */
  38394. virtual bool isInterestedInDragSource (const String& sourceDescription,
  38395. Component* sourceComponent) = 0;
  38396. /** Callback to indicate that something is being dragged over this component.
  38397. This gets called when the user moves the mouse into this component while dragging
  38398. something.
  38399. Use this callback as a trigger to make your component repaint itself to give the
  38400. user feedback about whether the item can be dropped here or not.
  38401. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38402. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38403. @param x the mouse x position, relative to this component
  38404. @param y the mouse y position, relative to this component
  38405. @see itemDragExit
  38406. */
  38407. virtual void itemDragEnter (const String& sourceDescription,
  38408. Component* sourceComponent,
  38409. int x, int y);
  38410. /** Callback to indicate that the user is dragging something over this component.
  38411. This gets called when the user moves the mouse over this component while dragging
  38412. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  38413. this lets you know what happens in-between.
  38414. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38415. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38416. @param x the mouse x position, relative to this component
  38417. @param y the mouse y position, relative to this component
  38418. */
  38419. virtual void itemDragMove (const String& sourceDescription,
  38420. Component* sourceComponent,
  38421. int x, int y);
  38422. /** Callback to indicate that something has been dragged off the edge of this component.
  38423. This gets called when the user moves the mouse out of this component while dragging
  38424. something.
  38425. If you've used itemDragEnter() to repaint your component and give feedback, use this
  38426. as a signal to repaint it in its normal state.
  38427. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38428. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38429. @see itemDragEnter
  38430. */
  38431. virtual void itemDragExit (const String& sourceDescription,
  38432. Component* sourceComponent);
  38433. /** Callback to indicate that the user has dropped something onto this component.
  38434. When the user drops an item this get called, and you can use the description to
  38435. work out whether your object wants to deal with it or not.
  38436. Note that after this is called, the itemDragExit method may not be called, so you should
  38437. clean up in here if there's anything you need to do when the drag finishes.
  38438. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  38439. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  38440. @param x the mouse x position, relative to this component
  38441. @param y the mouse y position, relative to this component
  38442. */
  38443. virtual void itemDropped (const String& sourceDescription,
  38444. Component* sourceComponent,
  38445. int x, int y) = 0;
  38446. /** Overriding this allows the target to tell the drag container whether to
  38447. draw the drag image while the cursor is over it.
  38448. By default it returns true, but if you return false, then the normal drag
  38449. image will not be shown when the cursor is over this target.
  38450. */
  38451. virtual bool shouldDrawDragImageWhenOver();
  38452. };
  38453. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38454. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  38455. /**
  38456. Enables drag-and-drop behaviour for a component and all its sub-components.
  38457. For a component to be able to make or receive drag-and-drop events, one of its parent
  38458. components must derive from this class. It's probably best for the top-level
  38459. component to implement it.
  38460. Then to start a drag operation, any sub-component can just call the startDragging()
  38461. method, and this object will take over, tracking the mouse and sending appropriate
  38462. callbacks to any child components derived from DragAndDropTarget which the mouse
  38463. moves over.
  38464. Note: If all that you need to do is to respond to files being drag-and-dropped from
  38465. the operating system onto your component, you don't need any of these classes: you can do this
  38466. simply by overriding Component::filesDropped().
  38467. @see DragAndDropTarget
  38468. */
  38469. class JUCE_API DragAndDropContainer
  38470. {
  38471. public:
  38472. /** Creates a DragAndDropContainer.
  38473. The object that derives from this class must also be a Component.
  38474. */
  38475. DragAndDropContainer();
  38476. /** Destructor. */
  38477. virtual ~DragAndDropContainer();
  38478. /** Begins a drag-and-drop operation.
  38479. This starts a drag-and-drop operation - call it when the user drags the
  38480. mouse in your drag-source component, and this object will track mouse
  38481. movements until the user lets go of the mouse button, and will send
  38482. appropriate messages to DragAndDropTarget objects that the mouse moves
  38483. over.
  38484. findParentDragContainerFor() is a handy method to call to find the
  38485. drag container to use for a component.
  38486. @param sourceDescription a string to use as the description of the thing being
  38487. dragged - this will be passed to the objects that might be
  38488. dropped-onto so they can decide if they want to handle it or
  38489. not
  38490. @param sourceComponent the component that is being dragged
  38491. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  38492. a snapshot of the sourceComponent will be used instead.
  38493. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  38494. window, and can be dragged to DragAndDropTargets that are the
  38495. children of components other than this one.
  38496. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  38497. at which the image should be drawn from the mouse. If it isn't
  38498. specified, then the image will be centred around the mouse. If
  38499. an image hasn't been passed-in, this will be ignored.
  38500. */
  38501. void startDragging (const String& sourceDescription,
  38502. Component* sourceComponent,
  38503. const Image& dragImage = Image::null,
  38504. bool allowDraggingToOtherJuceWindows = false,
  38505. const Point<int>* imageOffsetFromMouse = 0);
  38506. /** Returns true if something is currently being dragged. */
  38507. bool isDragAndDropActive() const;
  38508. /** Returns the description of the thing that's currently being dragged.
  38509. If nothing's being dragged, this will return an empty string, otherwise it's the
  38510. string that was passed into startDragging().
  38511. @see startDragging
  38512. */
  38513. const String getCurrentDragDescription() const;
  38514. /** Utility to find the DragAndDropContainer for a given Component.
  38515. This will search up this component's parent hierarchy looking for the first
  38516. parent component which is a DragAndDropContainer.
  38517. It's useful when a component wants to call startDragging but doesn't know
  38518. the DragAndDropContainer it should to use.
  38519. Obviously this may return 0 if it doesn't find a suitable component.
  38520. */
  38521. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  38522. /** This performs a synchronous drag-and-drop of a set of files to some external
  38523. application.
  38524. You can call this function in response to a mouseDrag callback, and it will
  38525. block, running its own internal message loop and tracking the mouse, while it
  38526. uses a native operating system drag-and-drop operation to move or copy some
  38527. files to another application.
  38528. @param files a list of filenames to drag
  38529. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  38530. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  38531. @returns true if the files were successfully dropped somewhere, or false if it
  38532. was interrupted
  38533. @see performExternalDragDropOfText
  38534. */
  38535. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  38536. /** This performs a synchronous drag-and-drop of a block of text to some external
  38537. application.
  38538. You can call this function in response to a mouseDrag callback, and it will
  38539. block, running its own internal message loop and tracking the mouse, while it
  38540. uses a native operating system drag-and-drop operation to move or copy some
  38541. text to another application.
  38542. @param text the text to copy
  38543. @returns true if the text was successfully dropped somewhere, or false if it
  38544. was interrupted
  38545. @see performExternalDragDropOfFiles
  38546. */
  38547. static bool performExternalDragDropOfText (const String& text);
  38548. protected:
  38549. /** Override this if you want to be able to perform an external drag a set of files
  38550. when the user drags outside of this container component.
  38551. This method will be called when a drag operation moves outside the Juce-based window,
  38552. and if you want it to then perform a file drag-and-drop, add the filenames you want
  38553. to the array passed in, and return true.
  38554. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  38555. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  38556. @param files on return, the filenames you want to drag
  38557. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  38558. it must make a copy of them (see the performExternalDragDropOfFiles()
  38559. method)
  38560. @see performExternalDragDropOfFiles
  38561. */
  38562. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  38563. Component* dragSourceComponent,
  38564. StringArray& files,
  38565. bool& canMoveFiles);
  38566. private:
  38567. friend class DragImageComponent;
  38568. ScopedPointer <Component> dragImageComponent;
  38569. String currentDragDesc;
  38570. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  38571. };
  38572. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38573. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  38574. class ToolbarItemComponent;
  38575. class ToolbarItemFactory;
  38576. /**
  38577. A toolbar component.
  38578. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  38579. and looks after their order and layout.
  38580. Items (icon buttons or other custom components) are added to a toolbar using a
  38581. ToolbarItemFactory - each type of item is given a unique ID number, and a
  38582. toolbar might contain more than one instance of a particular item type.
  38583. Toolbars can be interactively customised, allowing the user to drag the items
  38584. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  38585. component as a source of new items.
  38586. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  38587. */
  38588. class JUCE_API Toolbar : public Component,
  38589. public DragAndDropContainer,
  38590. public DragAndDropTarget,
  38591. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  38592. {
  38593. public:
  38594. /** Creates an empty toolbar component.
  38595. To add some icons or other components to your toolbar, you'll need to
  38596. create a ToolbarItemFactory class that can create a suitable set of
  38597. ToolbarItemComponents.
  38598. @see ToolbarItemFactory, ToolbarItemComponents
  38599. */
  38600. Toolbar();
  38601. /** Destructor.
  38602. Any items on the bar will be deleted when the toolbar is deleted.
  38603. */
  38604. ~Toolbar();
  38605. /** Changes the bar's orientation.
  38606. @see isVertical
  38607. */
  38608. void setVertical (bool shouldBeVertical);
  38609. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  38610. You can change the bar's orientation with setVertical().
  38611. */
  38612. bool isVertical() const throw() { return vertical; }
  38613. /** Returns the depth of the bar.
  38614. If the bar is horizontal, this will return its height; if it's vertical, it
  38615. will return its width.
  38616. @see getLength
  38617. */
  38618. int getThickness() const throw();
  38619. /** Returns the length of the bar.
  38620. If the bar is horizontal, this will return its width; if it's vertical, it
  38621. will return its height.
  38622. @see getThickness
  38623. */
  38624. int getLength() const throw();
  38625. /** Deletes all items from the bar.
  38626. */
  38627. void clear();
  38628. /** Adds an item to the toolbar.
  38629. The factory's ToolbarItemFactory::createItem() will be called by this method
  38630. to create the component that will actually be added to the bar.
  38631. The new item will be inserted at the specified index (if the index is -1, it
  38632. will be added to the right-hand or bottom end of the bar).
  38633. Once added, the component will be automatically deleted by this object when it
  38634. is no longer needed.
  38635. @see ToolbarItemFactory
  38636. */
  38637. void addItem (ToolbarItemFactory& factory,
  38638. int itemId,
  38639. int insertIndex = -1);
  38640. /** Deletes one of the items from the bar.
  38641. */
  38642. void removeToolbarItem (int itemIndex);
  38643. /** Returns the number of items currently on the toolbar.
  38644. @see getItemId, getItemComponent
  38645. */
  38646. int getNumItems() const throw();
  38647. /** Returns the ID of the item with the given index.
  38648. If the index is less than zero or greater than the number of items,
  38649. this will return 0.
  38650. @see getNumItems
  38651. */
  38652. int getItemId (int itemIndex) const throw();
  38653. /** Returns the component being used for the item with the given index.
  38654. If the index is less than zero or greater than the number of items,
  38655. this will return 0.
  38656. @see getNumItems
  38657. */
  38658. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  38659. /** Clears this toolbar and adds to it the default set of items that the specified
  38660. factory creates.
  38661. @see ToolbarItemFactory::getDefaultItemSet
  38662. */
  38663. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  38664. /** Options for the way items should be displayed.
  38665. @see setStyle, getStyle
  38666. */
  38667. enum ToolbarItemStyle
  38668. {
  38669. iconsOnly, /**< Means that the toolbar should just contain icons. */
  38670. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  38671. textOnly /**< Means that the toolbar only display text labels for each item. */
  38672. };
  38673. /** Returns the toolbar's current style.
  38674. @see ToolbarItemStyle, setStyle
  38675. */
  38676. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  38677. /** Changes the toolbar's current style.
  38678. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  38679. */
  38680. void setStyle (const ToolbarItemStyle& newStyle);
  38681. /** Flags used by the showCustomisationDialog() method. */
  38682. enum CustomisationFlags
  38683. {
  38684. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  38685. show the "icons only" option on its choice of toolbar styles. */
  38686. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  38687. show the "icons with text" option on its choice of toolbar styles. */
  38688. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  38689. show the "text only" option on its choice of toolbar styles. */
  38690. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  38691. show a button to reset the toolbar to its default set of items. */
  38692. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  38693. };
  38694. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  38695. The dialog contains a ToolbarItemPalette and various controls for editing other
  38696. aspects of the toolbar. This method will block and run the dialog box modally,
  38697. returning when the user closes it.
  38698. The factory is used to determine the set of items that will be shown on the
  38699. palette.
  38700. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  38701. enum.
  38702. @see ToolbarItemPalette
  38703. */
  38704. void showCustomisationDialog (ToolbarItemFactory& factory,
  38705. int optionFlags = allCustomisationOptionsEnabled);
  38706. /** Turns on or off the toolbar's editing mode, in which its items can be
  38707. rearranged by the user.
  38708. (In most cases it's easier just to use showCustomisationDialog() instead of
  38709. trying to enable editing directly).
  38710. @see ToolbarItemPalette
  38711. */
  38712. void setEditingActive (bool editingEnabled);
  38713. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  38714. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38715. methods.
  38716. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38717. */
  38718. enum ColourIds
  38719. {
  38720. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  38721. more control over this, override LookAndFeel::paintToolbarBackground(). */
  38722. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  38723. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  38724. over them. */
  38725. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  38726. held down on them. */
  38727. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  38728. when the style is set to iconsWithText or textOnly. */
  38729. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  38730. the customisation dialog is active and the mouse moves over them. */
  38731. };
  38732. /** Returns a string that represents the toolbar's current set of items.
  38733. This lets you later restore the same item layout using restoreFromString().
  38734. @see restoreFromString
  38735. */
  38736. const String toString() const;
  38737. /** Restores a set of items that was previously stored in a string by the toString()
  38738. method.
  38739. The factory object is used to create any item components that are needed.
  38740. @see toString
  38741. */
  38742. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  38743. const String& savedVersion);
  38744. /** @internal */
  38745. void paint (Graphics& g);
  38746. /** @internal */
  38747. void resized();
  38748. /** @internal */
  38749. void buttonClicked (Button*);
  38750. /** @internal */
  38751. void mouseDown (const MouseEvent&);
  38752. /** @internal */
  38753. bool isInterestedInDragSource (const String&, Component*);
  38754. /** @internal */
  38755. void itemDragMove (const String&, Component*, int, int);
  38756. /** @internal */
  38757. void itemDragExit (const String&, Component*);
  38758. /** @internal */
  38759. void itemDropped (const String&, Component*, int, int);
  38760. /** @internal */
  38761. void updateAllItemPositions (bool animate);
  38762. /** @internal */
  38763. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  38764. private:
  38765. ScopedPointer<Button> missingItemsButton;
  38766. bool vertical, isEditingActive;
  38767. ToolbarItemStyle toolbarStyle;
  38768. class MissingItemsComponent;
  38769. friend class MissingItemsComponent;
  38770. OwnedArray <ToolbarItemComponent> items;
  38771. friend class ItemDragAndDropOverlayComponent;
  38772. static const char* const toolbarDragDescriptor;
  38773. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  38774. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  38775. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  38776. };
  38777. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  38778. /*** End of inlined file: juce_Toolbar.h ***/
  38779. class ItemDragAndDropOverlayComponent;
  38780. /**
  38781. A component that can be used as one of the items in a Toolbar.
  38782. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  38783. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  38784. class for further info about creating them.
  38785. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  38786. components too. To do this, set the value of isBeingUsedAsAButton to false when
  38787. calling the constructor, and override contentAreaChanged(), in which you can position
  38788. any sub-components you need to add.
  38789. To add basic buttons without writing a special subclass, have a look at the
  38790. ToolbarButton class.
  38791. @see ToolbarButton, Toolbar, ToolbarItemFactory
  38792. */
  38793. class JUCE_API ToolbarItemComponent : public Button
  38794. {
  38795. public:
  38796. /** Constructor.
  38797. @param itemId the ID of the type of toolbar item which this represents
  38798. @param labelText the text to display if the toolbar's style is set to
  38799. Toolbar::iconsWithText or Toolbar::textOnly
  38800. @param isBeingUsedAsAButton set this to false if you don't want the button
  38801. to draw itself with button over/down states when the mouse
  38802. moves over it or clicks
  38803. */
  38804. ToolbarItemComponent (int itemId,
  38805. const String& labelText,
  38806. bool isBeingUsedAsAButton);
  38807. /** Destructor. */
  38808. ~ToolbarItemComponent();
  38809. /** Returns the item type ID that this component represents.
  38810. This value is in the constructor.
  38811. */
  38812. int getItemId() const throw() { return itemId; }
  38813. /** Returns the toolbar that contains this component, or 0 if it's not currently
  38814. inside one.
  38815. */
  38816. Toolbar* getToolbar() const;
  38817. /** Returns true if this component is currently inside a toolbar which is vertical.
  38818. @see Toolbar::isVertical
  38819. */
  38820. bool isToolbarVertical() const;
  38821. /** Returns the current style setting of this item.
  38822. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  38823. @see setStyle, Toolbar::getStyle
  38824. */
  38825. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  38826. /** Changes the current style setting of this item.
  38827. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  38828. by the toolbar that holds this item.
  38829. @see setStyle, Toolbar::setStyle
  38830. */
  38831. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  38832. /** Returns the area of the component that should be used to display the button image or
  38833. other contents of the item.
  38834. This content area may change when the item's style changes, and may leave a space around the
  38835. edge of the component where the text label can be shown.
  38836. @see contentAreaChanged
  38837. */
  38838. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  38839. /** This method must return the size criteria for this item, based on a given toolbar
  38840. size and orientation.
  38841. The preferredSize, minSize and maxSize values must all be set by your implementation
  38842. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  38843. toolbar, they refer to the item's height.
  38844. The preferredSize is the size that the component would like to be, and this must be
  38845. between the min and max sizes. For a fixed-size item, simply set all three variables to
  38846. the same value.
  38847. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  38848. Toolbar::getThickness().
  38849. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  38850. vertically.
  38851. */
  38852. virtual bool getToolbarItemSizes (int toolbarThickness,
  38853. bool isToolbarVertical,
  38854. int& preferredSize,
  38855. int& minSize,
  38856. int& maxSize) = 0;
  38857. /** Your subclass should use this method to draw its content area.
  38858. The graphics object that is passed-in will have been clipped and had its origin
  38859. moved to fit the content area as specified get getContentArea(). The width and height
  38860. parameters are the width and height of the content area.
  38861. If the component you're writing isn't a button, you can just do nothing in this method.
  38862. */
  38863. virtual void paintButtonArea (Graphics& g,
  38864. int width, int height,
  38865. bool isMouseOver, bool isMouseDown) = 0;
  38866. /** Callback to indicate that the content area of this item has changed.
  38867. This might be because the component was resized, or because the style changed and
  38868. the space needed for the text label is different.
  38869. See getContentArea() for a description of what the area is.
  38870. */
  38871. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  38872. /** Editing modes.
  38873. These are used by setEditingMode(), but will be rarely needed in user code.
  38874. */
  38875. enum ToolbarEditingMode
  38876. {
  38877. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  38878. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  38879. customisation mode, and the items can be dragged around. */
  38880. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  38881. dragged onto a toolbar to add it to that bar.*/
  38882. };
  38883. /** Changes the editing mode of this component.
  38884. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38885. and is unlikely to be of much use in end-user-code.
  38886. */
  38887. void setEditingMode (const ToolbarEditingMode newMode);
  38888. /** Returns the current editing mode of this component.
  38889. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38890. and is unlikely to be of much use in end-user-code.
  38891. */
  38892. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  38893. /** @internal */
  38894. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  38895. /** @internal */
  38896. void resized();
  38897. private:
  38898. friend class Toolbar;
  38899. friend class ItemDragAndDropOverlayComponent;
  38900. const int itemId;
  38901. ToolbarEditingMode mode;
  38902. Toolbar::ToolbarItemStyle toolbarStyle;
  38903. ScopedPointer <Component> overlayComp;
  38904. int dragOffsetX, dragOffsetY;
  38905. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  38906. Rectangle<int> contentArea;
  38907. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  38908. };
  38909. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38910. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  38911. /**
  38912. A type of button designed to go on a toolbar.
  38913. This simple button can have two Drawable objects specified - one for normal
  38914. use and another one (optionally) for the button's "on" state if it's a
  38915. toggle button.
  38916. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  38917. */
  38918. class JUCE_API ToolbarButton : public ToolbarItemComponent
  38919. {
  38920. public:
  38921. /** Creates a ToolbarButton.
  38922. @param itemId the ID for this toolbar item type. This is passed through to the
  38923. ToolbarItemComponent constructor
  38924. @param labelText the text to display on the button (if the toolbar is using a style
  38925. that shows text labels). This is passed through to the
  38926. ToolbarItemComponent constructor
  38927. @param normalImage a drawable object that the button should use as its icon. The object
  38928. that is passed-in here will be kept by this object and will be
  38929. deleted when no longer needed or when this button is deleted.
  38930. @param toggledOnImage a drawable object that the button can use as its icon if the button
  38931. is in a toggled-on state (see the Button::getToggleState() method). If
  38932. 0 is passed-in here, then the normal image will be used instead, regardless
  38933. of the toggle state. The object that is passed-in here will be kept by
  38934. this object and will be deleted when no longer needed or when this button
  38935. is deleted.
  38936. */
  38937. ToolbarButton (int itemId,
  38938. const String& labelText,
  38939. Drawable* normalImage,
  38940. Drawable* toggledOnImage);
  38941. /** Destructor. */
  38942. ~ToolbarButton();
  38943. /** @internal */
  38944. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  38945. int& minSize, int& maxSize);
  38946. /** @internal */
  38947. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  38948. /** @internal */
  38949. void contentAreaChanged (const Rectangle<int>& newBounds);
  38950. /** @internal */
  38951. void buttonStateChanged();
  38952. /** @internal */
  38953. void resized();
  38954. /** @internal */
  38955. void enablementChanged();
  38956. private:
  38957. ScopedPointer<Drawable> normalImage, toggledOnImage;
  38958. Drawable* currentImage;
  38959. void updateDrawable();
  38960. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  38961. };
  38962. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38963. /*** End of inlined file: juce_ToolbarButton.h ***/
  38964. #endif
  38965. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38966. /*** Start of inlined file: juce_CodeDocument.h ***/
  38967. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38968. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  38969. class CodeDocumentLine;
  38970. /**
  38971. A class for storing and manipulating a source code file.
  38972. When using a CodeEditorComponent, it takes one of these as its source object.
  38973. The CodeDocument stores its content as an array of lines, which makes it
  38974. quick to insert and delete.
  38975. @see CodeEditorComponent
  38976. */
  38977. class JUCE_API CodeDocument
  38978. {
  38979. public:
  38980. /** Creates a new, empty document.
  38981. */
  38982. CodeDocument();
  38983. /** Destructor. */
  38984. ~CodeDocument();
  38985. /** A position in a code document.
  38986. Using this class you can find a position in a code document and quickly get its
  38987. character position, line, and index. By calling setPositionMaintained (true), the
  38988. position is automatically updated when text is inserted or deleted in the document,
  38989. so that it maintains its original place in the text.
  38990. */
  38991. class JUCE_API Position
  38992. {
  38993. public:
  38994. /** Creates an uninitialised postion.
  38995. Don't attempt to call any methods on this until you've given it an owner document
  38996. to refer to!
  38997. */
  38998. Position() throw();
  38999. /** Creates a position based on a line and index in a document.
  39000. Note that this index is NOT the column number, it's the number of characters from the
  39001. start of the line. The "column" number isn't quite the same, because if the line
  39002. contains any tab characters, the relationship of the index to its visual column depends on
  39003. the number of spaces per tab being used!
  39004. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  39005. they will be adjusted to keep them within its limits.
  39006. */
  39007. Position (const CodeDocument* ownerDocument,
  39008. int line, int indexInLine) throw();
  39009. /** Creates a position based on a character index in a document.
  39010. This position is placed at the specified number of characters from the start of the
  39011. document. The line and column are auto-calculated.
  39012. If the position is beyond the range of the document, it'll be adjusted to keep it
  39013. inside.
  39014. */
  39015. Position (const CodeDocument* ownerDocument,
  39016. int charactersFromStartOfDocument) throw();
  39017. /** Creates a copy of another position.
  39018. This will copy the position, but the new object will not be set to maintain its position,
  39019. even if the source object was set to do so.
  39020. */
  39021. Position (const Position& other) throw();
  39022. /** Destructor. */
  39023. ~Position();
  39024. Position& operator= (const Position& other);
  39025. bool operator== (const Position& other) const throw();
  39026. bool operator!= (const Position& other) const throw();
  39027. /** Points this object at a new position within the document.
  39028. If the position is beyond the range of the document, it'll be adjusted to keep it
  39029. inside.
  39030. @see getPosition, setLineAndIndex
  39031. */
  39032. void setPosition (int charactersFromStartOfDocument);
  39033. /** Returns the position as the number of characters from the start of the document.
  39034. @see setPosition, getLineNumber, getIndexInLine
  39035. */
  39036. int getPosition() const throw() { return characterPos; }
  39037. /** Moves the position to a new line and index within the line.
  39038. Note that the index is NOT the column at which the position appears in an editor.
  39039. If the line contains any tab characters, the relationship of the index to its
  39040. visual position depends on the number of spaces per tab being used!
  39041. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  39042. they will be adjusted to keep them within its limits.
  39043. */
  39044. void setLineAndIndex (int newLine, int newIndexInLine);
  39045. /** Returns the line number of this position.
  39046. The first line in the document is numbered zero, not one!
  39047. */
  39048. int getLineNumber() const throw() { return line; }
  39049. /** Returns the number of characters from the start of the line.
  39050. Note that this value is NOT the column at which the position appears in an editor.
  39051. If the line contains any tab characters, the relationship of the index to its
  39052. visual position depends on the number of spaces per tab being used!
  39053. */
  39054. int getIndexInLine() const throw() { return indexInLine; }
  39055. /** Allows the position to be automatically updated when the document changes.
  39056. If this is set to true, the positon will register with its document so that
  39057. when the document has text inserted or deleted, this position will be automatically
  39058. moved to keep it at the same position in the text.
  39059. */
  39060. void setPositionMaintained (bool isMaintained);
  39061. /** Moves the position forwards or backwards by the specified number of characters.
  39062. @see movedBy
  39063. */
  39064. void moveBy (int characterDelta);
  39065. /** Returns a position which is the same as this one, moved by the specified number of
  39066. characters.
  39067. @see moveBy
  39068. */
  39069. const Position movedBy (int characterDelta) const;
  39070. /** Returns a position which is the same as this one, moved up or down by the specified
  39071. number of lines.
  39072. @see movedBy
  39073. */
  39074. const Position movedByLines (int deltaLines) const;
  39075. /** Returns the character in the document at this position.
  39076. @see getLineText
  39077. */
  39078. const juce_wchar getCharacter() const;
  39079. /** Returns the line from the document that this position is within.
  39080. @see getCharacter, getLineNumber
  39081. */
  39082. const String getLineText() const;
  39083. private:
  39084. CodeDocument* owner;
  39085. int characterPos, line, indexInLine;
  39086. bool positionMaintained;
  39087. };
  39088. /** Returns the full text of the document. */
  39089. const String getAllContent() const;
  39090. /** Returns a section of the document's text. */
  39091. const String getTextBetween (const Position& start, const Position& end) const;
  39092. /** Returns a line from the document. */
  39093. const String getLine (int lineIndex) const throw();
  39094. /** Returns the number of characters in the document. */
  39095. int getNumCharacters() const throw();
  39096. /** Returns the number of lines in the document. */
  39097. int getNumLines() const throw() { return lines.size(); }
  39098. /** Returns the number of characters in the longest line of the document. */
  39099. int getMaximumLineLength() throw();
  39100. /** Deletes a section of the text.
  39101. This operation is undoable.
  39102. */
  39103. void deleteSection (const Position& startPosition, const Position& endPosition);
  39104. /** Inserts some text into the document at a given position.
  39105. This operation is undoable.
  39106. */
  39107. void insertText (const Position& position, const String& text);
  39108. /** Clears the document and replaces it with some new text.
  39109. This operation is undoable - if you're trying to completely reset the document, you
  39110. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  39111. */
  39112. void replaceAllContent (const String& newContent);
  39113. /** Replaces the editor's contents with the contents of a stream.
  39114. This will also reset the undo history and save point marker.
  39115. */
  39116. bool loadFromStream (InputStream& stream);
  39117. /** Writes the editor's current contents to a stream. */
  39118. bool writeToStream (OutputStream& stream);
  39119. /** Returns the preferred new-line characters for the document.
  39120. This will be either "\n", "\r\n", or (rarely) "\r".
  39121. @see setNewLineCharacters
  39122. */
  39123. const String getNewLineCharacters() const throw() { return newLineChars; }
  39124. /** Sets the new-line characters that the document should use.
  39125. The string must be either "\n", "\r\n", or (rarely) "\r".
  39126. @see getNewLineCharacters
  39127. */
  39128. void setNewLineCharacters (const String& newLine) throw();
  39129. /** Begins a new undo transaction.
  39130. The document itself will not call this internally, so relies on whatever is using the
  39131. document to periodically call this to break up the undo sequence into sensible chunks.
  39132. @see UndoManager::beginNewTransaction
  39133. */
  39134. void newTransaction();
  39135. /** Undo the last operation.
  39136. @see UndoManager::undo
  39137. */
  39138. void undo();
  39139. /** Redo the last operation.
  39140. @see UndoManager::redo
  39141. */
  39142. void redo();
  39143. /** Clears the undo history.
  39144. @see UndoManager::clearUndoHistory
  39145. */
  39146. void clearUndoHistory();
  39147. /** Returns the document's UndoManager */
  39148. UndoManager& getUndoManager() throw() { return undoManager; }
  39149. /** Makes a note that the document's current state matches the one that is saved.
  39150. After this has been called, hasChangedSinceSavePoint() will return false until
  39151. the document has been altered, and then it'll start returning true. If the document is
  39152. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  39153. will again return false.
  39154. @see hasChangedSinceSavePoint
  39155. */
  39156. void setSavePoint() throw();
  39157. /** Returns true if the state of the document differs from the state it was in when
  39158. setSavePoint() was last called.
  39159. @see setSavePoint
  39160. */
  39161. bool hasChangedSinceSavePoint() const throw();
  39162. /** Searches for a word-break. */
  39163. const Position findWordBreakAfter (const Position& position) const throw();
  39164. /** Searches for a word-break. */
  39165. const Position findWordBreakBefore (const Position& position) const throw();
  39166. /** An object that receives callbacks from the CodeDocument when its text changes.
  39167. @see CodeDocument::addListener, CodeDocument::removeListener
  39168. */
  39169. class JUCE_API Listener
  39170. {
  39171. public:
  39172. Listener() {}
  39173. virtual ~Listener() {}
  39174. /** Called by a CodeDocument when it is altered.
  39175. */
  39176. virtual void codeDocumentChanged (const Position& affectedTextStart,
  39177. const Position& affectedTextEnd) = 0;
  39178. };
  39179. /** Registers a listener object to receive callbacks when the document changes.
  39180. If the listener is already registered, this method has no effect.
  39181. @see removeListener
  39182. */
  39183. void addListener (Listener* listener) throw();
  39184. /** Deregisters a listener.
  39185. @see addListener
  39186. */
  39187. void removeListener (Listener* listener) throw();
  39188. /** Iterates the text in a CodeDocument.
  39189. This class lets you read characters from a CodeDocument. It's designed to be used
  39190. by a SyntaxAnalyser object.
  39191. @see CodeDocument, SyntaxAnalyser
  39192. */
  39193. class JUCE_API Iterator
  39194. {
  39195. public:
  39196. Iterator (CodeDocument* document);
  39197. Iterator (const Iterator& other);
  39198. Iterator& operator= (const Iterator& other) throw();
  39199. ~Iterator() throw();
  39200. /** Reads the next character and returns it.
  39201. @see peekNextChar
  39202. */
  39203. juce_wchar nextChar();
  39204. /** Reads the next character without advancing the current position. */
  39205. juce_wchar peekNextChar() const;
  39206. /** Advances the position by one character. */
  39207. void skip();
  39208. /** Returns the position of the next character as its position within the
  39209. whole document.
  39210. */
  39211. int getPosition() const throw() { return position; }
  39212. /** Skips over any whitespace characters until the next character is non-whitespace. */
  39213. void skipWhitespace();
  39214. /** Skips forward until the next character will be the first character on the next line */
  39215. void skipToEndOfLine();
  39216. /** Returns the line number of the next character. */
  39217. int getLine() const throw() { return line; }
  39218. /** Returns true if the iterator has reached the end of the document. */
  39219. bool isEOF() const throw();
  39220. private:
  39221. CodeDocument* document;
  39222. mutable String::CharPointerType charPointer;
  39223. int line, position;
  39224. };
  39225. private:
  39226. friend class CodeDocumentInsertAction;
  39227. friend class CodeDocumentDeleteAction;
  39228. friend class Iterator;
  39229. friend class Position;
  39230. OwnedArray <CodeDocumentLine> lines;
  39231. Array <Position*> positionsToMaintain;
  39232. UndoManager undoManager;
  39233. int currentActionIndex, indexOfSavedState;
  39234. int maximumLineLength;
  39235. ListenerList <Listener> listeners;
  39236. String newLineChars;
  39237. void sendListenerChangeMessage (int startLine, int endLine);
  39238. void insert (const String& text, int insertPos, bool undoable);
  39239. void remove (int startPos, int endPos, bool undoable);
  39240. void checkLastLineStatus();
  39241. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  39242. };
  39243. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  39244. /*** End of inlined file: juce_CodeDocument.h ***/
  39245. #endif
  39246. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39247. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  39248. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39249. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39250. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  39251. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39252. #define __JUCE_CODETOKENISER_JUCEHEADER__
  39253. /**
  39254. A base class for tokenising code so that the syntax can be displayed in a
  39255. code editor.
  39256. @see CodeDocument, CodeEditorComponent
  39257. */
  39258. class JUCE_API CodeTokeniser
  39259. {
  39260. public:
  39261. CodeTokeniser() {}
  39262. virtual ~CodeTokeniser() {}
  39263. /** Reads the next token from the source and returns its token type.
  39264. This must leave the source pointing to the first character in the
  39265. next token.
  39266. */
  39267. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  39268. /** Returns a list of the names of the token types this analyser uses.
  39269. The index in this list must match the token type numbers that are
  39270. returned by readNextToken().
  39271. */
  39272. virtual const StringArray getTokenTypes() = 0;
  39273. /** Returns a suggested syntax highlighting colour for a specified
  39274. token type.
  39275. */
  39276. virtual const Colour getDefaultColour (int tokenType) = 0;
  39277. private:
  39278. JUCE_LEAK_DETECTOR (CodeTokeniser);
  39279. };
  39280. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  39281. /*** End of inlined file: juce_CodeTokeniser.h ***/
  39282. /**
  39283. A text editor component designed specifically for source code.
  39284. This is designed to handle syntax highlighting and fast editing of very large
  39285. files.
  39286. */
  39287. class JUCE_API CodeEditorComponent : public Component,
  39288. public TextInputTarget,
  39289. public Timer,
  39290. public ScrollBar::Listener,
  39291. public CodeDocument::Listener,
  39292. public AsyncUpdater
  39293. {
  39294. public:
  39295. /** Creates an editor for a document.
  39296. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  39297. The object that you pass in is not owned or deleted by the editor - you must
  39298. make sure that it doesn't get deleted while this component is still using it.
  39299. @see CodeDocument
  39300. */
  39301. CodeEditorComponent (CodeDocument& document,
  39302. CodeTokeniser* codeTokeniser);
  39303. /** Destructor. */
  39304. ~CodeEditorComponent();
  39305. /** Returns the code document that this component is editing. */
  39306. CodeDocument& getDocument() const throw() { return document; }
  39307. /** Loads the given content into the document.
  39308. This will completely reset the CodeDocument object, clear its undo history,
  39309. and fill it with this text.
  39310. */
  39311. void loadContent (const String& newContent);
  39312. /** Returns the standard character width. */
  39313. float getCharWidth() const throw() { return charWidth; }
  39314. /** Returns the height of a line of text, in pixels. */
  39315. int getLineHeight() const throw() { return lineHeight; }
  39316. /** Returns the number of whole lines visible on the screen,
  39317. This doesn't include a cut-off line that might be visible at the bottom if the
  39318. component's height isn't an exact multiple of the line-height.
  39319. */
  39320. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  39321. /** Returns the number of whole columns visible on the screen.
  39322. This doesn't include any cut-off columns at the right-hand edge.
  39323. */
  39324. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  39325. /** Returns the current caret position. */
  39326. const CodeDocument::Position getCaretPos() const { return caretPos; }
  39327. /** Returns the position of the caret, relative to the editor's origin. */
  39328. const Rectangle<int> getCaretRectangle();
  39329. /** Moves the caret.
  39330. If selecting is true, the section of the document between the current
  39331. caret position and the new one will become selected. If false, any currently
  39332. selected region will be deselected.
  39333. */
  39334. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  39335. /** Returns the on-screen position of a character in the document.
  39336. The rectangle returned is relative to this component's top-left origin.
  39337. */
  39338. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  39339. /** Finds the character at a given on-screen position.
  39340. The co-ordinates are relative to this component's top-left origin.
  39341. */
  39342. const CodeDocument::Position getPositionAt (int x, int y);
  39343. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  39344. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  39345. void cursorDown (bool selecting);
  39346. void cursorUp (bool selecting);
  39347. void pageDown (bool selecting);
  39348. void pageUp (bool selecting);
  39349. void scrollDown();
  39350. void scrollUp();
  39351. void scrollToLine (int newFirstLineOnScreen);
  39352. void scrollBy (int deltaLines);
  39353. void scrollToColumn (int newFirstColumnOnScreen);
  39354. void scrollToKeepCaretOnScreen();
  39355. void goToStartOfDocument (bool selecting);
  39356. void goToStartOfLine (bool selecting);
  39357. void goToEndOfDocument (bool selecting);
  39358. void goToEndOfLine (bool selecting);
  39359. void deselectAll();
  39360. void selectAll();
  39361. void insertTextAtCaret (const String& textToInsert);
  39362. void insertTabAtCaret();
  39363. void cut();
  39364. void copy();
  39365. void copyThenCut();
  39366. void paste();
  39367. void backspace (bool moveInWholeWordSteps);
  39368. void deleteForward (bool moveInWholeWordSteps);
  39369. void undo();
  39370. void redo();
  39371. const Range<int> getHighlightedRegion() const;
  39372. void setHighlightedRegion (const Range<int>& newRange);
  39373. const String getTextInRange (const Range<int>& range) const;
  39374. /** Changes the current tab settings.
  39375. This lets you change the tab size and whether pressing the tab key inserts a
  39376. tab character, or its equivalent number of spaces.
  39377. */
  39378. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  39379. /** Returns the current number of spaces per tab.
  39380. @see setTabSize
  39381. */
  39382. int getTabSize() const throw() { return spacesPerTab; }
  39383. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  39384. @see setTabSize
  39385. */
  39386. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  39387. /** Changes the font.
  39388. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  39389. */
  39390. void setFont (const Font& newFont);
  39391. /** Returns the font that the editor is using. */
  39392. const Font& getFont() const throw() { return font; }
  39393. /** Resets the syntax highlighting colours to the default ones provided by the
  39394. code tokeniser.
  39395. @see CodeTokeniser::getDefaultColour
  39396. */
  39397. void resetToDefaultColours();
  39398. /** Changes one of the syntax highlighting colours.
  39399. The token type values are dependent on the tokeniser being used - use
  39400. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39401. @see getColourForTokenType
  39402. */
  39403. void setColourForTokenType (int tokenType, const Colour& colour);
  39404. /** Returns one of the syntax highlighting colours.
  39405. The token type values are dependent on the tokeniser being used - use
  39406. CodeTokeniser::getTokenTypes() to get a list of the token types.
  39407. @see setColourForTokenType
  39408. */
  39409. const Colour getColourForTokenType (int tokenType) const;
  39410. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  39411. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39412. methods.
  39413. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39414. */
  39415. enum ColourIds
  39416. {
  39417. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  39418. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  39419. selected text. */
  39420. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  39421. enabled. */
  39422. };
  39423. /** Changes the size of the scrollbars. */
  39424. void setScrollbarThickness (int thickness);
  39425. /** Returns the thickness of the scrollbars. */
  39426. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  39427. /** @internal */
  39428. void resized();
  39429. /** @internal */
  39430. void paint (Graphics& g);
  39431. /** @internal */
  39432. bool keyPressed (const KeyPress& key);
  39433. /** @internal */
  39434. void mouseDown (const MouseEvent& e);
  39435. /** @internal */
  39436. void mouseDrag (const MouseEvent& e);
  39437. /** @internal */
  39438. void mouseUp (const MouseEvent& e);
  39439. /** @internal */
  39440. void mouseDoubleClick (const MouseEvent& e);
  39441. /** @internal */
  39442. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39443. /** @internal */
  39444. void focusGained (FocusChangeType cause);
  39445. /** @internal */
  39446. void focusLost (FocusChangeType cause);
  39447. /** @internal */
  39448. void timerCallback();
  39449. /** @internal */
  39450. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  39451. /** @internal */
  39452. void handleAsyncUpdate();
  39453. /** @internal */
  39454. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  39455. const CodeDocument::Position& affectedTextEnd);
  39456. /** @internal */
  39457. bool isTextInputActive() const;
  39458. /** @internal */
  39459. void setTemporaryUnderlining (const Array <Range<int> >&);
  39460. private:
  39461. CodeDocument& document;
  39462. Font font;
  39463. int firstLineOnScreen, gutter, spacesPerTab;
  39464. float charWidth;
  39465. int lineHeight, linesOnScreen, columnsOnScreen;
  39466. int scrollbarThickness, columnToTryToMaintain;
  39467. bool useSpacesForTabs;
  39468. double xOffset;
  39469. CodeDocument::Position caretPos;
  39470. CodeDocument::Position selectionStart, selectionEnd;
  39471. ScopedPointer<CaretComponent> caret;
  39472. ScrollBar verticalScrollBar, horizontalScrollBar;
  39473. enum DragType
  39474. {
  39475. notDragging,
  39476. draggingSelectionStart,
  39477. draggingSelectionEnd
  39478. };
  39479. DragType dragType;
  39480. CodeTokeniser* codeTokeniser;
  39481. Array <Colour> coloursForTokenCategories;
  39482. class CodeEditorLine;
  39483. OwnedArray <CodeEditorLine> lines;
  39484. void rebuildLineTokens();
  39485. OwnedArray <CodeDocument::Iterator> cachedIterators;
  39486. void clearCachedIterators (int firstLineToBeInvalid);
  39487. void updateCachedIterators (int maxLineNum);
  39488. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  39489. void moveLineDelta (int delta, bool selecting);
  39490. void updateCaretPosition();
  39491. void updateScrollBars();
  39492. void scrollToLineInternal (int line);
  39493. void scrollToColumnInternal (double column);
  39494. void newTransaction();
  39495. int indexToColumn (int line, int index) const throw();
  39496. int columnToIndex (int line, int column) const throw();
  39497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  39498. };
  39499. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  39500. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  39501. #endif
  39502. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  39503. #endif
  39504. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39505. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39506. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39507. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39508. /**
  39509. A simple lexical analyser for syntax colouring of C++ code.
  39510. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  39511. */
  39512. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  39513. {
  39514. public:
  39515. CPlusPlusCodeTokeniser();
  39516. ~CPlusPlusCodeTokeniser();
  39517. enum TokenType
  39518. {
  39519. tokenType_error = 0,
  39520. tokenType_comment,
  39521. tokenType_builtInKeyword,
  39522. tokenType_identifier,
  39523. tokenType_integerLiteral,
  39524. tokenType_floatLiteral,
  39525. tokenType_stringLiteral,
  39526. tokenType_operator,
  39527. tokenType_bracket,
  39528. tokenType_punctuation,
  39529. tokenType_preprocessor
  39530. };
  39531. int readNextToken (CodeDocument::Iterator& source);
  39532. const StringArray getTokenTypes();
  39533. const Colour getDefaultColour (int tokenType);
  39534. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  39535. static bool isReservedKeyword (const String& token) throw();
  39536. private:
  39537. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  39538. };
  39539. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39540. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39541. #endif
  39542. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39543. #endif
  39544. #ifndef __JUCE_LABEL_JUCEHEADER__
  39545. #endif
  39546. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  39547. #endif
  39548. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  39549. /*** Start of inlined file: juce_ProgressBar.h ***/
  39550. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  39551. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  39552. /**
  39553. A progress bar component.
  39554. To use this, just create one and make it visible. It'll run its own timer
  39555. to keep an eye on a variable that you give it, and will automatically
  39556. redraw itself when the variable changes.
  39557. For an easy way of running a background task with a dialog box showing its
  39558. progress, see the ThreadWithProgressWindow class.
  39559. @see ThreadWithProgressWindow
  39560. */
  39561. class JUCE_API ProgressBar : public Component,
  39562. public SettableTooltipClient,
  39563. private Timer
  39564. {
  39565. public:
  39566. /** Creates a ProgressBar.
  39567. @param progress pass in a reference to a double that you're going to
  39568. update with your task's progress. The ProgressBar will
  39569. monitor the value of this variable and will redraw itself
  39570. when the value changes. The range is from 0 to 1.0. Obviously
  39571. you'd better be careful not to delete this variable while the
  39572. ProgressBar still exists!
  39573. */
  39574. explicit ProgressBar (double& progress);
  39575. /** Destructor. */
  39576. ~ProgressBar();
  39577. /** Turns the percentage display on or off.
  39578. By default this is on, and the progress bar will display a text string showing
  39579. its current percentage.
  39580. */
  39581. void setPercentageDisplay (bool shouldDisplayPercentage);
  39582. /** Gives the progress bar a string to display inside it.
  39583. If you call this, it will turn off the percentage display.
  39584. @see setPercentageDisplay
  39585. */
  39586. void setTextToDisplay (const String& text);
  39587. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  39588. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39589. methods.
  39590. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39591. */
  39592. enum ColourIds
  39593. {
  39594. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  39595. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  39596. classes will probably use variations on this colour. */
  39597. };
  39598. protected:
  39599. /** @internal */
  39600. void paint (Graphics& g);
  39601. /** @internal */
  39602. void lookAndFeelChanged();
  39603. /** @internal */
  39604. void visibilityChanged();
  39605. /** @internal */
  39606. void colourChanged();
  39607. private:
  39608. double& progress;
  39609. double currentValue;
  39610. bool displayPercentage;
  39611. String displayedMessage, currentMessage;
  39612. uint32 lastCallbackTime;
  39613. void timerCallback();
  39614. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  39615. };
  39616. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  39617. /*** End of inlined file: juce_ProgressBar.h ***/
  39618. #endif
  39619. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39620. /*** Start of inlined file: juce_Slider.h ***/
  39621. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39622. #define __JUCE_SLIDER_JUCEHEADER__
  39623. #if JUCE_VC6
  39624. #define Listener LabelListener
  39625. #endif
  39626. /**
  39627. A slider control for changing a value.
  39628. The slider can be horizontal, vertical, or rotary, and can optionally have
  39629. a text-box inside it to show an editable display of the current value.
  39630. To use it, create a Slider object and use the setSliderStyle() method
  39631. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  39632. To define the values that it can be set to, see the setRange() and setValue() methods.
  39633. There are also lots of custom tweaks you can do by subclassing and overriding
  39634. some of the virtual methods, such as changing the scaling, changing the format of
  39635. the text display, custom ways of limiting the values, etc.
  39636. You can register Slider::Listener objects with a slider, and they'll be called when
  39637. the value changes.
  39638. @see Slider::Listener
  39639. */
  39640. class JUCE_API Slider : public Component,
  39641. public SettableTooltipClient,
  39642. public AsyncUpdater,
  39643. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  39644. public LabelListener,
  39645. public ValueListener
  39646. {
  39647. public:
  39648. /** Creates a slider.
  39649. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  39650. setRange(), etc.
  39651. */
  39652. explicit Slider (const String& componentName = String::empty);
  39653. /** Destructor. */
  39654. ~Slider();
  39655. /** The types of slider available.
  39656. @see setSliderStyle, setRotaryParameters
  39657. */
  39658. enum SliderStyle
  39659. {
  39660. LinearHorizontal, /**< A traditional horizontal slider. */
  39661. LinearVertical, /**< A traditional vertical slider. */
  39662. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  39663. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  39664. @see setRotaryParameters */
  39665. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  39666. @see setRotaryParameters */
  39667. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  39668. @see setRotaryParameters */
  39669. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  39670. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39671. @see setMinValue, setMaxValue */
  39672. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39673. @see setMinValue, setMaxValue */
  39674. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  39675. value, with the current value being somewhere between them.
  39676. @see setMinValue, setMaxValue */
  39677. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  39678. value, with the current value being somewhere between them.
  39679. @see setMinValue, setMaxValue */
  39680. };
  39681. /** Changes the type of slider interface being used.
  39682. @param newStyle the type of interface
  39683. @see setRotaryParameters, setVelocityBasedMode,
  39684. */
  39685. void setSliderStyle (SliderStyle newStyle);
  39686. /** Returns the slider's current style.
  39687. @see setSliderStyle
  39688. */
  39689. SliderStyle getSliderStyle() const throw() { return style; }
  39690. /** Changes the properties of a rotary slider.
  39691. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  39692. the slider's minimum value is represented
  39693. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  39694. the slider's maximum value is represented. This must be
  39695. greater than startAngleRadians
  39696. @param stopAtEnd if true, then when the slider is dragged around past the
  39697. minimum or maximum, it'll stop there; if false, it'll wrap
  39698. back to the opposite value
  39699. */
  39700. void setRotaryParameters (float startAngleRadians,
  39701. float endAngleRadians,
  39702. bool stopAtEnd);
  39703. /** Sets the distance the mouse has to move to drag the slider across
  39704. the full extent of its range.
  39705. This only applies when in modes like RotaryHorizontalDrag, where it's using
  39706. relative mouse movements to adjust the slider.
  39707. */
  39708. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  39709. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  39710. int getMouseDragSensitivity() const throw() { return pixelsForFullDragExtent; }
  39711. /** Changes the way the the mouse is used when dragging the slider.
  39712. If true, this will turn on velocity-sensitive dragging, so that
  39713. the faster the mouse moves, the bigger the movement to the slider. This
  39714. helps when making accurate adjustments if the slider's range is quite large.
  39715. If false, the slider will just try to snap to wherever the mouse is.
  39716. */
  39717. void setVelocityBasedMode (bool isVelocityBased);
  39718. /** Returns true if velocity-based mode is active.
  39719. @see setVelocityBasedMode
  39720. */
  39721. bool getVelocityBasedMode() const throw() { return isVelocityBased; }
  39722. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  39723. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  39724. or if you're holding down ctrl.
  39725. @param sensitivity higher values than 1.0 increase the range of acceleration used
  39726. @param threshold the minimum number of pixels that the mouse needs to move for it
  39727. to be treated as a movement
  39728. @param offset values greater than 0.0 increase the minimum speed that will be used when
  39729. the threshold is reached
  39730. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  39731. key to toggle velocity-sensitive mode
  39732. */
  39733. void setVelocityModeParameters (double sensitivity = 1.0,
  39734. int threshold = 1,
  39735. double offset = 0.0,
  39736. bool userCanPressKeyToSwapMode = true);
  39737. /** Returns the velocity sensitivity setting.
  39738. @see setVelocityModeParameters
  39739. */
  39740. double getVelocitySensitivity() const throw() { return velocityModeSensitivity; }
  39741. /** Returns the velocity threshold setting.
  39742. @see setVelocityModeParameters
  39743. */
  39744. int getVelocityThreshold() const throw() { return velocityModeThreshold; }
  39745. /** Returns the velocity offset setting.
  39746. @see setVelocityModeParameters
  39747. */
  39748. double getVelocityOffset() const throw() { return velocityModeOffset; }
  39749. /** Returns the velocity user key setting.
  39750. @see setVelocityModeParameters
  39751. */
  39752. bool getVelocityModeIsSwappable() const throw() { return userKeyOverridesVelocity; }
  39753. /** Sets up a skew factor to alter the way values are distributed.
  39754. You may want to use a range of values on the slider where more accuracy
  39755. is required towards one end of the range, so this will logarithmically
  39756. spread the values across the length of the slider.
  39757. If the factor is < 1.0, the lower end of the range will fill more of the
  39758. slider's length; if the factor is > 1.0, the upper end of the range
  39759. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  39760. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  39761. method instead.
  39762. @see getSkewFactor, setSkewFactorFromMidPoint
  39763. */
  39764. void setSkewFactor (double factor);
  39765. /** Sets up a skew factor to alter the way values are distributed.
  39766. This allows you to specify the slider value that should appear in the
  39767. centre of the slider's visible range.
  39768. @see setSkewFactor, getSkewFactor
  39769. */
  39770. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  39771. /** Returns the current skew factor.
  39772. See setSkewFactor for more info.
  39773. @see setSkewFactor, setSkewFactorFromMidPoint
  39774. */
  39775. double getSkewFactor() const throw() { return skewFactor; }
  39776. /** Used by setIncDecButtonsMode().
  39777. */
  39778. enum IncDecButtonMode
  39779. {
  39780. incDecButtonsNotDraggable,
  39781. incDecButtonsDraggable_AutoDirection,
  39782. incDecButtonsDraggable_Horizontal,
  39783. incDecButtonsDraggable_Vertical
  39784. };
  39785. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  39786. can be dragged on the buttons to drag the values.
  39787. By default this is turned off. When enabled, clicking on the buttons still works
  39788. them as normal, but by holding down the mouse on a button and dragging it a little
  39789. distance, it flips into a mode where the value can be dragged. The drag direction can
  39790. either be set explicitly to be vertical or horizontal, or can be set to
  39791. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  39792. are side-by-side or above each other.
  39793. */
  39794. void setIncDecButtonsMode (IncDecButtonMode mode);
  39795. /** The position of the slider's text-entry box.
  39796. @see setTextBoxStyle
  39797. */
  39798. enum TextEntryBoxPosition
  39799. {
  39800. NoTextBox, /**< Doesn't display a text box. */
  39801. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  39802. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  39803. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  39804. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  39805. };
  39806. /** Changes the location and properties of the text-entry box.
  39807. @param newPosition where it should go (or NoTextBox to not have one at all)
  39808. @param isReadOnly if true, it's a read-only display
  39809. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  39810. room for the slider as well!
  39811. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  39812. room for the slider as well!
  39813. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  39814. */
  39815. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  39816. bool isReadOnly,
  39817. int textEntryBoxWidth,
  39818. int textEntryBoxHeight);
  39819. /** Returns the status of the text-box.
  39820. @see setTextBoxStyle
  39821. */
  39822. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  39823. /** Returns the width used for the text-box.
  39824. @see setTextBoxStyle
  39825. */
  39826. int getTextBoxWidth() const throw() { return textBoxWidth; }
  39827. /** Returns the height used for the text-box.
  39828. @see setTextBoxStyle
  39829. */
  39830. int getTextBoxHeight() const throw() { return textBoxHeight; }
  39831. /** Makes the text-box editable.
  39832. By default this is true, and the user can enter values into the textbox,
  39833. but it can be turned off if that's not suitable.
  39834. @see setTextBoxStyle, getValueFromText, getTextFromValue
  39835. */
  39836. void setTextBoxIsEditable (bool shouldBeEditable);
  39837. /** Returns true if the text-box is read-only.
  39838. @see setTextBoxStyle
  39839. */
  39840. bool isTextBoxEditable() const { return editableText; }
  39841. /** If the text-box is editable, this will give it the focus so that the user can
  39842. type directly into it.
  39843. This is basically the effect as the user clicking on it.
  39844. */
  39845. void showTextBox();
  39846. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  39847. focus away from it.
  39848. @param discardCurrentEditorContents if true, the slider's value will be left
  39849. unchanged; if false, the current contents of the
  39850. text editor will be used to set the slider position
  39851. before it is hidden.
  39852. */
  39853. void hideTextBox (bool discardCurrentEditorContents);
  39854. /** Changes the slider's current value.
  39855. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39856. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39857. want to handle it.
  39858. @param newValue the new value to set - this will be restricted by the
  39859. minimum and maximum range, and will be snapped to the
  39860. nearest interval if one has been set
  39861. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39862. any Slider::Listeners or the valueChanged() method
  39863. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39864. synchronously; if false, it will be asynchronous
  39865. */
  39866. void setValue (double newValue,
  39867. bool sendUpdateMessage = true,
  39868. bool sendMessageSynchronously = false);
  39869. /** Returns the slider's current value. */
  39870. double getValue() const;
  39871. /** Returns the Value object that represents the slider's current position.
  39872. You can use this Value object to connect the slider's position to external values or setters,
  39873. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39874. your own Value object.
  39875. @see Value, getMaxValue, getMinValueObject
  39876. */
  39877. Value& getValueObject() { return currentValue; }
  39878. /** Sets the limits that the slider's value can take.
  39879. @param newMinimum the lowest value allowed
  39880. @param newMaximum the highest value allowed
  39881. @param newInterval the steps in which the value is allowed to increase - if this
  39882. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  39883. */
  39884. void setRange (double newMinimum,
  39885. double newMaximum,
  39886. double newInterval = 0);
  39887. /** Returns the current maximum value.
  39888. @see setRange
  39889. */
  39890. double getMaximum() const { return maximum; }
  39891. /** Returns the current minimum value.
  39892. @see setRange
  39893. */
  39894. double getMinimum() const { return minimum; }
  39895. /** Returns the current step-size for values.
  39896. @see setRange
  39897. */
  39898. double getInterval() const { return interval; }
  39899. /** For a slider with two or three thumbs, this returns the lower of its values.
  39900. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  39901. A slider with three values also uses the normal getValue() and setValue() methods to
  39902. control the middle value.
  39903. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  39904. */
  39905. double getMinValue() const;
  39906. /** For a slider with two or three thumbs, this returns the lower of its values.
  39907. You can use this Value object to connect the slider's position to external values or setters,
  39908. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39909. your own Value object.
  39910. @see Value, getMinValue, getMaxValueObject
  39911. */
  39912. Value& getMinValueObject() throw() { return valueMin; }
  39913. /** For a slider with two or three thumbs, this sets the lower of its values.
  39914. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39915. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39916. want to handle it.
  39917. @param newValue the new value to set - this will be restricted by the
  39918. minimum and maximum range, and will be snapped to the nearest
  39919. interval if one has been set.
  39920. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39921. any Slider::Listeners or the valueChanged() method
  39922. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39923. synchronously; if false, it will be asynchronous
  39924. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  39925. max value (in a two-value slider) or the mid value (in a three-value
  39926. slider). If false, then if this value goes beyond those values,
  39927. it will push them along with it.
  39928. @see getMinValue, setMaxValue, setValue
  39929. */
  39930. void setMinValue (double newValue,
  39931. bool sendUpdateMessage = true,
  39932. bool sendMessageSynchronously = false,
  39933. bool allowNudgingOfOtherValues = false);
  39934. /** For a slider with two or three thumbs, this returns the higher of its values.
  39935. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  39936. A slider with three values also uses the normal getValue() and setValue() methods to
  39937. control the middle value.
  39938. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  39939. */
  39940. double getMaxValue() const;
  39941. /** For a slider with two or three thumbs, this returns the higher of its values.
  39942. You can use this Value object to connect the slider's position to external values or setters,
  39943. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39944. your own Value object.
  39945. @see Value, getMaxValue, getMinValueObject
  39946. */
  39947. Value& getMaxValueObject() throw() { return valueMax; }
  39948. /** For a slider with two or three thumbs, this sets the lower of its values.
  39949. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39950. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39951. want to handle it.
  39952. @param newValue the new value to set - this will be restricted by the
  39953. minimum and maximum range, and will be snapped to the nearest
  39954. interval if one has been set.
  39955. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39956. any Slider::Listeners or the valueChanged() method
  39957. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39958. synchronously; if false, it will be asynchronous
  39959. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  39960. min value (in a two-value slider) or the mid value (in a three-value
  39961. slider). If false, then if this value goes beyond those values,
  39962. it will push them along with it.
  39963. @see getMaxValue, setMinValue, setValue
  39964. */
  39965. void setMaxValue (double newValue,
  39966. bool sendUpdateMessage = true,
  39967. bool sendMessageSynchronously = false,
  39968. bool allowNudgingOfOtherValues = false);
  39969. /** For a slider with two or three thumbs, this sets the minimum and maximum thumb positions.
  39970. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39971. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39972. want to handle it.
  39973. @param newMinValue the new minimum value to set - this will be snapped to the
  39974. nearest interval if one has been set.
  39975. @param newMaxValue the new minimum value to set - this will be snapped to the
  39976. nearest interval if one has been set.
  39977. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39978. any Slider::Listeners or the valueChanged() method
  39979. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39980. synchronously; if false, it will be asynchronous
  39981. @see setMaxValue, setMinValue, setValue
  39982. */
  39983. void setMinAndMaxValues (double newMinValue, double newMaxValue,
  39984. bool sendUpdateMessage = true,
  39985. bool sendMessageSynchronously = false);
  39986. /** A class for receiving callbacks from a Slider.
  39987. To be told when a slider's value changes, you can register a Slider::Listener
  39988. object using Slider::addListener().
  39989. @see Slider::addListener, Slider::removeListener
  39990. */
  39991. class JUCE_API Listener
  39992. {
  39993. public:
  39994. /** Destructor. */
  39995. virtual ~Listener() {}
  39996. /** Called when the slider's value is changed.
  39997. This may be caused by dragging it, or by typing in its text entry box,
  39998. or by a call to Slider::setValue().
  39999. You can find out the new value using Slider::getValue().
  40000. @see Slider::valueChanged
  40001. */
  40002. virtual void sliderValueChanged (Slider* slider) = 0;
  40003. /** Called when the slider is about to be dragged.
  40004. This is called when a drag begins, then it's followed by multiple calls
  40005. to sliderValueChanged(), and then sliderDragEnded() is called after the
  40006. user lets go.
  40007. @see sliderDragEnded, Slider::startedDragging
  40008. */
  40009. virtual void sliderDragStarted (Slider* slider);
  40010. /** Called after a drag operation has finished.
  40011. @see sliderDragStarted, Slider::stoppedDragging
  40012. */
  40013. virtual void sliderDragEnded (Slider* slider);
  40014. };
  40015. /** Adds a listener to be called when this slider's value changes. */
  40016. void addListener (Listener* listener);
  40017. /** Removes a previously-registered listener. */
  40018. void removeListener (Listener* listener);
  40019. /** This lets you choose whether double-clicking moves the slider to a given position.
  40020. By default this is turned off, but it's handy if you want a double-click to act
  40021. as a quick way of resetting a slider. Just pass in the value you want it to
  40022. go to when double-clicked.
  40023. @see getDoubleClickReturnValue
  40024. */
  40025. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  40026. double valueToSetOnDoubleClick);
  40027. /** Returns the values last set by setDoubleClickReturnValue() method.
  40028. Sets isEnabled to true if double-click is enabled, and returns the value
  40029. that was set.
  40030. @see setDoubleClickReturnValue
  40031. */
  40032. double getDoubleClickReturnValue (bool& isEnabled) const;
  40033. /** Tells the slider whether to keep sending change messages while the user
  40034. is dragging the slider.
  40035. If set to true, a change message will only be sent when the user has
  40036. dragged the slider and let go. If set to false (the default), then messages
  40037. will be continuously sent as they drag it while the mouse button is still
  40038. held down.
  40039. */
  40040. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  40041. /** This lets you change whether the slider thumb jumps to the mouse position
  40042. when you click.
  40043. By default, this is true. If it's false, then the slider moves with relative
  40044. motion when you drag it.
  40045. This only applies to linear bars, and won't affect two- or three- value
  40046. sliders.
  40047. */
  40048. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  40049. /** If enabled, this gives the slider a pop-up bubble which appears while the
  40050. slider is being dragged.
  40051. This can be handy if your slider doesn't have a text-box, so that users can
  40052. see the value just when they're changing it.
  40053. If you pass a component as the parentComponentToUse parameter, the pop-up
  40054. bubble will be added as a child of that component when it's needed. If you
  40055. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  40056. transparent window, so if you're using an OS that can't do transparent windows
  40057. you'll have to add it to a parent component instead).
  40058. */
  40059. void setPopupDisplayEnabled (bool isEnabled,
  40060. Component* parentComponentToUse);
  40061. /** If this is set to true, then right-clicking on the slider will pop-up
  40062. a menu to let the user change the way it works.
  40063. By default this is turned off, but when turned on, the menu will include
  40064. things like velocity sensitivity, and for rotary sliders, whether they
  40065. use a linear or rotary mouse-drag to move them.
  40066. */
  40067. void setPopupMenuEnabled (bool menuEnabled);
  40068. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  40069. By default it's enabled.
  40070. */
  40071. void setScrollWheelEnabled (bool enabled);
  40072. /** Returns a number to indicate which thumb is currently being dragged by the
  40073. mouse.
  40074. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  40075. the maximum-value thumb, or -1 if none is currently down.
  40076. */
  40077. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  40078. /** Callback to indicate that the user is about to start dragging the slider.
  40079. @see Slider::Listener::sliderDragStarted
  40080. */
  40081. virtual void startedDragging();
  40082. /** Callback to indicate that the user has just stopped dragging the slider.
  40083. @see Slider::Listener::sliderDragEnded
  40084. */
  40085. virtual void stoppedDragging();
  40086. /** Callback to indicate that the user has just moved the slider.
  40087. @see Slider::Listener::sliderValueChanged
  40088. */
  40089. virtual void valueChanged();
  40090. /** Subclasses can override this to convert a text string to a value.
  40091. When the user enters something into the text-entry box, this method is
  40092. called to convert it to a value.
  40093. The default routine just tries to convert it to a double.
  40094. @see getTextFromValue
  40095. */
  40096. virtual double getValueFromText (const String& text);
  40097. /** Turns the slider's current value into a text string.
  40098. Subclasses can override this to customise the formatting of the text-entry box.
  40099. The default implementation just turns the value into a string, using
  40100. a number of decimal places based on the range interval. If a suffix string
  40101. has been set using setTextValueSuffix(), this will be appended to the text.
  40102. @see getValueFromText
  40103. */
  40104. virtual const String getTextFromValue (double value);
  40105. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  40106. a string.
  40107. This is used by the default implementation of getTextFromValue(), and is just
  40108. appended to the numeric value. For more advanced formatting, you can override
  40109. getTextFromValue() and do something else.
  40110. */
  40111. void setTextValueSuffix (const String& suffix);
  40112. /** Returns the suffix that was set by setTextValueSuffix(). */
  40113. const String getTextValueSuffix() const;
  40114. /** Allows a user-defined mapping of distance along the slider to its value.
  40115. The default implementation for this performs the skewing operation that
  40116. can be set up in the setSkewFactor() method. Override it if you need
  40117. some kind of custom mapping instead, but make sure you also implement the
  40118. inverse function in valueToProportionOfLength().
  40119. @param proportion a value 0 to 1.0, indicating a distance along the slider
  40120. @returns the slider value that is represented by this position
  40121. @see valueToProportionOfLength
  40122. */
  40123. virtual double proportionOfLengthToValue (double proportion);
  40124. /** Allows a user-defined mapping of value to the position of the slider along its length.
  40125. The default implementation for this performs the skewing operation that
  40126. can be set up in the setSkewFactor() method. Override it if you need
  40127. some kind of custom mapping instead, but make sure you also implement the
  40128. inverse function in proportionOfLengthToValue().
  40129. @param value a valid slider value, between the range of values specified in
  40130. setRange()
  40131. @returns a value 0 to 1.0 indicating the distance along the slider that
  40132. represents this value
  40133. @see proportionOfLengthToValue
  40134. */
  40135. virtual double valueToProportionOfLength (double value);
  40136. /** Returns the X or Y coordinate of a value along the slider's length.
  40137. If the slider is horizontal, this will be the X coordinate of the given
  40138. value, relative to the left of the slider. If it's vertical, then this will
  40139. be the Y coordinate, relative to the top of the slider.
  40140. If the slider is rotary, this will throw an assertion and return 0. If the
  40141. value is out-of-range, it will be constrained to the length of the slider.
  40142. */
  40143. float getPositionOfValue (double value);
  40144. /** This can be overridden to allow the slider to snap to user-definable values.
  40145. If overridden, it will be called when the user tries to move the slider to
  40146. a given position, and allows a subclass to sanity-check this value, possibly
  40147. returning a different value to use instead.
  40148. @param attemptedValue the value the user is trying to enter
  40149. @param userIsDragging true if the user is dragging with the mouse; false if
  40150. they are entering the value using the text box
  40151. @returns the value to use instead
  40152. */
  40153. virtual double snapValue (double attemptedValue, bool userIsDragging);
  40154. /** This can be called to force the text box to update its contents.
  40155. (Not normally needed, as this is done automatically).
  40156. */
  40157. void updateText();
  40158. /** True if the slider moves horizontally. */
  40159. bool isHorizontal() const;
  40160. /** True if the slider moves vertically. */
  40161. bool isVertical() const;
  40162. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  40163. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40164. methods.
  40165. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40166. */
  40167. enum ColourIds
  40168. {
  40169. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  40170. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  40171. and feel class how this is used. */
  40172. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  40173. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  40174. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  40175. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  40176. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  40177. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  40178. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  40179. };
  40180. protected:
  40181. /** @internal */
  40182. void labelTextChanged (Label*);
  40183. /** @internal */
  40184. void paint (Graphics& g);
  40185. /** @internal */
  40186. void resized();
  40187. /** @internal */
  40188. void mouseDown (const MouseEvent& e);
  40189. /** @internal */
  40190. void mouseUp (const MouseEvent& e);
  40191. /** @internal */
  40192. void mouseDrag (const MouseEvent& e);
  40193. /** @internal */
  40194. void mouseDoubleClick (const MouseEvent& e);
  40195. /** @internal */
  40196. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  40197. /** @internal */
  40198. void modifierKeysChanged (const ModifierKeys& modifiers);
  40199. /** @internal */
  40200. void buttonClicked (Button* button);
  40201. /** @internal */
  40202. void lookAndFeelChanged();
  40203. /** @internal */
  40204. void enablementChanged();
  40205. /** @internal */
  40206. void focusOfChildComponentChanged (FocusChangeType cause);
  40207. /** @internal */
  40208. void handleAsyncUpdate();
  40209. /** @internal */
  40210. void colourChanged();
  40211. /** @internal */
  40212. void valueChanged (Value& value);
  40213. /** Returns the best number of decimal places to use when displaying numbers.
  40214. This is calculated from the slider's interval setting.
  40215. */
  40216. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  40217. private:
  40218. ListenerList <Listener> listeners;
  40219. Value currentValue, valueMin, valueMax;
  40220. double lastCurrentValue, lastValueMin, lastValueMax;
  40221. double minimum, maximum, interval, doubleClickReturnValue;
  40222. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  40223. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  40224. int velocityModeThreshold;
  40225. float rotaryStart, rotaryEnd;
  40226. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  40227. int mouseDragStartX, mouseDragStartY;
  40228. int sliderRegionStart, sliderRegionSize;
  40229. int sliderBeingDragged;
  40230. int pixelsForFullDragExtent;
  40231. Rectangle<int> sliderRect;
  40232. String textSuffix;
  40233. SliderStyle style;
  40234. TextEntryBoxPosition textBoxPos;
  40235. int textBoxWidth, textBoxHeight;
  40236. IncDecButtonMode incDecButtonMode;
  40237. bool editableText : 1, doubleClickToValue : 1;
  40238. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  40239. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  40240. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  40241. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  40242. ScopedPointer<Label> valueBox;
  40243. ScopedPointer<Button> incButton, decButton;
  40244. class PopupDisplayComponent;
  40245. friend class PopupDisplayComponent;
  40246. friend class ScopedPointer <PopupDisplayComponent>;
  40247. ScopedPointer <PopupDisplayComponent> popupDisplay;
  40248. Component* parentForPopupDisplay;
  40249. float getLinearSliderPos (double value);
  40250. void restoreMouseIfHidden();
  40251. void sendDragStart();
  40252. void sendDragEnd();
  40253. double constrainedValue (double value) const;
  40254. void triggerChangeMessage (bool synchronous);
  40255. bool incDecDragDirectionIsHorizontal() const;
  40256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  40257. };
  40258. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  40259. typedef Slider::Listener SliderListener;
  40260. #if JUCE_VC6
  40261. #undef Listener
  40262. #endif
  40263. #endif // __JUCE_SLIDER_JUCEHEADER__
  40264. /*** End of inlined file: juce_Slider.h ***/
  40265. #endif
  40266. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40267. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  40268. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40269. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40270. /**
  40271. A component that displays a strip of column headings for a table, and allows these
  40272. to be resized, dragged around, etc.
  40273. This is just the component that goes at the top of a table. You can use it
  40274. directly for custom components, or to create a simple table, use the
  40275. TableListBox class.
  40276. To use one of these, create it and use addColumn() to add all the columns that you need.
  40277. Each column must be given a unique ID number that's used to refer to it.
  40278. @see TableListBox, TableHeaderComponent::Listener
  40279. */
  40280. class JUCE_API TableHeaderComponent : public Component,
  40281. private AsyncUpdater
  40282. {
  40283. public:
  40284. /** Creates an empty table header.
  40285. */
  40286. TableHeaderComponent();
  40287. /** Destructor. */
  40288. ~TableHeaderComponent();
  40289. /** A combination of these flags are passed into the addColumn() method to specify
  40290. the properties of a column.
  40291. */
  40292. enum ColumnPropertyFlags
  40293. {
  40294. 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. */
  40295. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  40296. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  40297. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  40298. 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. */
  40299. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  40300. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  40301. /** This set of default flags is used as the default parameter value in addColumn(). */
  40302. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  40303. /** A quick way of combining flags for a column that's not resizable. */
  40304. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  40305. /** A quick way of combining flags for a column that's not resizable or sortable. */
  40306. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  40307. /** A quick way of combining flags for a column that's not sortable. */
  40308. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  40309. };
  40310. /** Adds a column to the table.
  40311. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  40312. registered listeners.
  40313. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  40314. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  40315. a unique ID. This is used to identify the column later on, after the user may have
  40316. changed the order that they appear in
  40317. @param width the initial width of the column, in pixels
  40318. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  40319. if the 'resizable' flag is specified for this column
  40320. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  40321. if the 'resizable' flag is specified for this column
  40322. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  40323. properties of this column
  40324. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  40325. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  40326. all columns, not just the index amongst those that are currently visible
  40327. */
  40328. void addColumn (const String& columnName,
  40329. int columnId,
  40330. int width,
  40331. int minimumWidth = 30,
  40332. int maximumWidth = -1,
  40333. int propertyFlags = defaultFlags,
  40334. int insertIndex = -1);
  40335. /** Removes a column with the given ID.
  40336. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  40337. registered listeners.
  40338. */
  40339. void removeColumn (int columnIdToRemove);
  40340. /** Deletes all columns from the table.
  40341. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  40342. registered listeners.
  40343. */
  40344. void removeAllColumns();
  40345. /** Returns the number of columns in the table.
  40346. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  40347. return the total number of columns, including hidden ones.
  40348. @see isColumnVisible
  40349. */
  40350. int getNumColumns (bool onlyCountVisibleColumns) const;
  40351. /** Returns the name for a column.
  40352. @see setColumnName
  40353. */
  40354. const String getColumnName (int columnId) const;
  40355. /** Changes the name of a column. */
  40356. void setColumnName (int columnId, const String& newName);
  40357. /** Moves a column to a different index in the table.
  40358. @param columnId the column to move
  40359. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  40360. */
  40361. void moveColumn (int columnId, int newVisibleIndex);
  40362. /** Returns the width of one of the columns.
  40363. */
  40364. int getColumnWidth (int columnId) const;
  40365. /** Changes the width of a column.
  40366. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  40367. */
  40368. void setColumnWidth (int columnId, int newWidth);
  40369. /** Shows or hides a column.
  40370. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  40371. @see isColumnVisible
  40372. */
  40373. void setColumnVisible (int columnId, bool shouldBeVisible);
  40374. /** Returns true if this column is currently visible.
  40375. @see setColumnVisible
  40376. */
  40377. bool isColumnVisible (int columnId) const;
  40378. /** Changes the column which is the sort column.
  40379. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  40380. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  40381. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  40382. @see getSortColumnId, isSortedForwards, reSortTable
  40383. */
  40384. void setSortColumnId (int columnId, bool sortForwards);
  40385. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  40386. @see setSortColumnId, isSortedForwards
  40387. */
  40388. int getSortColumnId() const;
  40389. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  40390. @see setSortColumnId
  40391. */
  40392. bool isSortedForwards() const;
  40393. /** Triggers a re-sort of the table according to the current sort-column.
  40394. If you modifiy the table's contents, you can call this to signal that the table needs
  40395. to be re-sorted.
  40396. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  40397. tableSortOrderChanged() method of any listeners).
  40398. */
  40399. void reSortTable();
  40400. /** Returns the total width of all the visible columns in the table.
  40401. */
  40402. int getTotalWidth() const;
  40403. /** Returns the index of a given column.
  40404. If there's no such column ID, this will return -1.
  40405. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  40406. otherwise it'll return the index amongst all the columns, including any hidden ones.
  40407. */
  40408. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  40409. /** Returns the ID of the column at a given index.
  40410. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  40411. otherwise it'll count it amongst all the columns, including any hidden ones.
  40412. If the index is out-of-range, it'll return 0.
  40413. */
  40414. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  40415. /** Returns the rectangle containing of one of the columns.
  40416. The index is an index from 0 to the number of columns that are currently visible (hidden
  40417. ones are not counted). It returns a rectangle showing the position of the column relative
  40418. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  40419. */
  40420. const Rectangle<int> getColumnPosition (int index) const;
  40421. /** Finds the column ID at a given x-position in the component.
  40422. If there is a column at this point this returns its ID, or if not, it will return 0.
  40423. */
  40424. int getColumnIdAtX (int xToFind) const;
  40425. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  40426. entire width of the component.
  40427. By default this is disabled. Turning it on also means that when resizing a column, those
  40428. on the right will be squashed to fit.
  40429. */
  40430. void setStretchToFitActive (bool shouldStretchToFit);
  40431. /** Returns true if stretch-to-fit has been enabled.
  40432. @see setStretchToFitActive
  40433. */
  40434. bool isStretchToFitActive() const;
  40435. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  40436. specified width, keeping their relative proportions the same.
  40437. If the minimum widths of the columns are too wide to fit into this space, it may
  40438. actually end up wider.
  40439. */
  40440. void resizeAllColumnsToFit (int targetTotalWidth);
  40441. /** Enables or disables the pop-up menu.
  40442. The default menu allows the user to show or hide columns. You can add custom
  40443. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  40444. By default the menu is enabled.
  40445. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  40446. */
  40447. void setPopupMenuActive (bool hasMenu);
  40448. /** Returns true if the pop-up menu is enabled.
  40449. @see setPopupMenuActive
  40450. */
  40451. bool isPopupMenuActive() const;
  40452. /** Returns a string that encapsulates the table's current layout.
  40453. This can be restored later using restoreFromString(). It saves the order of
  40454. the columns, the currently-sorted column, and the widths.
  40455. @see restoreFromString
  40456. */
  40457. const String toString() const;
  40458. /** Restores the state of the table, based on a string previously created with
  40459. toString().
  40460. @see toString
  40461. */
  40462. void restoreFromString (const String& storedVersion);
  40463. /**
  40464. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  40465. You can register one of these objects for table events using TableHeaderComponent::addListener()
  40466. and TableHeaderComponent::removeListener().
  40467. @see TableHeaderComponent
  40468. */
  40469. class JUCE_API Listener
  40470. {
  40471. public:
  40472. Listener() {}
  40473. /** Destructor. */
  40474. virtual ~Listener() {}
  40475. /** This is called when some of the table's columns are added, removed, hidden,
  40476. or rearranged.
  40477. */
  40478. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  40479. /** This is called when one or more of the table's columns are resized.
  40480. */
  40481. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  40482. /** This is called when the column by which the table should be sorted is changed.
  40483. */
  40484. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  40485. /** This is called when the user begins or ends dragging one of the columns around.
  40486. When the user starts dragging a column, this is called with the ID of that
  40487. column. When they finish dragging, it is called again with 0 as the ID.
  40488. */
  40489. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  40490. int columnIdNowBeingDragged);
  40491. };
  40492. /** Adds a listener to be informed about things that happen to the header. */
  40493. void addListener (Listener* newListener);
  40494. /** Removes a previously-registered listener. */
  40495. void removeListener (Listener* listenerToRemove);
  40496. /** This can be overridden to handle a mouse-click on one of the column headers.
  40497. The default implementation will use this click to call getSortColumnId() and
  40498. change the sort order.
  40499. */
  40500. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  40501. /** This can be overridden to add custom items to the pop-up menu.
  40502. If you override this, you should call the superclass's method to add its
  40503. column show/hide items, if you want them on the menu as well.
  40504. Then to handle the result, override reactToMenuItem().
  40505. @see reactToMenuItem
  40506. */
  40507. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  40508. /** Override this to handle any custom items that you have added to the
  40509. pop-up menu with an addMenuItems() override.
  40510. If the menuReturnId isn't one of your own custom menu items, you'll need to
  40511. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  40512. handle the items that it had added.
  40513. @see addMenuItems
  40514. */
  40515. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  40516. /** @internal */
  40517. void paint (Graphics& g);
  40518. /** @internal */
  40519. void resized();
  40520. /** @internal */
  40521. void mouseMove (const MouseEvent&);
  40522. /** @internal */
  40523. void mouseEnter (const MouseEvent&);
  40524. /** @internal */
  40525. void mouseExit (const MouseEvent&);
  40526. /** @internal */
  40527. void mouseDown (const MouseEvent&);
  40528. /** @internal */
  40529. void mouseDrag (const MouseEvent&);
  40530. /** @internal */
  40531. void mouseUp (const MouseEvent&);
  40532. /** @internal */
  40533. const MouseCursor getMouseCursor();
  40534. /** Can be overridden for more control over the pop-up menu behaviour. */
  40535. virtual void showColumnChooserMenu (int columnIdClicked);
  40536. private:
  40537. struct ColumnInfo
  40538. {
  40539. String name;
  40540. int id, propertyFlags, width, minimumWidth, maximumWidth;
  40541. double lastDeliberateWidth;
  40542. bool isVisible() const;
  40543. };
  40544. OwnedArray <ColumnInfo> columns;
  40545. Array <Listener*> listeners;
  40546. ScopedPointer <Component> dragOverlayComp;
  40547. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  40548. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  40549. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  40550. ColumnInfo* getInfoForId (int columnId) const;
  40551. int visibleIndexToTotalIndex (int visibleIndex) const;
  40552. void sendColumnsChanged();
  40553. void handleAsyncUpdate();
  40554. void beginDrag (const MouseEvent&);
  40555. void endDrag (int finalIndex);
  40556. int getResizeDraggerAt (int mouseX) const;
  40557. void updateColumnUnderMouse (int x, int y);
  40558. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  40559. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  40560. };
  40561. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  40562. typedef TableHeaderComponent::Listener TableHeaderListener;
  40563. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40564. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  40565. #endif
  40566. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40567. /*** Start of inlined file: juce_TableListBox.h ***/
  40568. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40569. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  40570. /**
  40571. One of these is used by a TableListBox as the data model for the table's contents.
  40572. The virtual methods that you override in this class take care of drawing the
  40573. table cells, and reacting to events.
  40574. @see TableListBox
  40575. */
  40576. class JUCE_API TableListBoxModel
  40577. {
  40578. public:
  40579. TableListBoxModel() {}
  40580. /** Destructor. */
  40581. virtual ~TableListBoxModel() {}
  40582. /** This must return the number of rows currently in the table.
  40583. If the number of rows changes, you must call TableListBox::updateContent() to
  40584. cause it to refresh the list.
  40585. */
  40586. virtual int getNumRows() = 0;
  40587. /** This must draw the background behind one of the rows in the table.
  40588. The graphics context has its origin at the row's top-left, and your method
  40589. should fill the area specified by the width and height parameters.
  40590. */
  40591. virtual void paintRowBackground (Graphics& g,
  40592. int rowNumber,
  40593. int width, int height,
  40594. bool rowIsSelected) = 0;
  40595. /** This must draw one of the cells.
  40596. The graphics context's origin will already be set to the top-left of the cell,
  40597. whose size is specified by (width, height).
  40598. */
  40599. virtual void paintCell (Graphics& g,
  40600. int rowNumber,
  40601. int columnId,
  40602. int width, int height,
  40603. bool rowIsSelected) = 0;
  40604. /** This is used to create or update a custom component to go in a cell.
  40605. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  40606. and handle mouse clicks with cellClicked().
  40607. This method will be called whenever a custom component might need to be updated - e.g.
  40608. when the table is changed, or TableListBox::updateContent() is called.
  40609. If you don't need a custom component for the specified cell, then return 0.
  40610. If you do want a custom component, and the existingComponentToUpdate is null, then
  40611. this method must create a new component suitable for the cell, and return it.
  40612. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  40613. by this method. In this case, the method must either update it to make sure it's correctly representing
  40614. the given cell (which may be different from the one that the component was created for), or it can
  40615. delete this component and return a new one.
  40616. */
  40617. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  40618. Component* existingComponentToUpdate);
  40619. /** This callback is made when the user clicks on one of the cells in the table.
  40620. The mouse event's coordinates will be relative to the entire table row.
  40621. @see cellDoubleClicked, backgroundClicked
  40622. */
  40623. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  40624. /** This callback is made when the user clicks on one of the cells in the table.
  40625. The mouse event's coordinates will be relative to the entire table row.
  40626. @see cellClicked, backgroundClicked
  40627. */
  40628. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  40629. /** This can be overridden to react to the user double-clicking on a part of the list where
  40630. there are no rows.
  40631. @see cellClicked
  40632. */
  40633. virtual void backgroundClicked();
  40634. /** This callback is made when the table's sort order is changed.
  40635. This could be because the user has clicked a column header, or because the
  40636. TableHeaderComponent::setSortColumnId() method was called.
  40637. If you implement this, your method should re-sort the table using the given
  40638. column as the key.
  40639. */
  40640. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  40641. /** Returns the best width for one of the columns.
  40642. If you implement this method, you should measure the width of all the items
  40643. in this column, and return the best size.
  40644. Returning 0 means that the column shouldn't be changed.
  40645. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  40646. */
  40647. virtual int getColumnAutoSizeWidth (int columnId);
  40648. /** Returns a tooltip for a particular cell in the table.
  40649. */
  40650. virtual const String getCellTooltip (int rowNumber, int columnId);
  40651. /** Override this to be informed when rows are selected or deselected.
  40652. @see ListBox::selectedRowsChanged()
  40653. */
  40654. virtual void selectedRowsChanged (int lastRowSelected);
  40655. /** Override this to be informed when the delete key is pressed.
  40656. @see ListBox::deleteKeyPressed()
  40657. */
  40658. virtual void deleteKeyPressed (int lastRowSelected);
  40659. /** Override this to be informed when the return key is pressed.
  40660. @see ListBox::returnKeyPressed()
  40661. */
  40662. virtual void returnKeyPressed (int lastRowSelected);
  40663. /** Override this to be informed when the list is scrolled.
  40664. This might be caused by the user moving the scrollbar, or by programmatic changes
  40665. to the list position.
  40666. */
  40667. virtual void listWasScrolled();
  40668. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  40669. If this returns a non-empty name then when the user drags a row, the table will try to
  40670. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  40671. drag-and-drop operation, using this string as the source description, and the listbox
  40672. itself as the source component.
  40673. @see DragAndDropContainer::startDragging
  40674. */
  40675. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  40676. };
  40677. /**
  40678. A table of cells, using a TableHeaderComponent as its header.
  40679. This component makes it easy to create a table by providing a TableListBoxModel as
  40680. the data source.
  40681. @see TableListBoxModel, TableHeaderComponent
  40682. */
  40683. class JUCE_API TableListBox : public ListBox,
  40684. private ListBoxModel,
  40685. private TableHeaderComponent::Listener
  40686. {
  40687. public:
  40688. /** Creates a TableListBox.
  40689. The model pointer passed-in can be null, in which case you can set it later
  40690. with setModel().
  40691. */
  40692. TableListBox (const String& componentName = String::empty,
  40693. TableListBoxModel* model = 0);
  40694. /** Destructor. */
  40695. ~TableListBox();
  40696. /** Changes the TableListBoxModel that is being used for this table.
  40697. */
  40698. void setModel (TableListBoxModel* newModel);
  40699. /** Returns the model currently in use. */
  40700. TableListBoxModel* getModel() const { return model; }
  40701. /** Returns the header component being used in this table. */
  40702. TableHeaderComponent& getHeader() const { return *header; }
  40703. /** Sets the header component to use for the table.
  40704. The table will take ownership of the component that you pass in, and will delete it
  40705. when it's no longer needed.
  40706. */
  40707. void setHeader (TableHeaderComponent* newHeader);
  40708. /** Changes the height of the table header component.
  40709. @see getHeaderHeight
  40710. */
  40711. void setHeaderHeight (int newHeight);
  40712. /** Returns the height of the table header.
  40713. @see setHeaderHeight
  40714. */
  40715. int getHeaderHeight() const;
  40716. /** Resizes a column to fit its contents.
  40717. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  40718. and applies that to the column.
  40719. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  40720. */
  40721. void autoSizeColumn (int columnId);
  40722. /** Calls autoSizeColumn() for all columns in the table. */
  40723. void autoSizeAllColumns();
  40724. /** Enables or disables the auto size options on the popup menu.
  40725. By default, these are enabled.
  40726. */
  40727. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  40728. /** True if the auto-size options should be shown on the menu.
  40729. @see setAutoSizeMenuOptionsShown
  40730. */
  40731. bool isAutoSizeMenuOptionShown() const;
  40732. /** Returns the position of one of the cells in the table.
  40733. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  40734. the table component's top-left. The row number isn't checked to see if it's
  40735. in-range, but the column ID must exist or this will return an empty rectangle.
  40736. If relativeToComponentTopLeft is false, the co-ords are relative to the
  40737. top-left of the table's top-left cell.
  40738. */
  40739. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  40740. bool relativeToComponentTopLeft) const;
  40741. /** Returns the component that currently represents a given cell.
  40742. If the component for this cell is off-screen or if the position is out-of-range,
  40743. this may return 0.
  40744. @see getCellPosition
  40745. */
  40746. Component* getCellComponent (int columnId, int rowNumber) const;
  40747. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  40748. @see ListBox::scrollToEnsureRowIsOnscreen
  40749. */
  40750. void scrollToEnsureColumnIsOnscreen (int columnId);
  40751. /** @internal */
  40752. int getNumRows();
  40753. /** @internal */
  40754. void paintListBoxItem (int, Graphics&, int, int, bool);
  40755. /** @internal */
  40756. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  40757. /** @internal */
  40758. void selectedRowsChanged (int lastRowSelected);
  40759. /** @internal */
  40760. void deleteKeyPressed (int currentSelectedRow);
  40761. /** @internal */
  40762. void returnKeyPressed (int currentSelectedRow);
  40763. /** @internal */
  40764. void backgroundClicked();
  40765. /** @internal */
  40766. void listWasScrolled();
  40767. /** @internal */
  40768. void tableColumnsChanged (TableHeaderComponent*);
  40769. /** @internal */
  40770. void tableColumnsResized (TableHeaderComponent*);
  40771. /** @internal */
  40772. void tableSortOrderChanged (TableHeaderComponent*);
  40773. /** @internal */
  40774. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  40775. /** @internal */
  40776. void resized();
  40777. private:
  40778. TableHeaderComponent* header;
  40779. TableListBoxModel* model;
  40780. int columnIdNowBeingDragged;
  40781. bool autoSizeOptionsShown;
  40782. void updateColumnComponents() const;
  40783. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  40784. };
  40785. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  40786. /*** End of inlined file: juce_TableListBox.h ***/
  40787. #endif
  40788. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  40789. #endif
  40790. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  40791. #endif
  40792. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  40793. #endif
  40794. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40795. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  40796. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40797. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40798. /**
  40799. A factory object which can create ToolbarItemComponent objects.
  40800. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  40801. that it can create.
  40802. Each type of item is identified by a unique ID, and multiple instances of an
  40803. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  40804. bars).
  40805. @see Toolbar, ToolbarItemComponent, ToolbarButton
  40806. */
  40807. class JUCE_API ToolbarItemFactory
  40808. {
  40809. public:
  40810. ToolbarItemFactory();
  40811. /** Destructor. */
  40812. virtual ~ToolbarItemFactory();
  40813. /** A set of reserved item ID values, used for the built-in item types.
  40814. */
  40815. enum SpecialItemIds
  40816. {
  40817. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  40818. can be placed between sets of items to break them into groups. */
  40819. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  40820. items.*/
  40821. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  40822. either side of it, filling any available space. */
  40823. };
  40824. /** Must return a list of the IDs for all the item types that this factory can create.
  40825. The ids should be added to the array that is passed-in.
  40826. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  40827. and the predefined IDs in the SpecialItemIds enum.
  40828. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  40829. to this list if you want your toolbar to be able to contain those items.
  40830. The list returned here is used by the ToolbarItemPalette class to obtain its list
  40831. of available items, and their order on the palette will reflect the order in which
  40832. they appear on this list.
  40833. @see ToolbarItemPalette
  40834. */
  40835. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  40836. /** Must return the set of items that should be added to a toolbar as its default set.
  40837. This method is used by Toolbar::addDefaultItems() to determine which items to
  40838. create.
  40839. The items that your method adds to the array that is passed-in will be added to the
  40840. toolbar in the same order. Items can appear in the list more than once.
  40841. */
  40842. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  40843. /** Must create an instance of one of the items that the factory lists in its
  40844. getAllToolbarItemIds() method.
  40845. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  40846. method, except for the built-in item types from the SpecialItemIds enum, which
  40847. are created internally by the toolbar code.
  40848. Try not to keep a pointer to the object that is returned, as it will be deleted
  40849. automatically by the toolbar, and remember that multiple instances of the same
  40850. item type are likely to exist at the same time.
  40851. */
  40852. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  40853. };
  40854. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40855. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  40856. #endif
  40857. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40858. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  40859. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40860. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40861. /**
  40862. A component containing a list of toolbar items, which the user can drag onto
  40863. a toolbar to add them.
  40864. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  40865. which automatically shows one of these in a dialog box with lots of extra controls.
  40866. @see Toolbar
  40867. */
  40868. class JUCE_API ToolbarItemPalette : public Component,
  40869. public DragAndDropContainer
  40870. {
  40871. public:
  40872. /** Creates a palette of items for a given factory, with the aim of adding them
  40873. to the specified toolbar.
  40874. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  40875. set of items that are shown in this palette.
  40876. The toolbar and factory must not be deleted while this object exists.
  40877. */
  40878. ToolbarItemPalette (ToolbarItemFactory& factory,
  40879. Toolbar* toolbar);
  40880. /** Destructor. */
  40881. ~ToolbarItemPalette();
  40882. /** @internal */
  40883. void resized();
  40884. private:
  40885. ToolbarItemFactory& factory;
  40886. Toolbar* toolbar;
  40887. Viewport viewport;
  40888. OwnedArray <ToolbarItemComponent> items;
  40889. friend class Toolbar;
  40890. void replaceComponent (ToolbarItemComponent* comp);
  40891. void addComponent (int itemId, int index);
  40892. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  40893. };
  40894. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40895. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  40896. #endif
  40897. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  40898. /*** Start of inlined file: juce_TreeView.h ***/
  40899. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  40900. #define __JUCE_TREEVIEW_JUCEHEADER__
  40901. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  40902. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40903. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40904. /**
  40905. Components derived from this class can have files dropped onto them by an external application.
  40906. @see DragAndDropContainer
  40907. */
  40908. class JUCE_API FileDragAndDropTarget
  40909. {
  40910. public:
  40911. /** Destructor. */
  40912. virtual ~FileDragAndDropTarget() {}
  40913. /** Callback to check whether this target is interested in the set of files being offered.
  40914. Note that this will be called repeatedly when the user is dragging the mouse around over your
  40915. component, so don't do anything time-consuming in here, like opening the files to have a look
  40916. inside them!
  40917. @param files the set of (absolute) pathnames of the files that the user is dragging
  40918. @returns true if this component wants to receive the other callbacks regarging this
  40919. type of object; if it returns false, no other callbacks will be made.
  40920. */
  40921. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  40922. /** Callback to indicate that some files are being dragged over this component.
  40923. This gets called when the user moves the mouse into this component while dragging.
  40924. Use this callback as a trigger to make your component repaint itself to give the
  40925. user feedback about whether the files can be dropped here or not.
  40926. @param files the set of (absolute) pathnames of the files that the user is dragging
  40927. @param x the mouse x position, relative to this component
  40928. @param y the mouse y position, relative to this component
  40929. */
  40930. virtual void fileDragEnter (const StringArray& files, int x, int y);
  40931. /** Callback to indicate that the user is dragging some files over this component.
  40932. This gets called when the user moves the mouse over this component while dragging.
  40933. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  40934. this lets you know what happens in-between.
  40935. @param files the set of (absolute) pathnames of the files that the user is dragging
  40936. @param x the mouse x position, relative to this component
  40937. @param y the mouse y position, relative to this component
  40938. */
  40939. virtual void fileDragMove (const StringArray& files, int x, int y);
  40940. /** Callback to indicate that the mouse has moved away from this component.
  40941. This gets called when the user moves the mouse out of this component while dragging
  40942. the files.
  40943. If you've used fileDragEnter() to repaint your component and give feedback, use this
  40944. as a signal to repaint it in its normal state.
  40945. @param files the set of (absolute) pathnames of the files that the user is dragging
  40946. */
  40947. virtual void fileDragExit (const StringArray& files);
  40948. /** Callback to indicate that the user has dropped the files onto this component.
  40949. When the user drops the files, this get called, and you can use the files in whatever
  40950. way is appropriate.
  40951. Note that after this is called, the fileDragExit method may not be called, so you should
  40952. clean up in here if there's anything you need to do when the drag finishes.
  40953. @param files the set of (absolute) pathnames of the files that the user is dragging
  40954. @param x the mouse x position, relative to this component
  40955. @param y the mouse y position, relative to this component
  40956. */
  40957. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  40958. };
  40959. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40960. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  40961. class TreeView;
  40962. /**
  40963. An item in a treeview.
  40964. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  40965. own sub-items.
  40966. To implement an item that contains sub-items, override the itemOpennessChanged()
  40967. method so that when it is opened, it adds the new sub-items to itself using the
  40968. addSubItem method. Depending on the nature of the item it might choose to only
  40969. do this the first time it's opened, or it might want to refresh itself each time.
  40970. It also has the option of deleting its sub-items when it is closed, or leaving them
  40971. in place.
  40972. */
  40973. class JUCE_API TreeViewItem
  40974. {
  40975. public:
  40976. /** Constructor. */
  40977. TreeViewItem();
  40978. /** Destructor. */
  40979. virtual ~TreeViewItem();
  40980. /** Returns the number of sub-items that have been added to this item.
  40981. Note that this doesn't mean much if the node isn't open.
  40982. @see getSubItem, mightContainSubItems, addSubItem
  40983. */
  40984. int getNumSubItems() const throw();
  40985. /** Returns one of the item's sub-items.
  40986. Remember that the object returned might get deleted at any time when its parent
  40987. item is closed or refreshed, depending on the nature of the items you're using.
  40988. @see getNumSubItems
  40989. */
  40990. TreeViewItem* getSubItem (int index) const throw();
  40991. /** Removes any sub-items. */
  40992. void clearSubItems();
  40993. /** Adds a sub-item.
  40994. @param newItem the object to add to the item's sub-item list. Once added, these can be
  40995. found using getSubItem(). When the items are later removed with
  40996. removeSubItem() (or when this item is deleted), they will be deleted.
  40997. @param insertPosition the index which the new item should have when it's added. If this
  40998. value is less than 0, the item will be added to the end of the list.
  40999. */
  41000. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  41001. /** Removes one of the sub-items.
  41002. @param index the item to remove
  41003. @param deleteItem if true, the item that is removed will also be deleted.
  41004. */
  41005. void removeSubItem (int index, bool deleteItem = true);
  41006. /** Returns the TreeView to which this item belongs. */
  41007. TreeView* getOwnerView() const throw() { return ownerView; }
  41008. /** Returns the item within which this item is contained. */
  41009. TreeViewItem* getParentItem() const throw() { return parentItem; }
  41010. /** True if this item is currently open in the treeview. */
  41011. bool isOpen() const throw();
  41012. /** Opens or closes the item.
  41013. When opened or closed, the item's itemOpennessChanged() method will be called,
  41014. and a subclass should use this callback to create and add any sub-items that
  41015. it needs to.
  41016. @see itemOpennessChanged, mightContainSubItems
  41017. */
  41018. void setOpen (bool shouldBeOpen);
  41019. /** True if this item is currently selected.
  41020. Use this when painting the node, to decide whether to draw it as selected or not.
  41021. */
  41022. bool isSelected() const throw();
  41023. /** Selects or deselects the item.
  41024. This will cause a callback to itemSelectionChanged()
  41025. */
  41026. void setSelected (bool shouldBeSelected,
  41027. bool deselectOtherItemsFirst);
  41028. /** Returns the rectangle that this item occupies.
  41029. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  41030. top-left of the TreeView comp, so this will depend on the scroll-position of
  41031. the tree. If false, it is relative to the top-left of the topmost item in the
  41032. tree (so this would be unaffected by scrolling the view).
  41033. */
  41034. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  41035. /** Sends a signal to the treeview to make it refresh itself.
  41036. Call this if your items have changed and you want the tree to update to reflect
  41037. this.
  41038. */
  41039. void treeHasChanged() const throw();
  41040. /** Sends a repaint message to redraw just this item.
  41041. Note that you should only call this if you want to repaint a superficial change. If
  41042. you're altering the tree's nodes, you should instead call treeHasChanged().
  41043. */
  41044. void repaintItem() const;
  41045. /** Returns the row number of this item in the tree.
  41046. The row number of an item will change according to which items are open.
  41047. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  41048. */
  41049. int getRowNumberInTree() const throw();
  41050. /** Returns true if all the item's parent nodes are open.
  41051. This is useful to check whether the item might actually be visible or not.
  41052. */
  41053. bool areAllParentsOpen() const throw();
  41054. /** Changes whether lines are drawn to connect any sub-items to this item.
  41055. By default, line-drawing is turned on.
  41056. */
  41057. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  41058. /** Tells the tree whether this item can potentially be opened.
  41059. If your item could contain sub-items, this should return true; if it returns
  41060. false then the tree will not try to open the item. This determines whether or
  41061. not the item will be drawn with a 'plus' button next to it.
  41062. */
  41063. virtual bool mightContainSubItems() = 0;
  41064. /** Returns a string to uniquely identify this item.
  41065. If you're planning on using the TreeView::getOpennessState() method, then
  41066. these strings will be used to identify which nodes are open. The string
  41067. should be unique amongst the item's sibling items, but it's ok for there
  41068. to be duplicates at other levels of the tree.
  41069. If you're not going to store the state, then it's ok not to bother implementing
  41070. this method.
  41071. */
  41072. virtual const String getUniqueName() const;
  41073. /** Called when an item is opened or closed.
  41074. When setOpen() is called and the item has specified that it might
  41075. have sub-items with the mightContainSubItems() method, this method
  41076. is called to let the item create or manage its sub-items.
  41077. So when this is called with isNowOpen set to true (i.e. when the item is being
  41078. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  41079. refresh its sub-item list.
  41080. When this is called with isNowOpen set to false, the subclass might want
  41081. to use clearSubItems() to save on space, or it might choose to leave them,
  41082. depending on the nature of the tree.
  41083. You could also use this callback as a trigger to start a background process
  41084. which asynchronously creates sub-items and adds them, if that's more
  41085. appropriate for the task in hand.
  41086. @see mightContainSubItems
  41087. */
  41088. virtual void itemOpennessChanged (bool isNowOpen);
  41089. /** Must return the width required by this item.
  41090. If your item needs to have a particular width in pixels, return that value; if
  41091. you'd rather have it just fill whatever space is available in the treeview,
  41092. return -1.
  41093. If all your items return -1, no horizontal scrollbar will be shown, but if any
  41094. items have fixed widths and extend beyond the width of the treeview, a
  41095. scrollbar will appear.
  41096. Each item can be a different width, but if they change width, you should call
  41097. treeHasChanged() to update the tree.
  41098. */
  41099. virtual int getItemWidth() const { return -1; }
  41100. /** Must return the height required by this item.
  41101. This is the height in pixels that the item will take up. Items in the tree
  41102. can be different heights, but if they change height, you should call
  41103. treeHasChanged() to update the tree.
  41104. */
  41105. virtual int getItemHeight() const { return 20; }
  41106. /** You can override this method to return false if you don't want to allow the
  41107. user to select this item.
  41108. */
  41109. virtual bool canBeSelected() const { return true; }
  41110. /** Creates a component that will be used to represent this item.
  41111. You don't have to implement this method - if it returns 0 then no component
  41112. will be used for the item, and you can just draw it using the paintItem()
  41113. callback. But if you do return a component, it will be positioned in the
  41114. treeview so that it can be used to represent this item.
  41115. The component returned will be managed by the treeview, so always return
  41116. a new component, and don't keep a reference to it, as the treeview will
  41117. delete it later when it goes off the screen or is no longer needed. Also
  41118. bear in mind that if the component keeps a reference to the item that
  41119. created it, that item could be deleted before the component. Its position
  41120. and size will be completely managed by the tree, so don't attempt to move it
  41121. around.
  41122. Something you may want to do with your component is to give it a pointer to
  41123. the TreeView that created it. This is perfectly safe, and there's no danger
  41124. of it becoming a dangling pointer because the TreeView will always delete
  41125. the component before it is itself deleted.
  41126. As long as you stick to these rules you can return whatever kind of
  41127. component you like. It's most useful if you're doing things like drag-and-drop
  41128. of items, or want to use a Label component to edit item names, etc.
  41129. */
  41130. virtual Component* createItemComponent() { return 0; }
  41131. /** Draws the item's contents.
  41132. You can choose to either implement this method and draw each item, or you
  41133. can use createItemComponent() to create a component that will represent the
  41134. item.
  41135. If all you need in your tree is to be able to draw the items and detect when
  41136. the user selects or double-clicks one of them, it's probably enough to
  41137. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  41138. complicated interactions, you may need to use createItemComponent() instead.
  41139. @param g the graphics context to draw into
  41140. @param width the width of the area available for drawing
  41141. @param height the height of the area available for drawing
  41142. */
  41143. virtual void paintItem (Graphics& g, int width, int height);
  41144. /** Draws the item's open/close button.
  41145. If you don't implement this method, the default behaviour is to
  41146. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  41147. it for custom effects.
  41148. */
  41149. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  41150. /** Called when the user clicks on this item.
  41151. If you're using createItemComponent() to create a custom component for the
  41152. item, the mouse-clicks might not make it through to the treeview, but this
  41153. is how you find out about clicks when just drawing each item individually.
  41154. The associated mouse-event details are passed in, so you can find out about
  41155. which button, where it was, etc.
  41156. @see itemDoubleClicked
  41157. */
  41158. virtual void itemClicked (const MouseEvent& e);
  41159. /** Called when the user double-clicks on this item.
  41160. If you're using createItemComponent() to create a custom component for the
  41161. item, the mouse-clicks might not make it through to the treeview, but this
  41162. is how you find out about clicks when just drawing each item individually.
  41163. The associated mouse-event details are passed in, so you can find out about
  41164. which button, where it was, etc.
  41165. If not overridden, the base class method here will open or close the item as
  41166. if the 'plus' button had been clicked.
  41167. @see itemClicked
  41168. */
  41169. virtual void itemDoubleClicked (const MouseEvent& e);
  41170. /** Called when the item is selected or deselected.
  41171. Use this if you want to do something special when the item's selectedness
  41172. changes. By default it'll get repainted when this happens.
  41173. */
  41174. virtual void itemSelectionChanged (bool isNowSelected);
  41175. /** The item can return a tool tip string here if it wants to.
  41176. @see TooltipClient
  41177. */
  41178. virtual const String getTooltip();
  41179. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  41180. If this returns a non-empty name then when the user drags an item, the treeview will
  41181. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  41182. a drag-and-drop operation, using this string as the source description, with the treeview
  41183. itself as the source component.
  41184. If you need more complex drag-and-drop behaviour, you can use custom components for
  41185. the items, and use those to trigger the drag.
  41186. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  41187. isInterestedInFileDrag(), etc.
  41188. @see DragAndDropContainer::startDragging
  41189. */
  41190. virtual const String getDragSourceDescription();
  41191. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  41192. method and return true.
  41193. If you return true and allow some files to be dropped, you'll also need to implement the
  41194. filesDropped() method to do something with them.
  41195. Note that this will be called often, so make your implementation very quick! There's
  41196. certainly no time to try opening the files and having a think about what's inside them!
  41197. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  41198. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  41199. */
  41200. virtual bool isInterestedInFileDrag (const StringArray& files);
  41201. /** When files are dropped into this item, this callback is invoked.
  41202. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  41203. The insertIndex value indicates where in the list of sub-items the files were dropped.
  41204. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  41205. */
  41206. virtual void filesDropped (const StringArray& files, int insertIndex);
  41207. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  41208. If you implement this method, you'll also need to implement itemDropped() in order to handle
  41209. the items when they are dropped.
  41210. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  41211. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  41212. */
  41213. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  41214. /** When a things are dropped into this item, this callback is invoked.
  41215. For this to work, you need to have also implemented isInterestedInDragSource().
  41216. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  41217. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  41218. */
  41219. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  41220. /** Sets a flag to indicate that the item wants to be allowed
  41221. to draw all the way across to the left edge of the treeview.
  41222. By default this is false, which means that when the paintItem()
  41223. method is called, its graphics context is clipped to only allow
  41224. drawing within the item's rectangle. If this flag is set to true,
  41225. then the graphics context isn't clipped on its left side, so it
  41226. can draw all the way across to the left margin. Note that the
  41227. context will still have its origin in the same place though, so
  41228. the coordinates of anything to its left will be negative. It's
  41229. mostly useful if you want to draw a wider bar behind the
  41230. highlighted item.
  41231. */
  41232. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  41233. /** Saves the current state of open/closed nodes so it can be restored later.
  41234. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  41235. and records it as XML. To identify node objects it uses the
  41236. TreeViewItem::getUniqueName() method to create named paths. This
  41237. means that the same state of open/closed nodes can be restored to a
  41238. completely different instance of the tree, as long as it contains nodes
  41239. whose unique names are the same.
  41240. You'd normally want to use TreeView::getOpennessState() rather than call it
  41241. for a specific item, but this can be handy if you need to briefly save the state
  41242. for a section of the tree.
  41243. The caller is responsible for deleting the object that is returned.
  41244. @see TreeView::getOpennessState, restoreOpennessState
  41245. */
  41246. XmlElement* getOpennessState() const throw();
  41247. /** Restores the openness of this item and all its sub-items from a saved state.
  41248. See TreeView::restoreOpennessState for more details.
  41249. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  41250. for a specific item, but this can be handy if you need to briefly save the state
  41251. for a section of the tree.
  41252. @see TreeView::restoreOpennessState, getOpennessState
  41253. */
  41254. void restoreOpennessState (const XmlElement& xml) throw();
  41255. /** Returns the index of this item in its parent's sub-items. */
  41256. int getIndexInParent() const throw();
  41257. /** Returns true if this item is the last of its parent's sub-itens. */
  41258. bool isLastOfSiblings() const throw();
  41259. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  41260. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  41261. The string takes the form of a path, constructed from the getUniqueName() of this
  41262. item and all its parents, so these must all be correctly implemented for it to work.
  41263. @see TreeView::findItemFromIdentifierString, getUniqueName
  41264. */
  41265. const String getItemIdentifierString() const;
  41266. /**
  41267. This handy class takes a copy of a TreeViewItem's openness when you create it,
  41268. and restores that openness state when its destructor is called.
  41269. This can very handy when you're refreshing sub-items - e.g.
  41270. @code
  41271. void MyTreeViewItem::updateChildItems()
  41272. {
  41273. OpennessRestorer openness (*this); // saves the openness state here..
  41274. clearSubItems();
  41275. // add a bunch of sub-items here which may or may not be the same as the ones that
  41276. // were previously there
  41277. addSubItem (...
  41278. // ..and at this point, the old openness is restored, so any items that haven't
  41279. // changed will have their old openness retained.
  41280. }
  41281. @endcode
  41282. */
  41283. class OpennessRestorer
  41284. {
  41285. public:
  41286. OpennessRestorer (TreeViewItem& treeViewItem);
  41287. ~OpennessRestorer();
  41288. private:
  41289. TreeViewItem& treeViewItem;
  41290. ScopedPointer <XmlElement> oldOpenness;
  41291. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  41292. };
  41293. private:
  41294. TreeView* ownerView;
  41295. TreeViewItem* parentItem;
  41296. OwnedArray <TreeViewItem> subItems;
  41297. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  41298. int uid;
  41299. bool selected : 1;
  41300. bool redrawNeeded : 1;
  41301. bool drawLinesInside : 1;
  41302. bool drawsInLeftMargin : 1;
  41303. unsigned int openness : 2;
  41304. friend class TreeView;
  41305. friend class TreeViewContentComponent;
  41306. void updatePositions (int newY);
  41307. int getIndentX() const throw();
  41308. void setOwnerView (TreeView* newOwner) throw();
  41309. void paintRecursively (Graphics& g, int width);
  41310. TreeViewItem* getTopLevelItem() throw();
  41311. TreeViewItem* findItemRecursively (int y) throw();
  41312. TreeViewItem* getDeepestOpenParentItem() throw();
  41313. int getNumRows() const throw();
  41314. TreeViewItem* getItemOnRow (int index) throw();
  41315. void deselectAllRecursively();
  41316. int countSelectedItemsRecursively (int depth) const throw();
  41317. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  41318. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  41319. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  41320. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  41321. };
  41322. /**
  41323. A tree-view component.
  41324. Use one of these to hold and display a structure of TreeViewItem objects.
  41325. */
  41326. class JUCE_API TreeView : public Component,
  41327. public SettableTooltipClient,
  41328. public FileDragAndDropTarget,
  41329. public DragAndDropTarget,
  41330. private AsyncUpdater
  41331. {
  41332. public:
  41333. /** Creates an empty treeview.
  41334. Once you've got a treeview component, you'll need to give it something to
  41335. display, using the setRootItem() method.
  41336. */
  41337. TreeView (const String& componentName = String::empty);
  41338. /** Destructor. */
  41339. ~TreeView();
  41340. /** Sets the item that is displayed in the treeview.
  41341. A tree has a single root item which contains as many sub-items as it needs. If
  41342. you want the tree to contain a number of root items, you should still use a single
  41343. root item above these, but hide it using setRootItemVisible().
  41344. You can pass in 0 to this method to clear the tree and remove its current root item.
  41345. The object passed in will not be deleted by the treeview, it's up to the caller
  41346. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  41347. this item until you've removed it from the tree, either by calling setRootItem (0),
  41348. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  41349. to delete it.
  41350. */
  41351. void setRootItem (TreeViewItem* newRootItem);
  41352. /** Returns the tree's root item.
  41353. This will be the last object passed to setRootItem(), or 0 if none has been set.
  41354. */
  41355. TreeViewItem* getRootItem() const throw() { return rootItem; }
  41356. /** This will remove and delete the current root item.
  41357. It's a convenient way of deleting the item and calling setRootItem (0).
  41358. */
  41359. void deleteRootItem();
  41360. /** Changes whether the tree's root item is shown or not.
  41361. If the root item is hidden, only its sub-items will be shown in the treeview - this
  41362. lets you make the tree look as if it's got many root items. If it's hidden, this call
  41363. will also make sure the root item is open (otherwise the treeview would look empty).
  41364. */
  41365. void setRootItemVisible (bool shouldBeVisible);
  41366. /** Returns true if the root item is visible.
  41367. @see setRootItemVisible
  41368. */
  41369. bool isRootItemVisible() const throw() { return rootItemVisible; }
  41370. /** Sets whether items are open or closed by default.
  41371. Normally, items are closed until the user opens them, but you can use this
  41372. to make them default to being open until explicitly closed.
  41373. @see areItemsOpenByDefault
  41374. */
  41375. void setDefaultOpenness (bool isOpenByDefault);
  41376. /** Returns true if the tree's items default to being open.
  41377. @see setDefaultOpenness
  41378. */
  41379. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  41380. /** This sets a flag to indicate that the tree can be used for multi-selection.
  41381. You can always select multiple items internally by calling the
  41382. TreeViewItem::setSelected() method, but this flag indicates whether the user
  41383. is allowed to multi-select by clicking on the tree.
  41384. By default it is disabled.
  41385. @see isMultiSelectEnabled
  41386. */
  41387. void setMultiSelectEnabled (bool canMultiSelect);
  41388. /** Returns whether multi-select has been enabled for the tree.
  41389. @see setMultiSelectEnabled
  41390. */
  41391. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  41392. /** Sets a flag to indicate whether to hide the open/close buttons.
  41393. @see areOpenCloseButtonsVisible
  41394. */
  41395. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  41396. /** Returns whether open/close buttons are shown.
  41397. @see setOpenCloseButtonsVisible
  41398. */
  41399. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  41400. /** Deselects any items that are currently selected. */
  41401. void clearSelectedItems();
  41402. /** Returns the number of items that are currently selected.
  41403. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  41404. tree will be recursed.
  41405. @see getSelectedItem, clearSelectedItems
  41406. */
  41407. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const throw();
  41408. /** Returns one of the selected items in the tree.
  41409. @param index the index, 0 to (getNumSelectedItems() - 1)
  41410. */
  41411. TreeViewItem* getSelectedItem (int index) const throw();
  41412. /** Returns the number of rows the tree is using.
  41413. This will depend on which items are open.
  41414. @see TreeViewItem::getRowNumberInTree()
  41415. */
  41416. int getNumRowsInTree() const;
  41417. /** Returns the item on a particular row of the tree.
  41418. If the index is out of range, this will return 0.
  41419. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  41420. */
  41421. TreeViewItem* getItemOnRow (int index) const;
  41422. /** Returns the item that contains a given y position.
  41423. The y is relative to the top of the TreeView component.
  41424. */
  41425. TreeViewItem* getItemAt (int yPosition) const throw();
  41426. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  41427. void scrollToKeepItemVisible (TreeViewItem* item);
  41428. /** Returns the treeview's Viewport object. */
  41429. Viewport* getViewport() const throw();
  41430. /** Returns the number of pixels by which each nested level of the tree is indented.
  41431. @see setIndentSize
  41432. */
  41433. int getIndentSize() const throw() { return indentSize; }
  41434. /** Changes the distance by which each nested level of the tree is indented.
  41435. @see getIndentSize
  41436. */
  41437. void setIndentSize (int newIndentSize);
  41438. /** Searches the tree for an item with the specified identifier.
  41439. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  41440. If no such item exists, this will return false. If the item is found, all of its items
  41441. will be automatically opened.
  41442. */
  41443. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  41444. /** Saves the current state of open/closed nodes so it can be restored later.
  41445. This takes a snapshot of which nodes have been explicitly opened or closed,
  41446. and records it as XML. To identify node objects it uses the
  41447. TreeViewItem::getUniqueName() method to create named paths. This
  41448. means that the same state of open/closed nodes can be restored to a
  41449. completely different instance of the tree, as long as it contains nodes
  41450. whose unique names are the same.
  41451. The caller is responsible for deleting the object that is returned.
  41452. @param alsoIncludeScrollPosition if this is true, the state will also
  41453. include information about where the
  41454. tree has been scrolled to vertically,
  41455. so this can also be restored
  41456. @see restoreOpennessState
  41457. */
  41458. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  41459. /** Restores a previously saved arrangement of open/closed nodes.
  41460. This will try to restore a snapshot of the tree's state that was created by
  41461. the getOpennessState() method. If any of the nodes named in the original
  41462. XML aren't present in this tree, they will be ignored.
  41463. @see getOpennessState
  41464. */
  41465. void restoreOpennessState (const XmlElement& newState);
  41466. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  41467. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41468. methods.
  41469. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41470. */
  41471. enum ColourIds
  41472. {
  41473. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  41474. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  41475. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  41476. };
  41477. /** @internal */
  41478. void paint (Graphics& g);
  41479. /** @internal */
  41480. void resized();
  41481. /** @internal */
  41482. bool keyPressed (const KeyPress& key);
  41483. /** @internal */
  41484. void colourChanged();
  41485. /** @internal */
  41486. void enablementChanged();
  41487. /** @internal */
  41488. bool isInterestedInFileDrag (const StringArray& files);
  41489. /** @internal */
  41490. void fileDragEnter (const StringArray& files, int x, int y);
  41491. /** @internal */
  41492. void fileDragMove (const StringArray& files, int x, int y);
  41493. /** @internal */
  41494. void fileDragExit (const StringArray& files);
  41495. /** @internal */
  41496. void filesDropped (const StringArray& files, int x, int y);
  41497. /** @internal */
  41498. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  41499. /** @internal */
  41500. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  41501. /** @internal */
  41502. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  41503. /** @internal */
  41504. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  41505. /** @internal */
  41506. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  41507. private:
  41508. friend class TreeViewItem;
  41509. friend class TreeViewContentComponent;
  41510. class TreeViewport;
  41511. class InsertPointHighlight;
  41512. class TargetGroupHighlight;
  41513. friend class ScopedPointer<TreeViewport>;
  41514. friend class ScopedPointer<InsertPointHighlight>;
  41515. friend class ScopedPointer<TargetGroupHighlight>;
  41516. ScopedPointer<TreeViewport> viewport;
  41517. CriticalSection nodeAlterationLock;
  41518. TreeViewItem* rootItem;
  41519. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  41520. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  41521. int indentSize;
  41522. bool defaultOpenness : 1;
  41523. bool needsRecalculating : 1;
  41524. bool rootItemVisible : 1;
  41525. bool multiSelectEnabled : 1;
  41526. bool openCloseButtonsVisible : 1;
  41527. void itemsChanged() throw();
  41528. void handleAsyncUpdate();
  41529. void moveSelectedRow (int delta);
  41530. void updateButtonUnderMouse (const MouseEvent& e);
  41531. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  41532. void hideDragHighlight() throw();
  41533. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  41534. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  41535. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  41536. const StringArray& files, const String& sourceDescription,
  41537. Component* sourceComponent) const throw();
  41538. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  41539. };
  41540. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  41541. /*** End of inlined file: juce_TreeView.h ***/
  41542. #endif
  41543. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41544. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  41545. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41546. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41547. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  41548. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41549. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41550. /*** Start of inlined file: juce_FileFilter.h ***/
  41551. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  41552. #define __JUCE_FILEFILTER_JUCEHEADER__
  41553. /**
  41554. Interface for deciding which files are suitable for something.
  41555. For example, this is used by DirectoryContentsList to select which files
  41556. go into the list.
  41557. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  41558. */
  41559. class JUCE_API FileFilter
  41560. {
  41561. public:
  41562. /** Creates a filter with the given description.
  41563. The description can be returned later with the getDescription() method.
  41564. */
  41565. FileFilter (const String& filterDescription);
  41566. /** Destructor. */
  41567. virtual ~FileFilter();
  41568. /** Returns the description that the filter was created with. */
  41569. const String& getDescription() const throw();
  41570. /** Should return true if this file is suitable for inclusion in whatever context
  41571. the object is being used.
  41572. */
  41573. virtual bool isFileSuitable (const File& file) const = 0;
  41574. /** Should return true if this directory is suitable for inclusion in whatever context
  41575. the object is being used.
  41576. */
  41577. virtual bool isDirectorySuitable (const File& file) const = 0;
  41578. protected:
  41579. String description;
  41580. };
  41581. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  41582. /*** End of inlined file: juce_FileFilter.h ***/
  41583. /**
  41584. A class to asynchronously scan for details about the files in a directory.
  41585. This keeps a list of files and some information about them, using a background
  41586. thread to scan for more files. As files are found, it broadcasts change messages
  41587. to tell any listeners.
  41588. @see FileListComponent, FileBrowserComponent
  41589. */
  41590. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  41591. public TimeSliceClient
  41592. {
  41593. public:
  41594. /** Creates a directory list.
  41595. To set the directory it should point to, use setDirectory(), which will
  41596. also start it scanning for files on the background thread.
  41597. When the background thread finds and adds new files to this list, the
  41598. ChangeBroadcaster class will send a change message, so you can register
  41599. listeners and update them when the list changes.
  41600. @param fileFilter an optional filter to select which files are
  41601. included in the list. If this is 0, then all files
  41602. and directories are included. Make sure that the
  41603. filter doesn't get deleted during the lifetime of this
  41604. object
  41605. @param threadToUse a thread object that this list can use
  41606. to scan for files as a background task. Make sure
  41607. that the thread you give it has been started, or you
  41608. won't get any files!
  41609. */
  41610. DirectoryContentsList (const FileFilter* fileFilter,
  41611. TimeSliceThread& threadToUse);
  41612. /** Destructor. */
  41613. ~DirectoryContentsList();
  41614. /** Sets the directory to look in for files.
  41615. If the directory that's passed in is different to the current one, this will
  41616. also start the background thread scanning it for files.
  41617. */
  41618. void setDirectory (const File& directory,
  41619. bool includeDirectories,
  41620. bool includeFiles);
  41621. /** Returns the directory that's currently being used. */
  41622. const File& getDirectory() const;
  41623. /** Clears the list, and stops the thread scanning for files. */
  41624. void clear();
  41625. /** Clears the list and restarts scanning the directory for files. */
  41626. void refresh();
  41627. /** True if the background thread hasn't yet finished scanning for files. */
  41628. bool isStillLoading() const;
  41629. /** Tells the list whether or not to ignore hidden files.
  41630. By default these are ignored.
  41631. */
  41632. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  41633. /** Returns true if hidden files are ignored.
  41634. @see setIgnoresHiddenFiles
  41635. */
  41636. bool ignoresHiddenFiles() const;
  41637. /** Contains cached information about one of the files in a DirectoryContentsList.
  41638. */
  41639. struct FileInfo
  41640. {
  41641. /** The filename.
  41642. This isn't a full pathname, it's just the last part of the path, same as you'd
  41643. get from File::getFileName().
  41644. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  41645. */
  41646. String filename;
  41647. /** File size in bytes. */
  41648. int64 fileSize;
  41649. /** File modification time.
  41650. As supplied by File::getLastModificationTime().
  41651. */
  41652. Time modificationTime;
  41653. /** File creation time.
  41654. As supplied by File::getCreationTime().
  41655. */
  41656. Time creationTime;
  41657. /** True if the file is a directory. */
  41658. bool isDirectory;
  41659. /** True if the file is read-only. */
  41660. bool isReadOnly;
  41661. };
  41662. /** Returns the number of files currently available in the list.
  41663. The info about one of these files can be retrieved with getFileInfo() or
  41664. getFile().
  41665. Obviously as the background thread runs and scans the directory for files, this
  41666. number will change.
  41667. @see getFileInfo, getFile
  41668. */
  41669. int getNumFiles() const;
  41670. /** Returns the cached information about one of the files in the list.
  41671. If the index is in-range, this will return true and will copy the file's details
  41672. to the structure that is passed-in.
  41673. If it returns false, then the index wasn't in range, and the structure won't
  41674. be affected.
  41675. @see getNumFiles, getFile
  41676. */
  41677. bool getFileInfo (int index, FileInfo& resultInfo) const;
  41678. /** Returns one of the files in the list.
  41679. @param index should be less than getNumFiles(). If this is out-of-range, the
  41680. return value will be File::nonexistent
  41681. @see getNumFiles, getFileInfo
  41682. */
  41683. const File getFile (int index) const;
  41684. /** Returns the file filter being used.
  41685. The filter is specified in the constructor.
  41686. */
  41687. const FileFilter* getFilter() const { return fileFilter; }
  41688. /** @internal */
  41689. int useTimeSlice();
  41690. /** @internal */
  41691. TimeSliceThread& getTimeSliceThread() { return thread; }
  41692. /** @internal */
  41693. static int compareElements (const DirectoryContentsList::FileInfo* first,
  41694. const DirectoryContentsList::FileInfo* second);
  41695. private:
  41696. File root;
  41697. const FileFilter* fileFilter;
  41698. TimeSliceThread& thread;
  41699. int fileTypeFlags;
  41700. CriticalSection fileListLock;
  41701. OwnedArray <FileInfo> files;
  41702. ScopedPointer <DirectoryIterator> fileFindHandle;
  41703. bool volatile shouldStop;
  41704. void changed();
  41705. bool checkNextFile (bool& hasChanged);
  41706. bool addFile (const File& file, bool isDir,
  41707. const int64 fileSize, const Time& modTime,
  41708. const Time& creationTime, bool isReadOnly);
  41709. void setTypeFlags (int newFlags);
  41710. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  41711. };
  41712. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41713. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  41714. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  41715. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41716. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41717. /**
  41718. A listener for user selection events in a file browser.
  41719. This is used by a FileBrowserComponent or FileListComponent.
  41720. */
  41721. class JUCE_API FileBrowserListener
  41722. {
  41723. public:
  41724. /** Destructor. */
  41725. virtual ~FileBrowserListener();
  41726. /** Callback when the user selects a different file in the browser. */
  41727. virtual void selectionChanged() = 0;
  41728. /** Callback when the user clicks on a file in the browser. */
  41729. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  41730. /** Callback when the user double-clicks on a file in the browser. */
  41731. virtual void fileDoubleClicked (const File& file) = 0;
  41732. };
  41733. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41734. /*** End of inlined file: juce_FileBrowserListener.h ***/
  41735. /**
  41736. A base class for components that display a list of the files in a directory.
  41737. @see DirectoryContentsList
  41738. */
  41739. class JUCE_API DirectoryContentsDisplayComponent
  41740. {
  41741. public:
  41742. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  41743. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  41744. /** Destructor. */
  41745. virtual ~DirectoryContentsDisplayComponent();
  41746. /** Returns the number of files the user has got selected.
  41747. @see getSelectedFile
  41748. */
  41749. virtual int getNumSelectedFiles() const = 0;
  41750. /** Returns one of the files that the user has currently selected.
  41751. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  41752. @see getNumSelectedFiles
  41753. */
  41754. virtual const File getSelectedFile (int index) const = 0;
  41755. /** Deselects any selected files. */
  41756. virtual void deselectAllFiles() = 0;
  41757. /** Scrolls this view to the top. */
  41758. virtual void scrollToTop() = 0;
  41759. /** Adds a listener to be told when files are selected or clicked.
  41760. @see removeListener
  41761. */
  41762. void addListener (FileBrowserListener* listener);
  41763. /** Removes a listener.
  41764. @see addListener
  41765. */
  41766. void removeListener (FileBrowserListener* listener);
  41767. /** A set of colour IDs to use to change the colour of various aspects of the list.
  41768. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41769. methods.
  41770. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41771. */
  41772. enum ColourIds
  41773. {
  41774. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  41775. textColourId = 0x1000541, /**< The colour for the text. */
  41776. };
  41777. /** @internal */
  41778. void sendSelectionChangeMessage();
  41779. /** @internal */
  41780. void sendDoubleClickMessage (const File& file);
  41781. /** @internal */
  41782. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  41783. protected:
  41784. DirectoryContentsList& fileList;
  41785. ListenerList <FileBrowserListener> listeners;
  41786. private:
  41787. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  41788. };
  41789. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41790. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  41791. #endif
  41792. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41793. #endif
  41794. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41795. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  41796. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41797. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41798. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  41799. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41800. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41801. /**
  41802. Base class for components that live inside a file chooser dialog box and
  41803. show previews of the files that get selected.
  41804. One of these allows special extra information to be displayed for files
  41805. in a dialog box as the user selects them. Each time the current file or
  41806. directory is changed, the selectedFileChanged() method will be called
  41807. to allow it to update itself appropriately.
  41808. @see FileChooser, ImagePreviewComponent
  41809. */
  41810. class JUCE_API FilePreviewComponent : public Component
  41811. {
  41812. public:
  41813. /** Creates a FilePreviewComponent. */
  41814. FilePreviewComponent();
  41815. /** Destructor. */
  41816. ~FilePreviewComponent();
  41817. /** Called to indicate that the user's currently selected file has changed.
  41818. @param newSelectedFile the newly selected file or directory, which may be
  41819. File::nonexistent if none is selected.
  41820. */
  41821. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  41822. private:
  41823. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  41824. };
  41825. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41826. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  41827. /**
  41828. A component for browsing and selecting a file or directory to open or save.
  41829. This contains a FileListComponent and adds various boxes and controls for
  41830. navigating and selecting a file. It can work in different modes so that it can
  41831. be used for loading or saving a file, or for choosing a directory.
  41832. @see FileChooserDialogBox, FileChooser, FileListComponent
  41833. */
  41834. class JUCE_API FileBrowserComponent : public Component,
  41835. public ChangeBroadcaster,
  41836. private FileBrowserListener,
  41837. private TextEditorListener,
  41838. private ButtonListener,
  41839. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  41840. private FileFilter
  41841. {
  41842. public:
  41843. /** Various options for the browser.
  41844. A combination of these is passed into the FileBrowserComponent constructor.
  41845. */
  41846. enum FileChooserFlags
  41847. {
  41848. openMode = 1, /**< specifies that the component should allow the user to
  41849. choose an existing file with the intention of opening it. */
  41850. saveMode = 2, /**< specifies that the component should allow the user to specify
  41851. the name of a file that will be used to save something. */
  41852. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  41853. conjunction with canSelectDirectories). */
  41854. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  41855. conjuction with canSelectFiles). */
  41856. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  41857. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  41858. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  41859. };
  41860. /** Creates a FileBrowserComponent.
  41861. @param flags A combination of flags from the FileChooserFlags enumeration,
  41862. used to specify the component's behaviour. The flags must contain
  41863. either openMode or saveMode, and canSelectFiles and/or
  41864. canSelectDirectories.
  41865. @param initialFileOrDirectory The file or directory that should be selected when
  41866. the component begins. If this is File::nonexistent,
  41867. a default directory will be chosen.
  41868. @param fileFilter an optional filter to use to determine which files
  41869. are shown. If this is 0 then all files are displayed. Note
  41870. that a pointer is kept internally to this object, so
  41871. make sure that it is not deleted before the browser object
  41872. is deleted.
  41873. @param previewComp an optional preview component that will be used to
  41874. show previews of files that the user selects
  41875. */
  41876. FileBrowserComponent (int flags,
  41877. const File& initialFileOrDirectory,
  41878. const FileFilter* fileFilter,
  41879. FilePreviewComponent* previewComp);
  41880. /** Destructor. */
  41881. ~FileBrowserComponent();
  41882. /** Returns the number of files that the user has got selected.
  41883. If multiple select isn't active, this will only be 0 or 1. To get the complete
  41884. list of files they've chosen, pass an index to getCurrentFile().
  41885. */
  41886. int getNumSelectedFiles() const throw();
  41887. /** Returns one of the files that the user has chosen.
  41888. If the box has multi-select enabled, the index lets you specify which of the files
  41889. to get - see getNumSelectedFiles() to find out how many files were chosen.
  41890. @see getHighlightedFile
  41891. */
  41892. const File getSelectedFile (int index) const throw();
  41893. /** Deselects any files that are currently selected.
  41894. */
  41895. void deselectAllFiles();
  41896. /** Returns true if the currently selected file(s) are usable.
  41897. This can be used to decide whether the user can press "ok" for the
  41898. current file. What it does depends on the mode, so for example in an "open"
  41899. mode, this only returns true if a file has been selected and if it exists.
  41900. In a "save" mode, a non-existent file would also be valid.
  41901. */
  41902. bool currentFileIsValid() const;
  41903. /** This returns the last item in the view that the user has highlighted.
  41904. This may be different from getCurrentFile(), which returns the value
  41905. that is shown in the filename box, and if there are multiple selections,
  41906. this will only return one of them.
  41907. @see getSelectedFile
  41908. */
  41909. const File getHighlightedFile() const throw();
  41910. /** Returns the directory whose contents are currently being shown in the listbox. */
  41911. const File getRoot() const;
  41912. /** Changes the directory that's being shown in the listbox. */
  41913. void setRoot (const File& newRootDirectory);
  41914. /** Equivalent to pressing the "up" button to browse the parent directory. */
  41915. void goUp();
  41916. /** Refreshes the directory that's currently being listed. */
  41917. void refresh();
  41918. /** Changes the filter that's being used to sift the files. */
  41919. void setFileFilter (const FileFilter* newFileFilter);
  41920. /** Returns a verb to describe what should happen when the file is accepted.
  41921. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  41922. mode, it'll be "Save", etc.
  41923. */
  41924. virtual const String getActionVerb() const;
  41925. /** Returns true if the saveMode flag was set when this component was created.
  41926. */
  41927. bool isSaveMode() const throw();
  41928. /** Adds a listener to be told when the user selects and clicks on files.
  41929. @see removeListener
  41930. */
  41931. void addListener (FileBrowserListener* listener);
  41932. /** Removes a listener.
  41933. @see addListener
  41934. */
  41935. void removeListener (FileBrowserListener* listener);
  41936. /** @internal */
  41937. void resized();
  41938. /** @internal */
  41939. void buttonClicked (Button* b);
  41940. /** @internal */
  41941. void comboBoxChanged (ComboBox*);
  41942. /** @internal */
  41943. void textEditorTextChanged (TextEditor& editor);
  41944. /** @internal */
  41945. void textEditorReturnKeyPressed (TextEditor& editor);
  41946. /** @internal */
  41947. void textEditorEscapeKeyPressed (TextEditor& editor);
  41948. /** @internal */
  41949. void textEditorFocusLost (TextEditor& editor);
  41950. /** @internal */
  41951. bool keyPressed (const KeyPress& key);
  41952. /** @internal */
  41953. void selectionChanged();
  41954. /** @internal */
  41955. void fileClicked (const File& f, const MouseEvent& e);
  41956. /** @internal */
  41957. void fileDoubleClicked (const File& f);
  41958. /** @internal */
  41959. bool isFileSuitable (const File& file) const;
  41960. /** @internal */
  41961. bool isDirectorySuitable (const File&) const;
  41962. /** @internal */
  41963. FilePreviewComponent* getPreviewComponent() const throw();
  41964. protected:
  41965. /** Returns a list of names and paths for the default places the user might want to look.
  41966. Use an empty string to indicate a section break.
  41967. */
  41968. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  41969. private:
  41970. ScopedPointer <DirectoryContentsList> fileList;
  41971. const FileFilter* fileFilter;
  41972. int flags;
  41973. File currentRoot;
  41974. Array<File> chosenFiles;
  41975. ListenerList <FileBrowserListener> listeners;
  41976. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  41977. FilePreviewComponent* previewComp;
  41978. ComboBox currentPathBox;
  41979. TextEditor filenameBox;
  41980. Label fileLabel;
  41981. ScopedPointer<Button> goUpButton;
  41982. TimeSliceThread thread;
  41983. void sendListenerChangeMessage();
  41984. bool isFileOrDirSuitable (const File& f) const;
  41985. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  41986. };
  41987. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41988. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  41989. #endif
  41990. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41991. #endif
  41992. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  41993. /*** Start of inlined file: juce_FileChooser.h ***/
  41994. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  41995. #define __JUCE_FILECHOOSER_JUCEHEADER__
  41996. /**
  41997. Creates a dialog box to choose a file or directory to load or save.
  41998. To use a FileChooser:
  41999. - create one (as a local stack variable is the neatest way)
  42000. - call one of its browseFor.. methods
  42001. - if this returns true, the user has selected a file, so you can retrieve it
  42002. with the getResult() method.
  42003. e.g. @code
  42004. void loadMooseFile()
  42005. {
  42006. FileChooser myChooser ("Please select the moose you want to load...",
  42007. File::getSpecialLocation (File::userHomeDirectory),
  42008. "*.moose");
  42009. if (myChooser.browseForFileToOpen())
  42010. {
  42011. File mooseFile (myChooser.getResult());
  42012. loadMoose (mooseFile);
  42013. }
  42014. }
  42015. @endcode
  42016. */
  42017. class JUCE_API FileChooser
  42018. {
  42019. public:
  42020. /** Creates a FileChooser.
  42021. After creating one of these, use one of the browseFor... methods to display it.
  42022. @param dialogBoxTitle a text string to display in the dialog box to
  42023. tell the user what's going on
  42024. @param initialFileOrDirectory the file or directory that should be selected when
  42025. the dialog box opens. If this parameter is set to
  42026. File::nonexistent, a sensible default directory
  42027. will be used instead.
  42028. @param filePatternsAllowed a set of file patterns to specify which files can be
  42029. selected - each pattern should be separated by a
  42030. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  42031. empty string means that all files are allowed
  42032. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  42033. possible; if false, then a Juce-based browser dialog
  42034. box will always be used
  42035. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  42036. */
  42037. FileChooser (const String& dialogBoxTitle,
  42038. const File& initialFileOrDirectory = File::nonexistent,
  42039. const String& filePatternsAllowed = String::empty,
  42040. bool useOSNativeDialogBox = true);
  42041. /** Destructor. */
  42042. ~FileChooser();
  42043. /** Shows a dialog box to choose a file to open.
  42044. This will display the dialog box modally, using an "open file" mode, so that
  42045. it won't allow non-existent files or directories to be chosen.
  42046. @param previewComponent an optional component to display inside the dialog
  42047. box to show special info about the files that the user
  42048. is browsing. The component will not be deleted by this
  42049. object, so the caller must take care of it.
  42050. @returns true if the user selected a file, in which case, use the getResult()
  42051. method to find out what it was. Returns false if they cancelled instead.
  42052. @see browseForFileToSave, browseForDirectory
  42053. */
  42054. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  42055. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  42056. The files that are returned can be obtained by calling getResults(). See
  42057. browseForFileToOpen() for more info about the behaviour of this method.
  42058. */
  42059. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  42060. /** Shows a dialog box to choose a file to save.
  42061. This will display the dialog box modally, using an "save file" mode, so it
  42062. will allow non-existent files to be chosen, but not directories.
  42063. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  42064. the user if they're sure they want to overwrite a file that already
  42065. exists
  42066. @returns true if the user chose a file and pressed 'ok', in which case, use
  42067. the getResult() method to find out what the file was. Returns false
  42068. if they cancelled instead.
  42069. @see browseForFileToOpen, browseForDirectory
  42070. */
  42071. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  42072. /** Shows a dialog box to choose a directory.
  42073. This will display the dialog box modally, using an "open directory" mode, so it
  42074. will only allow directories to be returned, not files.
  42075. @returns true if the user chose a directory and pressed 'ok', in which case, use
  42076. the getResult() method to find out what they chose. Returns false
  42077. if they cancelled instead.
  42078. @see browseForFileToOpen, browseForFileToSave
  42079. */
  42080. bool browseForDirectory();
  42081. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  42082. The files that are returned can be obtained by calling getResults(). See
  42083. browseForFileToOpen() for more info about the behaviour of this method.
  42084. */
  42085. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  42086. /** Returns the last file that was chosen by one of the browseFor methods.
  42087. After calling the appropriate browseFor... method, this method lets you
  42088. find out what file or directory they chose.
  42089. Note that the file returned is only valid if the browse method returned true (i.e.
  42090. if the user pressed 'ok' rather than cancelling).
  42091. If you're using a multiple-file select, then use the getResults() method instead,
  42092. to obtain the list of all files chosen.
  42093. @see getResults
  42094. */
  42095. const File getResult() const;
  42096. /** Returns a list of all the files that were chosen during the last call to a
  42097. browse method.
  42098. This array may be empty if no files were chosen, or can contain multiple entries
  42099. if multiple files were chosen.
  42100. @see getResult
  42101. */
  42102. const Array<File>& getResults() const;
  42103. private:
  42104. String title, filters;
  42105. File startingFile;
  42106. Array<File> results;
  42107. bool useNativeDialogBox;
  42108. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  42109. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42110. FilePreviewComponent* previewComponent);
  42111. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  42112. const String& filters, bool selectsDirectories, bool selectsFiles,
  42113. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  42114. FilePreviewComponent* previewComponent);
  42115. JUCE_LEAK_DETECTOR (FileChooser);
  42116. };
  42117. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  42118. /*** End of inlined file: juce_FileChooser.h ***/
  42119. #endif
  42120. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42121. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  42122. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42123. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42124. /*** Start of inlined file: juce_ResizableWindow.h ***/
  42125. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42126. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42127. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  42128. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42129. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42130. /*** Start of inlined file: juce_DropShadower.h ***/
  42131. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42132. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  42133. /**
  42134. Adds a drop-shadow to a component.
  42135. This object creates and manages a set of components which sit around a
  42136. component, creating a gaussian shadow around it. The components will track
  42137. the position of the component and if it's brought to the front they'll also
  42138. follow this.
  42139. For desktop windows you don't need to use this class directly - just
  42140. set the Component::windowHasDropShadow flag when calling
  42141. Component::addToDesktop(), and the system will create one of these if it's
  42142. needed (which it obviously isn't on the Mac, for example).
  42143. */
  42144. class JUCE_API DropShadower : public ComponentListener
  42145. {
  42146. public:
  42147. /** Creates a DropShadower.
  42148. @param alpha the opacity of the shadows, from 0 to 1.0
  42149. @param xOffset the horizontal displacement of the shadow, in pixels
  42150. @param yOffset the vertical displacement of the shadow, in pixels
  42151. @param blurRadius the radius of the blur to use for creating the shadow
  42152. */
  42153. DropShadower (float alpha = 0.5f,
  42154. int xOffset = 1,
  42155. int yOffset = 5,
  42156. float blurRadius = 10.0f);
  42157. /** Destructor. */
  42158. virtual ~DropShadower();
  42159. /** Attaches the DropShadower to the component you want to shadow. */
  42160. void setOwner (Component* componentToFollow);
  42161. /** @internal */
  42162. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  42163. /** @internal */
  42164. void componentBroughtToFront (Component& component);
  42165. /** @internal */
  42166. void componentParentHierarchyChanged (Component& component);
  42167. /** @internal */
  42168. void componentVisibilityChanged (Component& component);
  42169. private:
  42170. Component* owner;
  42171. OwnedArray<Component> shadowWindows;
  42172. Image shadowImageSections[12];
  42173. const int xOffset, yOffset;
  42174. const float alpha, blurRadius;
  42175. bool reentrant;
  42176. void updateShadows();
  42177. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  42178. void bringShadowWindowsToFront();
  42179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  42180. };
  42181. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  42182. /*** End of inlined file: juce_DropShadower.h ***/
  42183. /**
  42184. A base class for top-level windows.
  42185. This class is used for components that are considered a major part of your
  42186. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  42187. etc. Things like menus that pop up briefly aren't derived from it.
  42188. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  42189. could itself be the child of another component.
  42190. The class manages a list of all instances of top-level windows that are in use,
  42191. and each one is also given the concept of being "active". The active window is
  42192. one that is actively being used by the user. This isn't quite the same as the
  42193. component with the keyboard focus, because there may be a popup menu or other
  42194. temporary window which gets keyboard focus while the active top level window is
  42195. unchanged.
  42196. A top-level window also has an optional drop-shadow.
  42197. @see ResizableWindow, DocumentWindow, DialogWindow
  42198. */
  42199. class JUCE_API TopLevelWindow : public Component
  42200. {
  42201. public:
  42202. /** Creates a TopLevelWindow.
  42203. @param name the name to give the component
  42204. @param addToDesktop if true, the window will be automatically added to the
  42205. desktop; if false, you can use it as a child component
  42206. */
  42207. TopLevelWindow (const String& name, bool addToDesktop);
  42208. /** Destructor. */
  42209. ~TopLevelWindow();
  42210. /** True if this is currently the TopLevelWindow that is actively being used.
  42211. This isn't quite the same as having keyboard focus, because the focus may be
  42212. on a child component or a temporary pop-up menu, etc, while this window is
  42213. still considered to be active.
  42214. @see activeWindowStatusChanged
  42215. */
  42216. bool isActiveWindow() const throw() { return windowIsActive_; }
  42217. /** This will set the bounds of the window so that it's centred in front of another
  42218. window.
  42219. If your app has a few windows open and want to pop up a dialog box for one of
  42220. them, you can use this to show it in front of the relevent parent window, which
  42221. is a bit neater than just having it appear in the middle of the screen.
  42222. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  42223. be used instead. If no window is focused, it'll just default to the middle of the
  42224. screen.
  42225. */
  42226. void centreAroundComponent (Component* componentToCentreAround,
  42227. int width, int height);
  42228. /** Turns the drop-shadow on and off. */
  42229. void setDropShadowEnabled (bool useShadow);
  42230. /** Sets whether an OS-native title bar will be used, or a Juce one.
  42231. @see isUsingNativeTitleBar
  42232. */
  42233. void setUsingNativeTitleBar (bool useNativeTitleBar);
  42234. /** Returns true if the window is currently using an OS-native title bar.
  42235. @see setUsingNativeTitleBar
  42236. */
  42237. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  42238. /** Returns the number of TopLevelWindow objects currently in use.
  42239. @see getTopLevelWindow
  42240. */
  42241. static int getNumTopLevelWindows() throw();
  42242. /** Returns one of the TopLevelWindow objects currently in use.
  42243. The index is 0 to (getNumTopLevelWindows() - 1).
  42244. */
  42245. static TopLevelWindow* getTopLevelWindow (int index) throw();
  42246. /** Returns the currently-active top level window.
  42247. There might not be one, of course, so this can return 0.
  42248. */
  42249. static TopLevelWindow* getActiveTopLevelWindow() throw();
  42250. /** @internal */
  42251. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  42252. protected:
  42253. /** This callback happens when this window becomes active or inactive.
  42254. @see isActiveWindow
  42255. */
  42256. virtual void activeWindowStatusChanged();
  42257. /** @internal */
  42258. void focusOfChildComponentChanged (FocusChangeType cause);
  42259. /** @internal */
  42260. void parentHierarchyChanged();
  42261. /** @internal */
  42262. virtual int getDesktopWindowStyleFlags() const;
  42263. /** @internal */
  42264. void recreateDesktopWindow();
  42265. /** @internal */
  42266. void visibilityChanged();
  42267. private:
  42268. friend class TopLevelWindowManager;
  42269. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  42270. ScopedPointer <DropShadower> shadower;
  42271. void setWindowActive (bool isNowActive);
  42272. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  42273. };
  42274. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  42275. /*** End of inlined file: juce_TopLevelWindow.h ***/
  42276. /*** Start of inlined file: juce_ComponentDragger.h ***/
  42277. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42278. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42279. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  42280. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42281. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42282. /**
  42283. A class that imposes restrictions on a Component's size or position.
  42284. This is used by classes such as ResizableCornerComponent,
  42285. ResizableBorderComponent and ResizableWindow.
  42286. The base class can impose some basic size and position limits, but you can
  42287. also subclass this for custom uses.
  42288. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  42289. */
  42290. class JUCE_API ComponentBoundsConstrainer
  42291. {
  42292. public:
  42293. /** When first created, the object will not impose any restrictions on the components. */
  42294. ComponentBoundsConstrainer() throw();
  42295. /** Destructor. */
  42296. virtual ~ComponentBoundsConstrainer();
  42297. /** Imposes a minimum width limit. */
  42298. void setMinimumWidth (int minimumWidth) throw();
  42299. /** Returns the current minimum width. */
  42300. int getMinimumWidth() const throw() { return minW; }
  42301. /** Imposes a maximum width limit. */
  42302. void setMaximumWidth (int maximumWidth) throw();
  42303. /** Returns the current maximum width. */
  42304. int getMaximumWidth() const throw() { return maxW; }
  42305. /** Imposes a minimum height limit. */
  42306. void setMinimumHeight (int minimumHeight) throw();
  42307. /** Returns the current minimum height. */
  42308. int getMinimumHeight() const throw() { return minH; }
  42309. /** Imposes a maximum height limit. */
  42310. void setMaximumHeight (int maximumHeight) throw();
  42311. /** Returns the current maximum height. */
  42312. int getMaximumHeight() const throw() { return maxH; }
  42313. /** Imposes a minimum width and height limit. */
  42314. void setMinimumSize (int minimumWidth,
  42315. int minimumHeight) throw();
  42316. /** Imposes a maximum width and height limit. */
  42317. void setMaximumSize (int maximumWidth,
  42318. int maximumHeight) throw();
  42319. /** Set all the maximum and minimum dimensions. */
  42320. void setSizeLimits (int minimumWidth,
  42321. int minimumHeight,
  42322. int maximumWidth,
  42323. int maximumHeight) throw();
  42324. /** Sets the amount by which the component is allowed to go off-screen.
  42325. The values indicate how many pixels must remain on-screen when dragged off
  42326. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  42327. when the component goes off the top of the screen, its y-position will be
  42328. clipped so that there are always at least 10 pixels on-screen. In other words,
  42329. the lowest y-position it can take would be (10 - the component's height).
  42330. If you pass 0 or less for one of these amounts, the component is allowed
  42331. to move beyond that edge completely, with no restrictions at all.
  42332. If you pass a very large number (i.e. larger that the dimensions of the
  42333. component itself), then the component won't be allowed to overlap that
  42334. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  42335. the component will bump into the left side of the screen and go no further.
  42336. */
  42337. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  42338. int minimumWhenOffTheLeft,
  42339. int minimumWhenOffTheBottom,
  42340. int minimumWhenOffTheRight) throw();
  42341. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42342. int getMinimumWhenOffTheTop() const throw() { return minOffTop; }
  42343. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42344. int getMinimumWhenOffTheLeft() const throw() { return minOffLeft; }
  42345. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42346. int getMinimumWhenOffTheBottom() const throw() { return minOffBottom; }
  42347. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  42348. int getMinimumWhenOffTheRight() const throw() { return minOffRight; }
  42349. /** Specifies a width-to-height ratio that the resizer should always maintain.
  42350. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  42351. will always be maintained as this multiple of the height.
  42352. @see setResizeLimits
  42353. */
  42354. void setFixedAspectRatio (double widthOverHeight) throw();
  42355. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  42356. If no aspect ratio is being enforced, this will return 0.
  42357. */
  42358. double getFixedAspectRatio() const throw();
  42359. /** This callback changes the given co-ordinates to impose whatever the current
  42360. constraints are set to be.
  42361. @param bounds the target position that should be examined and adjusted
  42362. @param previousBounds the component's current size
  42363. @param limits the region in which the component can be positioned
  42364. @param isStretchingTop whether the top edge of the component is being resized
  42365. @param isStretchingLeft whether the left edge of the component is being resized
  42366. @param isStretchingBottom whether the bottom edge of the component is being resized
  42367. @param isStretchingRight whether the right edge of the component is being resized
  42368. */
  42369. virtual void checkBounds (Rectangle<int>& bounds,
  42370. const Rectangle<int>& previousBounds,
  42371. const Rectangle<int>& limits,
  42372. bool isStretchingTop,
  42373. bool isStretchingLeft,
  42374. bool isStretchingBottom,
  42375. bool isStretchingRight);
  42376. /** This callback happens when the resizer is about to start dragging. */
  42377. virtual void resizeStart();
  42378. /** This callback happens when the resizer has finished dragging. */
  42379. virtual void resizeEnd();
  42380. /** Checks the given bounds, and then sets the component to the corrected size. */
  42381. void setBoundsForComponent (Component* component,
  42382. const Rectangle<int>& bounds,
  42383. bool isStretchingTop,
  42384. bool isStretchingLeft,
  42385. bool isStretchingBottom,
  42386. bool isStretchingRight);
  42387. /** Performs a check on the current size of a component, and moves or resizes
  42388. it if it fails the constraints.
  42389. */
  42390. void checkComponentBounds (Component* component);
  42391. /** Called by setBoundsForComponent() to apply a new constrained size to a
  42392. component.
  42393. By default this just calls setBounds(), but it virtual in case it's needed for
  42394. extremely cunning purposes.
  42395. */
  42396. virtual void applyBoundsToComponent (Component* component,
  42397. const Rectangle<int>& bounds);
  42398. private:
  42399. int minW, maxW, minH, maxH;
  42400. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  42401. double aspectRatio;
  42402. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  42403. };
  42404. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42405. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  42406. /**
  42407. An object to take care of the logic for dragging components around with the mouse.
  42408. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  42409. then in your mouseDrag() callback, call dragComponent().
  42410. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  42411. to limit the component's position and keep it on-screen.
  42412. e.g. @code
  42413. class MyDraggableComp
  42414. {
  42415. ComponentDragger myDragger;
  42416. void mouseDown (const MouseEvent& e)
  42417. {
  42418. myDragger.startDraggingComponent (this, e);
  42419. }
  42420. void mouseDrag (const MouseEvent& e)
  42421. {
  42422. myDragger.dragComponent (this, e, 0);
  42423. }
  42424. };
  42425. @endcode
  42426. */
  42427. class JUCE_API ComponentDragger
  42428. {
  42429. public:
  42430. /** Creates a ComponentDragger. */
  42431. ComponentDragger();
  42432. /** Destructor. */
  42433. virtual ~ComponentDragger();
  42434. /** Call this from your component's mouseDown() method, to prepare for dragging.
  42435. @param componentToDrag the component that you want to drag
  42436. @param e the mouse event that is triggering the drag
  42437. @see dragComponent
  42438. */
  42439. void startDraggingComponent (Component* componentToDrag,
  42440. const MouseEvent& e);
  42441. /** Call this from your mouseDrag() callback to move the component.
  42442. This will move the component, but will first check the validity of the
  42443. component's new position using the checkPosition() method, which you
  42444. can override if you need to enforce special positioning limits on the
  42445. component.
  42446. @param componentToDrag the component that you want to drag
  42447. @param e the current mouse-drag event
  42448. @param constrainer an optional constrainer object that should be used
  42449. to apply limits to the component's position. Pass
  42450. null if you don't want to contrain the movement.
  42451. @see startDraggingComponent
  42452. */
  42453. void dragComponent (Component* componentToDrag,
  42454. const MouseEvent& e,
  42455. ComponentBoundsConstrainer* constrainer);
  42456. private:
  42457. Point<int> mouseDownWithinTarget;
  42458. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  42459. };
  42460. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  42461. /*** End of inlined file: juce_ComponentDragger.h ***/
  42462. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  42463. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42464. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42465. /**
  42466. A component that resizes its parent component when dragged.
  42467. This component forms a frame around the edge of a component, allowing it to
  42468. be dragged by the edges or corners to resize it - like the way windows are
  42469. resized in MSWindows or Linux.
  42470. To use it, just add it to your component, making it fill the entire parent component
  42471. (there's a mouse hit-test that only traps mouse-events which land around the
  42472. edge of the component, so it's even ok to put it on top of any other components
  42473. you're using). Make sure you rescale the resizer component to fill the parent
  42474. each time the parent's size changes.
  42475. @see ResizableCornerComponent
  42476. */
  42477. class JUCE_API ResizableBorderComponent : public Component
  42478. {
  42479. public:
  42480. /** Creates a resizer.
  42481. Pass in the target component which you want to be resized when this one is
  42482. dragged.
  42483. The target component will usually be a parent of the resizer component, but this
  42484. isn't mandatory.
  42485. Remember that when the target component is resized, it'll need to move and
  42486. resize this component to keep it in place, as this won't happen automatically.
  42487. If the constrainer parameter is non-zero, then this object will be used to enforce
  42488. limits on the size and position that the component can be stretched to. Make sure
  42489. that the constrainer isn't deleted while still in use by this object.
  42490. @see ComponentBoundsConstrainer
  42491. */
  42492. ResizableBorderComponent (Component* componentToResize,
  42493. ComponentBoundsConstrainer* constrainer);
  42494. /** Destructor. */
  42495. ~ResizableBorderComponent();
  42496. /** Specifies how many pixels wide the draggable edges of this component are.
  42497. @see getBorderThickness
  42498. */
  42499. void setBorderThickness (const BorderSize<int>& newBorderSize);
  42500. /** Returns the number of pixels wide that the draggable edges of this component are.
  42501. @see setBorderThickness
  42502. */
  42503. const BorderSize<int> getBorderThickness() const;
  42504. /** Represents the different sections of a resizable border, which allow it to
  42505. resized in different ways.
  42506. */
  42507. class Zone
  42508. {
  42509. public:
  42510. enum Zones
  42511. {
  42512. centre = 0,
  42513. left = 1,
  42514. top = 2,
  42515. right = 4,
  42516. bottom = 8
  42517. };
  42518. /** Creates a Zone from a combination of the flags in \enum Zones. */
  42519. explicit Zone (int zoneFlags = 0) throw();
  42520. Zone (const Zone& other) throw();
  42521. Zone& operator= (const Zone& other) throw();
  42522. bool operator== (const Zone& other) const throw();
  42523. bool operator!= (const Zone& other) const throw();
  42524. /** Given a point within a rectangle with a resizable border, this returns the
  42525. zone that the point lies within.
  42526. */
  42527. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  42528. const BorderSize<int>& border,
  42529. const Point<int>& position);
  42530. /** Returns an appropriate mouse-cursor for this resize zone. */
  42531. const MouseCursor getMouseCursor() const throw();
  42532. /** Returns true if dragging this zone will move the enire object without resizing it. */
  42533. bool isDraggingWholeObject() const throw() { return zone == centre; }
  42534. /** Returns true if dragging this zone will move the object's left edge. */
  42535. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  42536. /** Returns true if dragging this zone will move the object's right edge. */
  42537. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  42538. /** Returns true if dragging this zone will move the object's top edge. */
  42539. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  42540. /** Returns true if dragging this zone will move the object's bottom edge. */
  42541. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  42542. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  42543. applies to.
  42544. */
  42545. template <typename ValueType>
  42546. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  42547. const Point<ValueType>& distance) const throw()
  42548. {
  42549. if (isDraggingWholeObject())
  42550. return original + distance;
  42551. if (isDraggingLeftEdge())
  42552. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  42553. if (isDraggingRightEdge())
  42554. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  42555. if (isDraggingTopEdge())
  42556. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  42557. if (isDraggingBottomEdge())
  42558. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  42559. return original;
  42560. }
  42561. /** Returns the raw flags for this zone. */
  42562. int getZoneFlags() const throw() { return zone; }
  42563. private:
  42564. int zone;
  42565. };
  42566. protected:
  42567. /** @internal */
  42568. void paint (Graphics& g);
  42569. /** @internal */
  42570. void mouseEnter (const MouseEvent& e);
  42571. /** @internal */
  42572. void mouseMove (const MouseEvent& e);
  42573. /** @internal */
  42574. void mouseDown (const MouseEvent& e);
  42575. /** @internal */
  42576. void mouseDrag (const MouseEvent& e);
  42577. /** @internal */
  42578. void mouseUp (const MouseEvent& e);
  42579. /** @internal */
  42580. bool hitTest (int x, int y);
  42581. private:
  42582. WeakReference<Component> component;
  42583. ComponentBoundsConstrainer* constrainer;
  42584. BorderSize<int> borderSize;
  42585. Rectangle<int> originalBounds;
  42586. Zone mouseZone;
  42587. void updateMouseZone (const MouseEvent& e);
  42588. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  42589. };
  42590. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42591. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  42592. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  42593. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42594. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42595. /** A component that resizes a parent component when dragged.
  42596. This is the small triangular stripey resizer component you get in the bottom-right
  42597. of windows (more commonly on the Mac than Windows). Put one in the corner of
  42598. a larger component and it will automatically resize its parent when it gets dragged
  42599. around.
  42600. @see ResizableFrameComponent
  42601. */
  42602. class JUCE_API ResizableCornerComponent : public Component
  42603. {
  42604. public:
  42605. /** Creates a resizer.
  42606. Pass in the target component which you want to be resized when this one is
  42607. dragged.
  42608. The target component will usually be a parent of the resizer component, but this
  42609. isn't mandatory.
  42610. Remember that when the target component is resized, it'll need to move and
  42611. resize this component to keep it in place, as this won't happen automatically.
  42612. If the constrainer parameter is non-zero, then this object will be used to enforce
  42613. limits on the size and position that the component can be stretched to. Make sure
  42614. that the constrainer isn't deleted while still in use by this object. If you
  42615. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  42616. @see ComponentBoundsConstrainer
  42617. */
  42618. ResizableCornerComponent (Component* componentToResize,
  42619. ComponentBoundsConstrainer* constrainer);
  42620. /** Destructor. */
  42621. ~ResizableCornerComponent();
  42622. protected:
  42623. /** @internal */
  42624. void paint (Graphics& g);
  42625. /** @internal */
  42626. void mouseDown (const MouseEvent& e);
  42627. /** @internal */
  42628. void mouseDrag (const MouseEvent& e);
  42629. /** @internal */
  42630. void mouseUp (const MouseEvent& e);
  42631. /** @internal */
  42632. bool hitTest (int x, int y);
  42633. private:
  42634. WeakReference<Component> component;
  42635. ComponentBoundsConstrainer* constrainer;
  42636. Rectangle<int> originalBounds;
  42637. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  42638. };
  42639. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42640. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  42641. /**
  42642. A base class for top-level windows that can be dragged around and resized.
  42643. To add content to the window, use its setContentOwned() or setContentNonOwned() methods
  42644. to give it a component that will remain positioned inside it (leaving a gap around
  42645. the edges for a border).
  42646. It's not advisable to add child components directly to a ResizableWindow: put them
  42647. inside your content component instead. And overriding methods like resized(), moved(), etc
  42648. is also not recommended - instead override these methods for your content component.
  42649. (If for some obscure reason you do need to override these methods, always remember to
  42650. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  42651. decorations correctly).
  42652. By default resizing isn't enabled - use the setResizable() method to enable it and
  42653. to choose the style of resizing to use.
  42654. @see TopLevelWindow
  42655. */
  42656. class JUCE_API ResizableWindow : public TopLevelWindow
  42657. {
  42658. public:
  42659. /** Creates a ResizableWindow.
  42660. This constructor doesn't specify a background colour, so the LookAndFeel's default
  42661. background colour will be used.
  42662. @param name the name to give the component
  42663. @param addToDesktop if true, the window will be automatically added to the
  42664. desktop; if false, you can use it as a child component
  42665. */
  42666. ResizableWindow (const String& name,
  42667. bool addToDesktop);
  42668. /** Creates a ResizableWindow.
  42669. @param name the name to give the component
  42670. @param backgroundColour the colour to use for filling the window's background.
  42671. @param addToDesktop if true, the window will be automatically added to the
  42672. desktop; if false, you can use it as a child component
  42673. */
  42674. ResizableWindow (const String& name,
  42675. const Colour& backgroundColour,
  42676. bool addToDesktop);
  42677. /** Destructor.
  42678. If a content component has been set with setContentOwned(), it will be deleted.
  42679. */
  42680. ~ResizableWindow();
  42681. /** Returns the colour currently being used for the window's background.
  42682. As a convenience the window will fill itself with this colour, but you
  42683. can override the paint() method if you need more customised behaviour.
  42684. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  42685. @see setBackgroundColour
  42686. */
  42687. const Colour getBackgroundColour() const throw();
  42688. /** Changes the colour currently being used for the window's background.
  42689. As a convenience the window will fill itself with this colour, but you
  42690. can override the paint() method if you need more customised behaviour.
  42691. Note that the opaque state of this window is altered by this call to reflect
  42692. the opacity of the colour passed-in. On window systems which can't support
  42693. semi-transparent windows this might cause problems, (though it's unlikely you'll
  42694. be using this class as a base for a semi-transparent component anyway).
  42695. You can also use the ResizableWindow::backgroundColourId colour id to set
  42696. this colour.
  42697. @see getBackgroundColour
  42698. */
  42699. void setBackgroundColour (const Colour& newColour);
  42700. /** Make the window resizable or fixed.
  42701. @param shouldBeResizable whether it's resizable at all
  42702. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  42703. bottom-right; if false, it'll use a ResizableBorderComponent
  42704. around the edge
  42705. @see setResizeLimits, isResizable
  42706. */
  42707. void setResizable (bool shouldBeResizable,
  42708. bool useBottomRightCornerResizer);
  42709. /** True if resizing is enabled.
  42710. @see setResizable
  42711. */
  42712. bool isResizable() const throw();
  42713. /** This sets the maximum and minimum sizes for the window.
  42714. If the window's current size is outside these limits, it will be resized to
  42715. make sure it's within them.
  42716. Calling setBounds() on the component will bypass any size checking - it's only when
  42717. the window is being resized by the user that these values are enforced.
  42718. @see setResizable, setFixedAspectRatio
  42719. */
  42720. void setResizeLimits (int newMinimumWidth,
  42721. int newMinimumHeight,
  42722. int newMaximumWidth,
  42723. int newMaximumHeight) throw();
  42724. /** Returns the bounds constrainer object that this window is using.
  42725. You can access this to change its properties.
  42726. */
  42727. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  42728. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  42729. A pointer to the object you pass in will be kept, but it won't be deleted
  42730. by this object, so it's the caller's responsiblity to manage it.
  42731. If you pass 0, then no contraints will be placed on the positioning of the window.
  42732. */
  42733. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  42734. /** Calls the window's setBounds method, after first checking these bounds
  42735. with the current constrainer.
  42736. @see setConstrainer
  42737. */
  42738. void setBoundsConstrained (const Rectangle<int>& bounds);
  42739. /** Returns true if the window is currently in full-screen mode.
  42740. @see setFullScreen
  42741. */
  42742. bool isFullScreen() const;
  42743. /** Puts the window into full-screen mode, or restores it to its normal size.
  42744. If true, the window will become full-screen; if false, it will return to the
  42745. last size it was before being made full-screen.
  42746. @see isFullScreen
  42747. */
  42748. void setFullScreen (bool shouldBeFullScreen);
  42749. /** Returns true if the window is currently minimised.
  42750. @see setMinimised
  42751. */
  42752. bool isMinimised() const;
  42753. /** Minimises the window, or restores it to its previous position and size.
  42754. When being un-minimised, it'll return to the last position and size it
  42755. was in before being minimised.
  42756. @see isMinimised
  42757. */
  42758. void setMinimised (bool shouldMinimise);
  42759. /** Returns a string which encodes the window's current size and position.
  42760. This string will encapsulate the window's size, position, and whether it's
  42761. in full-screen mode. It's intended for letting your application save and
  42762. restore a window's position.
  42763. Use the restoreWindowStateFromString() to restore from a saved state.
  42764. @see restoreWindowStateFromString
  42765. */
  42766. const String getWindowStateAsString();
  42767. /** Restores the window to a previously-saved size and position.
  42768. This restores the window's size, positon and full-screen status from an
  42769. string that was previously created with the getWindowStateAsString()
  42770. method.
  42771. @returns false if the string wasn't a valid window state
  42772. @see getWindowStateAsString
  42773. */
  42774. bool restoreWindowStateFromString (const String& previousState);
  42775. /** Returns the current content component.
  42776. This will be the component set by setContentOwned() or setContentNonOwned, or 0 if none
  42777. has yet been specified.
  42778. @see setContentOwned, setContentNonOwned
  42779. */
  42780. Component* getContentComponent() const throw() { return contentComponent; }
  42781. /** Changes the current content component.
  42782. This sets a component that will be placed in the centre of the ResizableWindow,
  42783. (leaving a space around the edge for the border).
  42784. You should never add components directly to a ResizableWindow (or any of its subclasses)
  42785. with addChildComponent(). Instead, add them to the content component.
  42786. @param newContentComponent the new component to use - this component will be deleted when it's
  42787. no longer needed (i.e. when the window is deleted or a new content
  42788. component is set for it). To set a component that this window will not
  42789. delete, call setContentNonOwned() instead.
  42790. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  42791. such that it always fits around the size of the content component. If false,
  42792. the new content will be resized to fit the current space available.
  42793. */
  42794. void setContentOwned (Component* newContentComponent,
  42795. bool resizeToFitWhenContentChangesSize);
  42796. /** Changes the current content component.
  42797. This sets a component that will be placed in the centre of the ResizableWindow,
  42798. (leaving a space around the edge for the border).
  42799. You should never add components directly to a ResizableWindow (or any of its subclasses)
  42800. with addChildComponent(). Instead, add them to the content component.
  42801. @param newContentComponent the new component to use - this component will NOT be deleted by this
  42802. component, so it's the caller's responsibility to manage its lifetime (it's
  42803. ok to delete it while this window is still using it). To set a content
  42804. component that the window will delete, call setContentOwned() instead.
  42805. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  42806. such that it always fits around the size of the content component. If false,
  42807. the new content will be resized to fit the current space available.
  42808. */
  42809. void setContentNonOwned (Component* newContentComponent,
  42810. bool resizeToFitWhenContentChangesSize);
  42811. /** Removes the current content component.
  42812. If the previous content component was added with setContentOwned(), it will also be deleted. If
  42813. it was added with setContentNonOwned(), it will simply be removed from this component.
  42814. */
  42815. void clearContentComponent();
  42816. /** Changes the window so that the content component ends up with the specified size.
  42817. This is basically a setSize call on the window, but which adds on the borders,
  42818. so you can specify the content component's target size.
  42819. */
  42820. void setContentComponentSize (int width, int height);
  42821. /** Returns the width of the frame to use around the window.
  42822. @see getContentComponentBorder
  42823. */
  42824. virtual const BorderSize<int> getBorderThickness();
  42825. /** Returns the insets to use when positioning the content component.
  42826. @see getBorderThickness
  42827. */
  42828. virtual const BorderSize<int> getContentComponentBorder();
  42829. /** A set of colour IDs to use to change the colour of various aspects of the window.
  42830. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42831. methods.
  42832. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42833. */
  42834. enum ColourIds
  42835. {
  42836. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  42837. };
  42838. /** @deprecated - use setContentOwned() and setContentNonOwned() instead. */
  42839. JUCE_DEPRECATED (void setContentComponent (Component* newContentComponent,
  42840. bool deleteOldOne = true,
  42841. bool resizeToFit = false));
  42842. protected:
  42843. /** @internal */
  42844. void paint (Graphics& g);
  42845. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  42846. void moved();
  42847. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  42848. void resized();
  42849. /** @internal */
  42850. void mouseDown (const MouseEvent& e);
  42851. /** @internal */
  42852. void mouseDrag (const MouseEvent& e);
  42853. /** @internal */
  42854. void lookAndFeelChanged();
  42855. /** @internal */
  42856. void childBoundsChanged (Component* child);
  42857. /** @internal */
  42858. void parentSizeChanged();
  42859. /** @internal */
  42860. void visibilityChanged();
  42861. /** @internal */
  42862. void activeWindowStatusChanged();
  42863. /** @internal */
  42864. int getDesktopWindowStyleFlags() const;
  42865. #if JUCE_DEBUG
  42866. /** Overridden to warn people about adding components directly to this component
  42867. instead of using setContentOwned().
  42868. If you know what you're doing and are sure you really want to add a component, specify
  42869. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  42870. */
  42871. void addChildComponent (Component* child, int zOrder = -1);
  42872. /** Overridden to warn people about adding components directly to this component
  42873. instead of using setContentOwned().
  42874. If you know what you're doing and are sure you really want to add a component, specify
  42875. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  42876. */
  42877. void addAndMakeVisible (Component* child, int zOrder = -1);
  42878. #endif
  42879. ScopedPointer <ResizableCornerComponent> resizableCorner;
  42880. ScopedPointer <ResizableBorderComponent> resizableBorder;
  42881. private:
  42882. Component::SafePointer <Component> contentComponent;
  42883. bool ownsContentComponent, resizeToFitContent, fullscreen;
  42884. ComponentDragger dragger;
  42885. Rectangle<int> lastNonFullScreenPos;
  42886. ComponentBoundsConstrainer defaultConstrainer;
  42887. ComponentBoundsConstrainer* constrainer;
  42888. #if JUCE_DEBUG
  42889. bool hasBeenResized;
  42890. #endif
  42891. void updateLastPos();
  42892. void setContent (Component* newComp, bool takeOwnership, bool resizeToFit);
  42893. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  42894. // The parameters for these methods have changed - please update your code!
  42895. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  42896. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  42897. #endif
  42898. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  42899. };
  42900. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42901. /*** End of inlined file: juce_ResizableWindow.h ***/
  42902. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  42903. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  42904. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  42905. /**
  42906. A glyph from a particular font, with a particular size, style,
  42907. typeface and position.
  42908. @see GlyphArrangement, Font
  42909. */
  42910. class JUCE_API PositionedGlyph
  42911. {
  42912. public:
  42913. PositionedGlyph (const PositionedGlyph& other);
  42914. /** Returns the character the glyph represents. */
  42915. juce_wchar getCharacter() const { return character; }
  42916. /** Checks whether the glyph is actually empty. */
  42917. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  42918. /** Returns the position of the glyph's left-hand edge. */
  42919. float getLeft() const { return x; }
  42920. /** Returns the position of the glyph's right-hand edge. */
  42921. float getRight() const { return x + w; }
  42922. /** Returns the y position of the glyph's baseline. */
  42923. float getBaselineY() const { return y; }
  42924. /** Returns the y position of the top of the glyph. */
  42925. float getTop() const { return y - font.getAscent(); }
  42926. /** Returns the y position of the bottom of the glyph. */
  42927. float getBottom() const { return y + font.getDescent(); }
  42928. /** Returns the bounds of the glyph. */
  42929. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  42930. /** Shifts the glyph's position by a relative amount. */
  42931. void moveBy (float deltaX, float deltaY);
  42932. /** Draws the glyph into a graphics context. */
  42933. void draw (const Graphics& g) const;
  42934. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  42935. void draw (const Graphics& g, const AffineTransform& transform) const;
  42936. /** Returns the path for this glyph.
  42937. @param path the glyph's outline will be appended to this path
  42938. */
  42939. void createPath (Path& path) const;
  42940. /** Checks to see if a point lies within this glyph. */
  42941. bool hitTest (float x, float y) const;
  42942. private:
  42943. friend class GlyphArrangement;
  42944. float x, y, w;
  42945. Font font;
  42946. juce_wchar character;
  42947. int glyph;
  42948. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  42949. JUCE_LEAK_DETECTOR (PositionedGlyph);
  42950. };
  42951. /**
  42952. A set of glyphs, each with a position.
  42953. You can create a GlyphArrangement, text to it and then draw it onto a
  42954. graphics context. It's used internally by the text methods in the
  42955. Graphics class, but can be used directly if more control is needed.
  42956. @see Font, PositionedGlyph
  42957. */
  42958. class JUCE_API GlyphArrangement
  42959. {
  42960. public:
  42961. /** Creates an empty arrangement. */
  42962. GlyphArrangement();
  42963. /** Takes a copy of another arrangement. */
  42964. GlyphArrangement (const GlyphArrangement& other);
  42965. /** Copies another arrangement onto this one.
  42966. To add another arrangement without clearing this one, use addGlyphArrangement().
  42967. */
  42968. GlyphArrangement& operator= (const GlyphArrangement& other);
  42969. /** Destructor. */
  42970. ~GlyphArrangement();
  42971. /** Returns the total number of glyphs in the arrangement. */
  42972. int getNumGlyphs() const throw() { return glyphs.size(); }
  42973. /** Returns one of the glyphs from the arrangement.
  42974. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  42975. careful not to pass an out-of-range index here, as it
  42976. doesn't do any bounds-checking.
  42977. */
  42978. PositionedGlyph& getGlyph (int index) const;
  42979. /** Clears all text from the arrangement and resets it.
  42980. */
  42981. void clear();
  42982. /** Appends a line of text to the arrangement.
  42983. This will add the text as a single line, where x is the left-hand edge of the
  42984. first character, and y is the position for the text's baseline.
  42985. If the text contains new-lines or carriage-returns, this will ignore them - use
  42986. addJustifiedText() to add multi-line arrangements.
  42987. */
  42988. void addLineOfText (const Font& font,
  42989. const String& text,
  42990. float x, float y);
  42991. /** Adds a line of text, truncating it if it's wider than a specified size.
  42992. This is the same as addLineOfText(), but if the line's width exceeds the value
  42993. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  42994. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  42995. */
  42996. void addCurtailedLineOfText (const Font& font,
  42997. const String& text,
  42998. float x, float y,
  42999. float maxWidthPixels,
  43000. bool useEllipsis);
  43001. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  43002. This will add text to the arrangement, breaking it into new lines either where there
  43003. is a new-line or carriage-return character in the text, or where a line's width
  43004. exceeds the value set in maxLineWidth.
  43005. Each line that is added will be laid out using the flags set in horizontalLayout, so
  43006. the lines can be left- or right-justified, or centred horizontally in the space
  43007. between x and (x + maxLineWidth).
  43008. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  43009. lines will be placed below it, separated by a distance of font.getHeight().
  43010. */
  43011. void addJustifiedText (const Font& font,
  43012. const String& text,
  43013. float x, float y,
  43014. float maxLineWidth,
  43015. const Justification& horizontalLayout);
  43016. /** Tries to fit some text withing a given space.
  43017. This does its best to make the given text readable within the specified rectangle,
  43018. so it useful for labelling things.
  43019. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  43020. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  43021. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  43022. it's been truncated.
  43023. A Justification parameter lets you specify how the text is laid out within the rectangle,
  43024. both horizontally and vertically.
  43025. @see Graphics::drawFittedText
  43026. */
  43027. void addFittedText (const Font& font,
  43028. const String& text,
  43029. float x, float y, float width, float height,
  43030. const Justification& layout,
  43031. int maximumLinesToUse,
  43032. float minimumHorizontalScale = 0.7f);
  43033. /** Appends another glyph arrangement to this one. */
  43034. void addGlyphArrangement (const GlyphArrangement& other);
  43035. /** Draws this glyph arrangement to a graphics context.
  43036. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  43037. method, which renders the glyphs as filled vectors.
  43038. */
  43039. void draw (const Graphics& g) const;
  43040. /** Draws this glyph arrangement to a graphics context.
  43041. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  43042. method for non-transformed arrangements.
  43043. */
  43044. void draw (const Graphics& g, const AffineTransform& transform) const;
  43045. /** Converts the set of glyphs into a path.
  43046. @param path the glyphs' outlines will be appended to this path
  43047. */
  43048. void createPath (Path& path) const;
  43049. /** Looks for a glyph that contains the given co-ordinate.
  43050. @returns the index of the glyph, or -1 if none were found.
  43051. */
  43052. int findGlyphIndexAt (float x, float y) const;
  43053. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  43054. @param startIndex the first glyph to test
  43055. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  43056. startIndex will be included
  43057. @param includeWhitespace if true, the extent of any whitespace characters will also
  43058. be taken into account
  43059. */
  43060. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  43061. /** Shifts a set of glyphs by a given amount.
  43062. @param startIndex the first glyph to transform
  43063. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  43064. startIndex will be used
  43065. @param deltaX the amount to add to their x-positions
  43066. @param deltaY the amount to add to their y-positions
  43067. */
  43068. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  43069. float deltaX, float deltaY);
  43070. /** Removes a set of glyphs from the arrangement.
  43071. @param startIndex the first glyph to remove
  43072. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  43073. startIndex will be deleted
  43074. */
  43075. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  43076. /** Expands or compresses a set of glyphs horizontally.
  43077. @param startIndex the first glyph to transform
  43078. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  43079. startIndex will be used
  43080. @param horizontalScaleFactor how much to scale their horizontal width by
  43081. */
  43082. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  43083. float horizontalScaleFactor);
  43084. /** Justifies a set of glyphs within a given space.
  43085. This moves the glyphs as a block so that the whole thing is located within the
  43086. given rectangle with the specified layout.
  43087. If the Justification::horizontallyJustified flag is specified, each line will
  43088. be stretched out to fill the specified width.
  43089. */
  43090. void justifyGlyphs (int startIndex, int numGlyphs,
  43091. float x, float y, float width, float height,
  43092. const Justification& justification);
  43093. private:
  43094. OwnedArray <PositionedGlyph> glyphs;
  43095. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  43096. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  43097. const Justification& justification, float minimumHorizontalScale);
  43098. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  43099. JUCE_LEAK_DETECTOR (GlyphArrangement);
  43100. };
  43101. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  43102. /*** End of inlined file: juce_GlyphArrangement.h ***/
  43103. /*** Start of inlined file: juce_AlertWindow.h ***/
  43104. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43105. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  43106. /*** Start of inlined file: juce_TextLayout.h ***/
  43107. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  43108. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  43109. class Graphics;
  43110. /**
  43111. A laid-out arrangement of text.
  43112. You can add text in different fonts to a TextLayout object, then call its
  43113. layout() method to word-wrap it into lines. The layout can then be drawn
  43114. using a graphics context.
  43115. It's handy if you've got a message to display, because you can format it,
  43116. measure the extent of the layout, and then create a suitably-sized window
  43117. to show it in.
  43118. @see Font, Graphics::drawFittedText, GlyphArrangement
  43119. */
  43120. class JUCE_API TextLayout
  43121. {
  43122. public:
  43123. /** Creates an empty text layout.
  43124. Text can then be appended using the appendText() method.
  43125. */
  43126. TextLayout();
  43127. /** Creates a copy of another layout object. */
  43128. TextLayout (const TextLayout& other);
  43129. /** Creates a text layout from an initial string and font. */
  43130. TextLayout (const String& text, const Font& font);
  43131. /** Destructor. */
  43132. ~TextLayout();
  43133. /** Copies another layout onto this one. */
  43134. TextLayout& operator= (const TextLayout& layoutToCopy);
  43135. /** Clears the layout, removing all its text. */
  43136. void clear();
  43137. /** Adds a string to the end of the arrangement.
  43138. The string will be broken onto new lines wherever it contains
  43139. carriage-returns or linefeeds. After adding it, you can call layout()
  43140. to wrap long lines into a paragraph and justify it.
  43141. */
  43142. void appendText (const String& textToAppend,
  43143. const Font& fontToUse);
  43144. /** Replaces all the text with a new string.
  43145. This is equivalent to calling clear() followed by appendText().
  43146. */
  43147. void setText (const String& newText,
  43148. const Font& fontToUse);
  43149. /** Returns true if the layout has not had any text added yet. */
  43150. bool isEmpty() const;
  43151. /** Breaks the text up to form a paragraph with the given width.
  43152. @param maximumWidth any text wider than this will be split
  43153. across multiple lines
  43154. @param justification how the lines are to be laid-out horizontally
  43155. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  43156. width that keeps all the lines of text at a
  43157. similar length - this is good when you're displaying
  43158. a short message and don't want it to get split
  43159. onto two lines with only a couple of words on
  43160. the second line, which looks untidy.
  43161. */
  43162. void layout (int maximumWidth,
  43163. const Justification& justification,
  43164. bool attemptToBalanceLineLengths);
  43165. /** Returns the overall width of the entire text layout. */
  43166. int getWidth() const;
  43167. /** Returns the overall height of the entire text layout. */
  43168. int getHeight() const;
  43169. /** Returns the total number of lines of text. */
  43170. int getNumLines() const { return totalLines; }
  43171. /** Returns the width of a particular line of text.
  43172. @param lineNumber the line, from 0 to (getNumLines() - 1)
  43173. */
  43174. int getLineWidth (int lineNumber) const;
  43175. /** Renders the text at a specified position using a graphics context.
  43176. */
  43177. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  43178. /** Renders the text within a specified rectangle using a graphics context.
  43179. The justification flags dictate how the block of text should be positioned
  43180. within the rectangle.
  43181. */
  43182. void drawWithin (Graphics& g,
  43183. int x, int y, int w, int h,
  43184. const Justification& layoutFlags) const;
  43185. private:
  43186. class Token;
  43187. friend class OwnedArray <Token>;
  43188. OwnedArray <Token> tokens;
  43189. int totalLines;
  43190. JUCE_LEAK_DETECTOR (TextLayout);
  43191. };
  43192. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  43193. /*** End of inlined file: juce_TextLayout.h ***/
  43194. /** A window that displays a message and has buttons for the user to react to it.
  43195. For simple dialog boxes with just a couple of buttons on them, there are
  43196. some static methods for running these.
  43197. For more complex dialogs, an AlertWindow can be created, then it can have some
  43198. buttons and components added to it, and its runModalLoop() method is then used to
  43199. show it. The value returned by runModalLoop() shows which button the
  43200. user pressed to dismiss the box.
  43201. @see ThreadWithProgressWindow
  43202. */
  43203. class JUCE_API AlertWindow : public TopLevelWindow,
  43204. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  43205. {
  43206. public:
  43207. /** The type of icon to show in the dialog box. */
  43208. enum AlertIconType
  43209. {
  43210. NoIcon, /**< No icon will be shown on the dialog box. */
  43211. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  43212. user to answer a question. */
  43213. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  43214. warning about something and shouldn't be ignored. */
  43215. InfoIcon /**< An icon that indicates that the dialog box is just
  43216. giving the user some information, which doesn't require
  43217. a response from them. */
  43218. };
  43219. /** Creates an AlertWindow.
  43220. @param title the headline to show at the top of the dialog box
  43221. @param message a longer, more descriptive message to show underneath the
  43222. headline
  43223. @param iconType the type of icon to display
  43224. @param associatedComponent if this is non-null, it specifies the component that the
  43225. alert window should be associated with. Depending on the look
  43226. and feel, this might be used for positioning of the alert window.
  43227. */
  43228. AlertWindow (const String& title,
  43229. const String& message,
  43230. AlertIconType iconType,
  43231. Component* associatedComponent = 0);
  43232. /** Destroys the AlertWindow */
  43233. ~AlertWindow();
  43234. /** Returns the type of alert icon that was specified when the window
  43235. was created. */
  43236. AlertIconType getAlertType() const throw() { return alertIconType; }
  43237. /** Changes the dialog box's message.
  43238. This will also resize the window to fit the new message if required.
  43239. */
  43240. void setMessage (const String& message);
  43241. /** Adds a button to the window.
  43242. @param name the text to show on the button
  43243. @param returnValue the value that should be returned from runModalLoop()
  43244. if this is the button that the user presses.
  43245. @param shortcutKey1 an optional key that can be pressed to trigger this button
  43246. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  43247. */
  43248. void addButton (const String& name,
  43249. int returnValue,
  43250. const KeyPress& shortcutKey1 = KeyPress(),
  43251. const KeyPress& shortcutKey2 = KeyPress());
  43252. /** Returns the number of buttons that the window currently has. */
  43253. int getNumButtons() const;
  43254. /** Invokes a click of one of the buttons. */
  43255. void triggerButtonClick (const String& buttonName);
  43256. /** Adds a textbox to the window for entering strings.
  43257. @param name an internal name for the text-box. This is the name to pass to
  43258. the getTextEditorContents() method to find out what the
  43259. user typed-in.
  43260. @param initialContents a string to show in the text box when it's first shown
  43261. @param onScreenLabel if this is non-empty, it will be displayed next to the
  43262. text-box to label it.
  43263. @param isPasswordBox if true, the text editor will display asterisks instead of
  43264. the actual text
  43265. @see getTextEditorContents
  43266. */
  43267. void addTextEditor (const String& name,
  43268. const String& initialContents,
  43269. const String& onScreenLabel = String::empty,
  43270. bool isPasswordBox = false);
  43271. /** Returns the contents of a named textbox.
  43272. After showing an AlertWindow that contains a text editor, this can be
  43273. used to find out what the user has typed into it.
  43274. @param nameOfTextEditor the name of the text box that you're interested in
  43275. @see addTextEditor
  43276. */
  43277. const String getTextEditorContents (const String& nameOfTextEditor) const;
  43278. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  43279. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  43280. /** Adds a drop-down list of choices to the box.
  43281. After the box has been shown, the getComboBoxComponent() method can
  43282. be used to find out which item the user picked.
  43283. @param name the label to use for the drop-down list
  43284. @param items the list of items to show in it
  43285. @param onScreenLabel if this is non-empty, it will be displayed next to the
  43286. combo-box to label it.
  43287. @see getComboBoxComponent
  43288. */
  43289. void addComboBox (const String& name,
  43290. const StringArray& items,
  43291. const String& onScreenLabel = String::empty);
  43292. /** Returns a drop-down list that was added to the AlertWindow.
  43293. @param nameOfList the name that was passed into the addComboBox() method
  43294. when creating the drop-down
  43295. @returns the ComboBox component, or 0 if none was found for the given name.
  43296. */
  43297. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  43298. /** Adds a block of text.
  43299. This is handy for adding a multi-line note next to a textbox or combo-box,
  43300. to provide more details about what's going on.
  43301. */
  43302. void addTextBlock (const String& text);
  43303. /** Adds a progress-bar to the window.
  43304. @param progressValue a variable that will be repeatedly checked while the
  43305. dialog box is visible, to see how far the process has
  43306. got. The value should be in the range 0 to 1.0
  43307. */
  43308. void addProgressBarComponent (double& progressValue);
  43309. /** Adds a user-defined component to the dialog box.
  43310. @param component the component to add - its size should be set up correctly
  43311. before it is passed in. The caller is responsible for deleting
  43312. the component later on - the AlertWindow won't delete it.
  43313. */
  43314. void addCustomComponent (Component* component);
  43315. /** Returns the number of custom components in the dialog box.
  43316. @see getCustomComponent, addCustomComponent
  43317. */
  43318. int getNumCustomComponents() const;
  43319. /** Returns one of the custom components in the dialog box.
  43320. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  43321. will return 0
  43322. @see getNumCustomComponents, addCustomComponent
  43323. */
  43324. Component* getCustomComponent (int index) const;
  43325. /** Removes one of the custom components in the dialog box.
  43326. Note that this won't delete it, it just removes the component from the window
  43327. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  43328. will return 0
  43329. @returns the component that was removed (or null)
  43330. @see getNumCustomComponents, addCustomComponent
  43331. */
  43332. Component* removeCustomComponent (int index);
  43333. /** Returns true if the window contains any components other than just buttons.*/
  43334. bool containsAnyExtraComponents() const;
  43335. // easy-to-use message box functions:
  43336. /** Shows a dialog box that just has a message and a single button to get rid of it.
  43337. If the callback parameter is null, the box is shown modally, and the method will
  43338. block until the user has clicked the button (or pressed the escape or return keys).
  43339. If the callback parameter is non-null, the box will be displayed and placed into a
  43340. modal state, but this method will return immediately, and the callback will be invoked
  43341. later when the user dismisses the box.
  43342. @param iconType the type of icon to show
  43343. @param title the headline to show at the top of the box
  43344. @param message a longer, more descriptive message to show underneath the
  43345. headline
  43346. @param buttonText the text to show in the button - if this string is empty, the
  43347. default string "ok" (or a localised version) will be used.
  43348. @param associatedComponent if this is non-null, it specifies the component that the
  43349. alert window should be associated with. Depending on the look
  43350. and feel, this might be used for positioning of the alert window.
  43351. */
  43352. #if JUCE_MODAL_LOOPS_PERMITTED
  43353. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  43354. const String& title,
  43355. const String& message,
  43356. const String& buttonText = String::empty,
  43357. Component* associatedComponent = 0);
  43358. #endif
  43359. /** Shows a dialog box that just has a message and a single button to get rid of it.
  43360. If the callback parameter is null, the box is shown modally, and the method will
  43361. block until the user has clicked the button (or pressed the escape or return keys).
  43362. If the callback parameter is non-null, the box will be displayed and placed into a
  43363. modal state, but this method will return immediately, and the callback will be invoked
  43364. later when the user dismisses the box.
  43365. @param iconType the type of icon to show
  43366. @param title the headline to show at the top of the box
  43367. @param message a longer, more descriptive message to show underneath the
  43368. headline
  43369. @param buttonText the text to show in the button - if this string is empty, the
  43370. default string "ok" (or a localised version) will be used.
  43371. @param associatedComponent if this is non-null, it specifies the component that the
  43372. alert window should be associated with. Depending on the look
  43373. and feel, this might be used for positioning of the alert window.
  43374. */
  43375. static void JUCE_CALLTYPE showMessageBoxAsync (AlertIconType iconType,
  43376. const String& title,
  43377. const String& message,
  43378. const String& buttonText = String::empty,
  43379. Component* associatedComponent = 0);
  43380. /** Shows a dialog box with two buttons.
  43381. Ideal for ok/cancel or yes/no choices. The return key can also be used
  43382. to trigger the first button, and the escape key for the second button.
  43383. If the callback parameter is null, the box is shown modally, and the method will
  43384. block until the user has clicked the button (or pressed the escape or return keys).
  43385. If the callback parameter is non-null, the box will be displayed and placed into a
  43386. modal state, but this method will return immediately, and the callback will be invoked
  43387. later when the user dismisses the box.
  43388. @param iconType the type of icon to show
  43389. @param title the headline to show at the top of the box
  43390. @param message a longer, more descriptive message to show underneath the
  43391. headline
  43392. @param button1Text the text to show in the first button - if this string is
  43393. empty, the default string "ok" (or a localised version of it)
  43394. will be used.
  43395. @param button2Text the text to show in the second button - if this string is
  43396. empty, the default string "cancel" (or a localised version of it)
  43397. will be used.
  43398. @param associatedComponent if this is non-null, it specifies the component that the
  43399. alert window should be associated with. Depending on the look
  43400. and feel, this might be used for positioning of the alert window.
  43401. @param callback if this is non-null, the menu will be launched asynchronously,
  43402. returning immediately, and the callback will receive a call to its
  43403. modalStateFinished() when the box is dismissed, with its parameter
  43404. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  43405. will be owned and deleted by the system, so make sure that it works
  43406. safely and doesn't keep any references to objects that might be deleted
  43407. before it gets called.
  43408. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  43409. is not null, the method always returns false, and the user's choice is delivered
  43410. later by the callback.
  43411. */
  43412. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  43413. const String& title,
  43414. const String& message,
  43415. #if JUCE_MODAL_LOOPS_PERMITTED
  43416. const String& button1Text = String::empty,
  43417. const String& button2Text = String::empty,
  43418. Component* associatedComponent = 0,
  43419. ModalComponentManager::Callback* callback = 0);
  43420. #else
  43421. const String& button1Text,
  43422. const String& button2Text,
  43423. Component* associatedComponent,
  43424. ModalComponentManager::Callback* callback);
  43425. #endif
  43426. /** Shows a dialog box with three buttons.
  43427. Ideal for yes/no/cancel boxes.
  43428. The escape key can be used to trigger the third button.
  43429. If the callback parameter is null, the box is shown modally, and the method will
  43430. block until the user has clicked the button (or pressed the escape or return keys).
  43431. If the callback parameter is non-null, the box will be displayed and placed into a
  43432. modal state, but this method will return immediately, and the callback will be invoked
  43433. later when the user dismisses the box.
  43434. @param iconType the type of icon to show
  43435. @param title the headline to show at the top of the box
  43436. @param message a longer, more descriptive message to show underneath the
  43437. headline
  43438. @param button1Text the text to show in the first button - if an empty string, then
  43439. "yes" will be used (or a localised version of it)
  43440. @param button2Text the text to show in the first button - if an empty string, then
  43441. "no" will be used (or a localised version of it)
  43442. @param button3Text the text to show in the first button - if an empty string, then
  43443. "cancel" will be used (or a localised version of it)
  43444. @param associatedComponent if this is non-null, it specifies the component that the
  43445. alert window should be associated with. Depending on the look
  43446. and feel, this might be used for positioning of the alert window.
  43447. @param callback if this is non-null, the menu will be launched asynchronously,
  43448. returning immediately, and the callback will receive a call to its
  43449. modalStateFinished() when the box is dismissed, with its parameter
  43450. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  43451. if it was cancelled, The callback object will be owned and deleted by the
  43452. system, so make sure that it works safely and doesn't keep any references
  43453. to objects that might be deleted before it gets called.
  43454. @returns If the callback parameter has been set, this returns 0. Otherwise, it
  43455. returns one of the following values:
  43456. - 0 if the third button was pressed (normally used for 'cancel')
  43457. - 1 if the first button was pressed (normally used for 'yes')
  43458. - 2 if the middle button was pressed (normally used for 'no')
  43459. */
  43460. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  43461. const String& title,
  43462. const String& message,
  43463. #if JUCE_MODAL_LOOPS_PERMITTED
  43464. const String& button1Text = String::empty,
  43465. const String& button2Text = String::empty,
  43466. const String& button3Text = String::empty,
  43467. Component* associatedComponent = 0,
  43468. ModalComponentManager::Callback* callback = 0);
  43469. #else
  43470. const String& button1Text,
  43471. const String& button2Text,
  43472. const String& button3Text,
  43473. Component* associatedComponent,
  43474. ModalComponentManager::Callback* callback);
  43475. #endif
  43476. /** Shows an operating-system native dialog box.
  43477. @param title the title to use at the top
  43478. @param bodyText the longer message to show
  43479. @param isOkCancel if true, this will show an ok/cancel box, if false,
  43480. it'll show a box with just an ok button
  43481. @returns true if the ok button was pressed, false if they pressed cancel.
  43482. */
  43483. #if JUCE_MODAL_LOOPS_PERMITTED
  43484. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  43485. const String& bodyText,
  43486. bool isOkCancel);
  43487. #endif
  43488. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  43489. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43490. methods.
  43491. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43492. */
  43493. enum ColourIds
  43494. {
  43495. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  43496. textColourId = 0x1001810, /**< The colour for the text. */
  43497. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  43498. };
  43499. protected:
  43500. /** @internal */
  43501. void paint (Graphics& g);
  43502. /** @internal */
  43503. void mouseDown (const MouseEvent& e);
  43504. /** @internal */
  43505. void mouseDrag (const MouseEvent& e);
  43506. /** @internal */
  43507. bool keyPressed (const KeyPress& key);
  43508. /** @internal */
  43509. void buttonClicked (Button* button);
  43510. /** @internal */
  43511. void lookAndFeelChanged();
  43512. /** @internal */
  43513. void userTriedToCloseWindow();
  43514. /** @internal */
  43515. int getDesktopWindowStyleFlags() const;
  43516. private:
  43517. String text;
  43518. TextLayout textLayout;
  43519. AlertIconType alertIconType;
  43520. ComponentBoundsConstrainer constrainer;
  43521. ComponentDragger dragger;
  43522. Rectangle<int> textArea;
  43523. OwnedArray<TextButton> buttons;
  43524. OwnedArray<TextEditor> textBoxes;
  43525. OwnedArray<ComboBox> comboBoxes;
  43526. OwnedArray<ProgressBar> progressBars;
  43527. Array<Component*> customComps;
  43528. OwnedArray<Component> textBlocks;
  43529. Array<Component*> allComps;
  43530. StringArray textboxNames, comboBoxNames;
  43531. Font font;
  43532. Component* associatedComponent;
  43533. void updateLayout (bool onlyIncreaseSize);
  43534. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  43535. };
  43536. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  43537. /*** End of inlined file: juce_AlertWindow.h ***/
  43538. /**
  43539. A file open/save dialog box.
  43540. This is a Juce-based file dialog box; to use a native file chooser, see the
  43541. FileChooser class.
  43542. To use one of these, create it and call its show() method. e.g.
  43543. @code
  43544. {
  43545. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  43546. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  43547. File::nonexistent,
  43548. &wildcardFilter,
  43549. 0);
  43550. FileChooserDialogBox dialogBox ("Open some kind of file",
  43551. "Please choose some kind of file that you want to open...",
  43552. browser,
  43553. getLookAndFeel().alertWindowBackground);
  43554. if (dialogBox.show())
  43555. {
  43556. File selectedFile = browser.getCurrentFile();
  43557. ...
  43558. }
  43559. }
  43560. @endcode
  43561. @see FileChooser
  43562. */
  43563. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  43564. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43565. public FileBrowserListener
  43566. {
  43567. public:
  43568. /** Creates a file chooser box.
  43569. @param title the main title to show at the top of the box
  43570. @param instructions an optional longer piece of text to show below the title in
  43571. a smaller font, describing in more detail what's required.
  43572. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  43573. box. Make sure you delete this after (but not before!) the
  43574. dialog box has been deleted.
  43575. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  43576. if they try to select a file that already exists. (This
  43577. flag is only used when saving files)
  43578. @param backgroundColour the background colour for the top level window
  43579. @see FileBrowserComponent, FilePreviewComponent
  43580. */
  43581. FileChooserDialogBox (const String& title,
  43582. const String& instructions,
  43583. FileBrowserComponent& browserComponent,
  43584. bool warnAboutOverwritingExistingFiles,
  43585. const Colour& backgroundColour);
  43586. /** Destructor. */
  43587. ~FileChooserDialogBox();
  43588. #if JUCE_MODAL_LOOPS_PERMITTED
  43589. /** Displays and runs the dialog box modally.
  43590. This will show the box with the specified size, returning true if the user
  43591. pressed 'ok', or false if they cancelled.
  43592. Leave the width or height as 0 to use the default size
  43593. */
  43594. bool show (int width = 0, int height = 0);
  43595. /** Displays and runs the dialog box modally.
  43596. This will show the box with the specified size at the specified location,
  43597. returning true if the user pressed 'ok', or false if they cancelled.
  43598. Leave the width or height as 0 to use the default size.
  43599. */
  43600. bool showAt (int x, int y, int width, int height);
  43601. #endif
  43602. /** Sets the size of this dialog box to its default and positions it either in the
  43603. centre of the screen, or centred around a component that is provided.
  43604. */
  43605. void centreWithDefaultSize (Component* componentToCentreAround = 0);
  43606. /** A set of colour IDs to use to change the colour of various aspects of the box.
  43607. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43608. methods.
  43609. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43610. */
  43611. enum ColourIds
  43612. {
  43613. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  43614. };
  43615. /** @internal */
  43616. void buttonClicked (Button* button);
  43617. /** @internal */
  43618. void closeButtonPressed();
  43619. /** @internal */
  43620. void selectionChanged();
  43621. /** @internal */
  43622. void fileClicked (const File& file, const MouseEvent& e);
  43623. /** @internal */
  43624. void fileDoubleClicked (const File& file);
  43625. private:
  43626. class ContentComponent;
  43627. ContentComponent* content;
  43628. const bool warnAboutOverwritingExistingFiles;
  43629. void okButtonPressed();
  43630. void createNewFolder();
  43631. void createNewFolderConfirmed (const String& name);
  43632. static void okToOverwriteFileCallback (int result, FileChooserDialogBox*);
  43633. static void createNewFolderCallback (int result, FileChooserDialogBox*, Component::SafePointer<AlertWindow>);
  43634. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  43635. };
  43636. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  43637. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  43638. #endif
  43639. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  43640. #endif
  43641. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43642. /*** Start of inlined file: juce_FileListComponent.h ***/
  43643. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43644. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43645. /**
  43646. A component that displays the files in a directory as a listbox.
  43647. This implements the DirectoryContentsDisplayComponent base class so that
  43648. it can be used in a FileBrowserComponent.
  43649. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  43650. class and the FileBrowserListener class.
  43651. @see DirectoryContentsList, FileTreeComponent
  43652. */
  43653. class JUCE_API FileListComponent : public ListBox,
  43654. public DirectoryContentsDisplayComponent,
  43655. private ListBoxModel,
  43656. private ChangeListener
  43657. {
  43658. public:
  43659. /** Creates a listbox to show the contents of a specified directory.
  43660. */
  43661. FileListComponent (DirectoryContentsList& listToShow);
  43662. /** Destructor. */
  43663. ~FileListComponent();
  43664. /** Returns the number of files the user has got selected.
  43665. @see getSelectedFile
  43666. */
  43667. int getNumSelectedFiles() const;
  43668. /** Returns one of the files that the user has currently selected.
  43669. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  43670. @see getNumSelectedFiles
  43671. */
  43672. const File getSelectedFile (int index = 0) const;
  43673. /** Deselects any files that are currently selected. */
  43674. void deselectAllFiles();
  43675. /** Scrolls to the top of the list. */
  43676. void scrollToTop();
  43677. /** @internal */
  43678. void changeListenerCallback (ChangeBroadcaster*);
  43679. /** @internal */
  43680. int getNumRows();
  43681. /** @internal */
  43682. void paintListBoxItem (int, Graphics&, int, int, bool);
  43683. /** @internal */
  43684. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  43685. /** @internal */
  43686. void selectedRowsChanged (int lastRowSelected);
  43687. /** @internal */
  43688. void deleteKeyPressed (int currentSelectedRow);
  43689. /** @internal */
  43690. void returnKeyPressed (int currentSelectedRow);
  43691. private:
  43692. File lastDirectory;
  43693. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  43694. };
  43695. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43696. /*** End of inlined file: juce_FileListComponent.h ***/
  43697. #endif
  43698. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43699. /*** Start of inlined file: juce_FilenameComponent.h ***/
  43700. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43701. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43702. class FilenameComponent;
  43703. /**
  43704. Listens for events happening to a FilenameComponent.
  43705. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  43706. register one of these objects for event callbacks when the filename is changed.
  43707. @see FilenameComponent
  43708. */
  43709. class JUCE_API FilenameComponentListener
  43710. {
  43711. public:
  43712. /** Destructor. */
  43713. virtual ~FilenameComponentListener() {}
  43714. /** This method is called after the FilenameComponent's file has been changed. */
  43715. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  43716. };
  43717. /**
  43718. Shows a filename as an editable text box, with a 'browse' button and a
  43719. drop-down list for recently selected files.
  43720. A handy component for dialogue boxes where you want the user to be able to
  43721. select a file or directory.
  43722. Attach an FilenameComponentListener using the addListener() method, and it will
  43723. get called each time the user changes the filename, either by browsing for a file
  43724. and clicking 'ok', or by typing a new filename into the box and pressing return.
  43725. @see FileChooser, ComboBox
  43726. */
  43727. class JUCE_API FilenameComponent : public Component,
  43728. public SettableTooltipClient,
  43729. public FileDragAndDropTarget,
  43730. private AsyncUpdater,
  43731. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43732. private ComboBoxListener
  43733. {
  43734. public:
  43735. /** Creates a FilenameComponent.
  43736. @param name the name for this component.
  43737. @param currentFile the file to initially show in the box
  43738. @param canEditFilename if true, the user can manually edit the filename; if false,
  43739. they can only change it by browsing for a new file
  43740. @param isDirectory if true, the file will be treated as a directory, and
  43741. an appropriate directory browser used
  43742. @param isForSaving if true, the file browser will allow non-existent files to
  43743. be picked, as the file is assumed to be used for saving rather
  43744. than loading
  43745. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  43746. If an empty string is passed in, then the pattern is assumed to be "*"
  43747. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  43748. to any filenames that are entered or chosen
  43749. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  43750. will only appear if the initial file isn't valid)
  43751. */
  43752. FilenameComponent (const String& name,
  43753. const File& currentFile,
  43754. bool canEditFilename,
  43755. bool isDirectory,
  43756. bool isForSaving,
  43757. const String& fileBrowserWildcard,
  43758. const String& enforcedSuffix,
  43759. const String& textWhenNothingSelected);
  43760. /** Destructor. */
  43761. ~FilenameComponent();
  43762. /** Returns the currently displayed filename. */
  43763. const File getCurrentFile() const;
  43764. /** Changes the current filename.
  43765. If addToRecentlyUsedList is true, the filename will also be added to the
  43766. drop-down list of recent files.
  43767. If sendChangeNotification is false, then the listeners won't be told of the
  43768. change.
  43769. */
  43770. void setCurrentFile (File newFile,
  43771. bool addToRecentlyUsedList,
  43772. bool sendChangeNotification = true);
  43773. /** Changes whether the use can type into the filename box.
  43774. */
  43775. void setFilenameIsEditable (bool shouldBeEditable);
  43776. /** Sets a file or directory to be the default starting point for the browser to show.
  43777. This is only used if the current file hasn't been set.
  43778. */
  43779. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  43780. /** Returns all the entries on the recent files list.
  43781. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  43782. state of this list.
  43783. @see setRecentlyUsedFilenames
  43784. */
  43785. const StringArray getRecentlyUsedFilenames() const;
  43786. /** Sets all the entries on the recent files list.
  43787. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  43788. state of this list.
  43789. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  43790. */
  43791. void setRecentlyUsedFilenames (const StringArray& filenames);
  43792. /** Adds an entry to the recently-used files dropdown list.
  43793. If the file is already in the list, it will be moved to the top. A limit
  43794. is also placed on the number of items that are kept in the list.
  43795. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  43796. */
  43797. void addRecentlyUsedFile (const File& file);
  43798. /** Changes the limit for the number of files that will be stored in the recent-file list.
  43799. */
  43800. void setMaxNumberOfRecentFiles (int newMaximum);
  43801. /** Changes the text shown on the 'browse' button.
  43802. By default this button just says "..." but you can change it. The button itself
  43803. can be changed using the look-and-feel classes, so it might not actually have any
  43804. text on it.
  43805. */
  43806. void setBrowseButtonText (const String& browseButtonText);
  43807. /** Adds a listener that will be called when the selected file is changed. */
  43808. void addListener (FilenameComponentListener* listener);
  43809. /** Removes a previously-registered listener. */
  43810. void removeListener (FilenameComponentListener* listener);
  43811. /** Gives the component a tooltip. */
  43812. void setTooltip (const String& newTooltip);
  43813. /** @internal */
  43814. void paintOverChildren (Graphics& g);
  43815. /** @internal */
  43816. void resized();
  43817. /** @internal */
  43818. void lookAndFeelChanged();
  43819. /** @internal */
  43820. bool isInterestedInFileDrag (const StringArray& files);
  43821. /** @internal */
  43822. void filesDropped (const StringArray& files, int, int);
  43823. /** @internal */
  43824. void fileDragEnter (const StringArray& files, int, int);
  43825. /** @internal */
  43826. void fileDragExit (const StringArray& files);
  43827. private:
  43828. ComboBox filenameBox;
  43829. String lastFilename;
  43830. ScopedPointer<Button> browseButton;
  43831. int maxRecentFiles;
  43832. bool isDir, isSaving, isFileDragOver;
  43833. String wildcard, enforcedSuffix, browseButtonText;
  43834. ListenerList <FilenameComponentListener> listeners;
  43835. File defaultBrowseFile;
  43836. void comboBoxChanged (ComboBox*);
  43837. void buttonClicked (Button* button);
  43838. void handleAsyncUpdate();
  43839. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  43840. };
  43841. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43842. /*** End of inlined file: juce_FilenameComponent.h ***/
  43843. #endif
  43844. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  43845. #endif
  43846. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43847. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  43848. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43849. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43850. /**
  43851. Shows a set of file paths in a list, allowing them to be added, removed or
  43852. re-ordered.
  43853. @see FileSearchPath
  43854. */
  43855. class JUCE_API FileSearchPathListComponent : public Component,
  43856. public SettableTooltipClient,
  43857. public FileDragAndDropTarget,
  43858. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43859. private ListBoxModel
  43860. {
  43861. public:
  43862. /** Creates an empty FileSearchPathListComponent. */
  43863. FileSearchPathListComponent();
  43864. /** Destructor. */
  43865. ~FileSearchPathListComponent();
  43866. /** Returns the path as it is currently shown. */
  43867. const FileSearchPath& getPath() const throw() { return path; }
  43868. /** Changes the current path. */
  43869. void setPath (const FileSearchPath& newPath);
  43870. /** Sets a file or directory to be the default starting point for the browser to show.
  43871. This is only used if the current file hasn't been set.
  43872. */
  43873. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  43874. /** A set of colour IDs to use to change the colour of various aspects of the label.
  43875. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43876. methods.
  43877. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43878. */
  43879. enum ColourIds
  43880. {
  43881. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  43882. Make this transparent if you don't want the background to be filled. */
  43883. };
  43884. /** @internal */
  43885. int getNumRows();
  43886. /** @internal */
  43887. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  43888. /** @internal */
  43889. void deleteKeyPressed (int lastRowSelected);
  43890. /** @internal */
  43891. void returnKeyPressed (int lastRowSelected);
  43892. /** @internal */
  43893. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  43894. /** @internal */
  43895. void selectedRowsChanged (int lastRowSelected);
  43896. /** @internal */
  43897. void resized();
  43898. /** @internal */
  43899. void paint (Graphics& g);
  43900. /** @internal */
  43901. bool isInterestedInFileDrag (const StringArray& files);
  43902. /** @internal */
  43903. void filesDropped (const StringArray& files, int, int);
  43904. /** @internal */
  43905. void buttonClicked (Button* button);
  43906. private:
  43907. FileSearchPath path;
  43908. File defaultBrowseTarget;
  43909. ListBox listBox;
  43910. TextButton addButton, removeButton, changeButton;
  43911. DrawableButton upButton, downButton;
  43912. void changed();
  43913. void updateButtons();
  43914. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  43915. };
  43916. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43917. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  43918. #endif
  43919. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43920. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  43921. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43922. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43923. /**
  43924. A component that displays the files in a directory as a treeview.
  43925. This implements the DirectoryContentsDisplayComponent base class so that
  43926. it can be used in a FileBrowserComponent.
  43927. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  43928. class and the FileBrowserListener class.
  43929. @see DirectoryContentsList, FileListComponent
  43930. */
  43931. class JUCE_API FileTreeComponent : public TreeView,
  43932. public DirectoryContentsDisplayComponent
  43933. {
  43934. public:
  43935. /** Creates a listbox to show the contents of a specified directory.
  43936. */
  43937. FileTreeComponent (DirectoryContentsList& listToShow);
  43938. /** Destructor. */
  43939. ~FileTreeComponent();
  43940. /** Returns the number of files the user has got selected.
  43941. @see getSelectedFile
  43942. */
  43943. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  43944. /** Returns one of the files that the user has currently selected.
  43945. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  43946. @see getNumSelectedFiles
  43947. */
  43948. const File getSelectedFile (int index = 0) const;
  43949. /** Deselects any files that are currently selected. */
  43950. void deselectAllFiles();
  43951. /** Scrolls the list to the top. */
  43952. void scrollToTop();
  43953. /** Setting a name for this allows tree items to be dragged.
  43954. The string that you pass in here will be returned by the getDragSourceDescription()
  43955. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  43956. */
  43957. void setDragAndDropDescription (const String& description);
  43958. /** Returns the last value that was set by setDragAndDropDescription().
  43959. */
  43960. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  43961. private:
  43962. String dragAndDropDescription;
  43963. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  43964. };
  43965. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43966. /*** End of inlined file: juce_FileTreeComponent.h ***/
  43967. #endif
  43968. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43969. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  43970. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43971. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43972. /**
  43973. A simple preview component that shows thumbnails of image files.
  43974. @see FileChooserDialogBox, FilePreviewComponent
  43975. */
  43976. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  43977. private Timer
  43978. {
  43979. public:
  43980. /** Creates an ImagePreviewComponent. */
  43981. ImagePreviewComponent();
  43982. /** Destructor. */
  43983. ~ImagePreviewComponent();
  43984. /** @internal */
  43985. void selectedFileChanged (const File& newSelectedFile);
  43986. /** @internal */
  43987. void paint (Graphics& g);
  43988. /** @internal */
  43989. void timerCallback();
  43990. private:
  43991. File fileToLoad;
  43992. Image currentThumbnail;
  43993. String currentDetails;
  43994. void getThumbSize (int& w, int& h) const;
  43995. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  43996. };
  43997. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43998. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  43999. #endif
  44000. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44001. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  44002. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44003. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44004. /**
  44005. A type of FileFilter that works by wildcard pattern matching.
  44006. This filter only allows files that match one of the specified patterns, but
  44007. allows all directories through.
  44008. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  44009. */
  44010. class JUCE_API WildcardFileFilter : public FileFilter
  44011. {
  44012. public:
  44013. /**
  44014. Creates a wildcard filter for one or more patterns.
  44015. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  44016. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  44017. or .aiff.
  44018. The description is a name to show the user in a list of possible patterns, so
  44019. for the wav/aiff example, your description might be "audio files".
  44020. */
  44021. WildcardFileFilter (const String& fileWildcardPatterns,
  44022. const String& directoryWildcardPatterns,
  44023. const String& description);
  44024. /** Destructor. */
  44025. ~WildcardFileFilter();
  44026. /** Returns true if the filename matches one of the patterns specified. */
  44027. bool isFileSuitable (const File& file) const;
  44028. /** This always returns true. */
  44029. bool isDirectorySuitable (const File& file) const;
  44030. private:
  44031. StringArray fileWildcards, directoryWildcards;
  44032. static void parse (const String& pattern, StringArray& result);
  44033. static bool match (const File& file, const StringArray& wildcards);
  44034. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  44035. };
  44036. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  44037. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  44038. #endif
  44039. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  44040. #endif
  44041. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  44042. #endif
  44043. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  44044. #endif
  44045. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  44046. #endif
  44047. #ifndef __JUCE_CARETCOMPONENT_JUCEHEADER__
  44048. #endif
  44049. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  44050. #endif
  44051. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  44052. #endif
  44053. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44054. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  44055. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44056. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44057. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  44058. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44059. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44060. /**
  44061. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  44062. command in a ApplicationCommandManager.
  44063. Normally, you won't actually create a KeyPressMappingSet directly, because
  44064. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  44065. you'd create yourself an ApplicationCommandManager, and call its
  44066. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  44067. KeyPressMappingSet.
  44068. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  44069. to the top-level component for which you want to handle keystrokes. So for example:
  44070. @code
  44071. class MyMainWindow : public Component
  44072. {
  44073. ApplicationCommandManager* myCommandManager;
  44074. public:
  44075. MyMainWindow()
  44076. {
  44077. myCommandManager = new ApplicationCommandManager();
  44078. // first, make sure the command manager has registered all the commands that its
  44079. // targets can perform..
  44080. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  44081. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  44082. // this will use the command manager to initialise the KeyPressMappingSet with
  44083. // the default keypresses that were specified when the targets added their commands
  44084. // to the manager.
  44085. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  44086. // having set up the default key-mappings, you might now want to load the last set
  44087. // of mappings that the user configured.
  44088. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  44089. // Now tell our top-level window to send any keypresses that arrive to the
  44090. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  44091. addKeyListener (myCommandManager->getKeyMappings());
  44092. }
  44093. ...
  44094. }
  44095. @endcode
  44096. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  44097. register to be told when a command or mapping is added, removed, etc.
  44098. There's also a UI component called KeyMappingEditorComponent that can be used
  44099. to easily edit the key mappings.
  44100. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  44101. */
  44102. class JUCE_API KeyPressMappingSet : public KeyListener,
  44103. public ChangeBroadcaster,
  44104. public FocusChangeListener
  44105. {
  44106. public:
  44107. /** Creates a KeyPressMappingSet for a given command manager.
  44108. Normally, you won't actually create a KeyPressMappingSet directly, because
  44109. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  44110. best thing to do is to create your ApplicationCommandManager, and use the
  44111. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  44112. When a suitable keypress happens, the manager's invoke() method will be
  44113. used to invoke the appropriate command.
  44114. @see ApplicationCommandManager
  44115. */
  44116. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  44117. /** Creates an copy of a KeyPressMappingSet. */
  44118. KeyPressMappingSet (const KeyPressMappingSet& other);
  44119. /** Destructor. */
  44120. ~KeyPressMappingSet();
  44121. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  44122. /** Returns a list of keypresses that are assigned to a particular command.
  44123. @param commandID the command's ID
  44124. */
  44125. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  44126. /** Assigns a keypress to a command.
  44127. If the keypress is already assigned to a different command, it will first be
  44128. removed from that command, to avoid it triggering multiple functions.
  44129. @param commandID the ID of the command that you want to add a keypress to. If
  44130. this is 0, the keypress will be removed from anything that it
  44131. was previously assigned to, but not re-assigned
  44132. @param newKeyPress the new key-press
  44133. @param insertIndex if this is less than zero, the key will be appended to the
  44134. end of the list of keypresses; otherwise the new keypress will
  44135. be inserted into the existing list at this index
  44136. */
  44137. void addKeyPress (CommandID commandID,
  44138. const KeyPress& newKeyPress,
  44139. int insertIndex = -1);
  44140. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  44141. @see resetToDefaultMapping
  44142. */
  44143. void resetToDefaultMappings();
  44144. /** Resets all key-mappings to the defaults for a particular command.
  44145. @see resetToDefaultMappings
  44146. */
  44147. void resetToDefaultMapping (CommandID commandID);
  44148. /** Removes all keypresses that are assigned to any commands. */
  44149. void clearAllKeyPresses();
  44150. /** Removes all keypresses that are assigned to a particular command. */
  44151. void clearAllKeyPresses (CommandID commandID);
  44152. /** Removes one of the keypresses that are assigned to a command.
  44153. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  44154. which the keyPressIndex refers.
  44155. */
  44156. void removeKeyPress (CommandID commandID, int keyPressIndex);
  44157. /** Removes a keypress from any command that it may be assigned to.
  44158. */
  44159. void removeKeyPress (const KeyPress& keypress);
  44160. /** Returns true if the given command is linked to this key. */
  44161. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  44162. /** Looks for a command that corresponds to a keypress.
  44163. @returns the UID of the command or 0 if none was found
  44164. */
  44165. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  44166. /** Tries to recreate the mappings from a previously stored state.
  44167. The XML passed in must have been created by the createXml() method.
  44168. If the stored state makes any reference to commands that aren't
  44169. currently available, these will be ignored.
  44170. If the set of mappings being loaded was a set of differences (using createXml (true)),
  44171. then this will call resetToDefaultMappings() and then merge the saved mappings
  44172. on top. If the saved set was created with createXml (false), then this method
  44173. will first clear all existing mappings and load the saved ones as a complete set.
  44174. @returns true if it manages to load the XML correctly
  44175. @see createXml
  44176. */
  44177. bool restoreFromXml (const XmlElement& xmlVersion);
  44178. /** Creates an XML representation of the current mappings.
  44179. This will produce a lump of XML that can be later reloaded using
  44180. restoreFromXml() to recreate the current mapping state.
  44181. The object that is returned must be deleted by the caller.
  44182. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  44183. will be saved into the XML. If it's true, then the XML will
  44184. only store the differences between the current mappings and
  44185. the default mappings you'd get from calling resetToDefaultMappings().
  44186. The advantage of saving a set of differences from the default is that
  44187. if you change the default mappings (in a new version of your app, for
  44188. example), then these will be merged into a user's saved preferences.
  44189. @see restoreFromXml
  44190. */
  44191. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  44192. /** @internal */
  44193. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  44194. /** @internal */
  44195. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  44196. /** @internal */
  44197. void globalFocusChanged (Component* focusedComponent);
  44198. private:
  44199. ApplicationCommandManager* commandManager;
  44200. struct CommandMapping
  44201. {
  44202. CommandID commandID;
  44203. Array <KeyPress> keypresses;
  44204. bool wantsKeyUpDownCallbacks;
  44205. };
  44206. OwnedArray <CommandMapping> mappings;
  44207. struct KeyPressTime
  44208. {
  44209. KeyPress key;
  44210. uint32 timeWhenPressed;
  44211. };
  44212. OwnedArray <KeyPressTime> keysDown;
  44213. void handleMessage (const Message& message);
  44214. void invokeCommand (const CommandID commandID,
  44215. const KeyPress& keyPress,
  44216. const bool isKeyDown,
  44217. const int millisecsSinceKeyPressed,
  44218. Component* const originatingComponent) const;
  44219. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  44220. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  44221. };
  44222. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44223. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  44224. /**
  44225. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  44226. object.
  44227. @see KeyPressMappingSet
  44228. */
  44229. class JUCE_API KeyMappingEditorComponent : public Component
  44230. {
  44231. public:
  44232. /** Creates a KeyMappingEditorComponent.
  44233. @param mappingSet this is the set of mappings to display and edit. Make sure the
  44234. mappings object is not deleted before this component!
  44235. @param showResetToDefaultButton if true, then at the bottom of the list, the
  44236. component will include a 'reset to defaults' button.
  44237. */
  44238. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  44239. bool showResetToDefaultButton);
  44240. /** Destructor. */
  44241. virtual ~KeyMappingEditorComponent();
  44242. /** Sets up the colours to use for parts of the component.
  44243. @param mainBackground colour to use for most of the background
  44244. @param textColour colour to use for the text
  44245. */
  44246. void setColours (const Colour& mainBackground,
  44247. const Colour& textColour);
  44248. /** Returns the KeyPressMappingSet that this component is acting upon. */
  44249. KeyPressMappingSet& getMappings() const throw() { return mappings; }
  44250. /** Can be overridden if some commands need to be excluded from the list.
  44251. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  44252. method to decide what to return, but you can override it to handle special cases.
  44253. */
  44254. virtual bool shouldCommandBeIncluded (CommandID commandID);
  44255. /** Can be overridden to indicate that some commands are shown as read-only.
  44256. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  44257. method to decide what to return, but you can override it to handle special cases.
  44258. */
  44259. virtual bool isCommandReadOnly (CommandID commandID);
  44260. /** This can be overridden to let you change the format of the string used
  44261. to describe a keypress.
  44262. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  44263. keys that are triggered by something else externally. If you override the
  44264. method, be sure to let the base class's method handle keys you're not
  44265. interested in.
  44266. */
  44267. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  44268. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  44269. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44270. methods.
  44271. To change the colours of the menu that pops up
  44272. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44273. */
  44274. enum ColourIds
  44275. {
  44276. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  44277. textColourId = 0x100ad01, /**< The colour for the text. */
  44278. };
  44279. /** @internal */
  44280. void parentHierarchyChanged();
  44281. /** @internal */
  44282. void resized();
  44283. private:
  44284. KeyPressMappingSet& mappings;
  44285. TreeView tree;
  44286. TextButton resetButton;
  44287. class TopLevelItem;
  44288. class ChangeKeyButton;
  44289. class MappingItem;
  44290. class CategoryItem;
  44291. class ItemComponent;
  44292. friend class TopLevelItem;
  44293. friend class OwnedArray <ChangeKeyButton>;
  44294. friend class ScopedPointer<TopLevelItem>;
  44295. ScopedPointer<TopLevelItem> treeItem;
  44296. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  44297. };
  44298. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  44299. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  44300. #endif
  44301. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  44302. #endif
  44303. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  44304. #endif
  44305. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  44306. #endif
  44307. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  44308. #endif
  44309. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  44310. #endif
  44311. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  44312. #endif
  44313. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  44314. #endif
  44315. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44316. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  44317. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44318. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44319. /** An object that watches for any movement of a component or any of its parent components.
  44320. This makes it easy to check when a component is moved relative to its top-level
  44321. peer window. The normal Component::moved() method is only called when a component
  44322. moves relative to its immediate parent, and sometimes you want to know if any of
  44323. components higher up the tree have moved (which of course will affect the overall
  44324. position of all their sub-components).
  44325. It also includes a callback that lets you know when the top-level peer is changed.
  44326. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  44327. because they need to keep their custom windows in the right place and respond to
  44328. changes in the peer.
  44329. */
  44330. class JUCE_API ComponentMovementWatcher : public ComponentListener
  44331. {
  44332. public:
  44333. /** Creates a ComponentMovementWatcher to watch a given target component. */
  44334. ComponentMovementWatcher (Component* component);
  44335. /** Destructor. */
  44336. ~ComponentMovementWatcher();
  44337. /** This callback happens when the component that is being watched is moved
  44338. relative to its top-level peer window, or when it is resized. */
  44339. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  44340. /** This callback happens when the component's top-level peer is changed. */
  44341. virtual void componentPeerChanged() = 0;
  44342. /** This callback happens when the component's visibility state changes, possibly due to
  44343. one of its parents being made visible or invisible.
  44344. */
  44345. virtual void componentVisibilityChanged() = 0;
  44346. /** @internal */
  44347. void componentParentHierarchyChanged (Component& component);
  44348. /** @internal */
  44349. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  44350. /** @internal */
  44351. void componentBeingDeleted (Component& component);
  44352. /** @internal */
  44353. void componentVisibilityChanged (Component& component);
  44354. private:
  44355. WeakReference<Component> component;
  44356. ComponentPeer* lastPeer;
  44357. Array <Component*> registeredParentComps;
  44358. bool reentrant, wasShowing;
  44359. Rectangle<int> lastBounds;
  44360. void unregister();
  44361. void registerWithParentComps();
  44362. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  44363. };
  44364. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  44365. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  44366. #endif
  44367. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44368. /*** Start of inlined file: juce_GroupComponent.h ***/
  44369. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44370. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44371. /**
  44372. A component that draws an outline around itself and has an optional title at
  44373. the top, for drawing an outline around a group of controls.
  44374. */
  44375. class JUCE_API GroupComponent : public Component
  44376. {
  44377. public:
  44378. /** Creates a GroupComponent.
  44379. @param componentName the name to give the component
  44380. @param labelText the text to show at the top of the outline
  44381. */
  44382. GroupComponent (const String& componentName = String::empty,
  44383. const String& labelText = String::empty);
  44384. /** Destructor. */
  44385. ~GroupComponent();
  44386. /** Changes the text that's shown at the top of the component. */
  44387. void setText (const String& newText);
  44388. /** Returns the currently displayed text label. */
  44389. const String getText() const;
  44390. /** Sets the positioning of the text label.
  44391. (The default is Justification::left)
  44392. @see getTextLabelPosition
  44393. */
  44394. void setTextLabelPosition (const Justification& justification);
  44395. /** Returns the current text label position.
  44396. @see setTextLabelPosition
  44397. */
  44398. const Justification getTextLabelPosition() const throw() { return justification; }
  44399. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44400. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44401. methods.
  44402. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44403. */
  44404. enum ColourIds
  44405. {
  44406. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  44407. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  44408. };
  44409. /** @internal */
  44410. void paint (Graphics& g);
  44411. /** @internal */
  44412. void enablementChanged();
  44413. /** @internal */
  44414. void colourChanged();
  44415. private:
  44416. String text;
  44417. Justification justification;
  44418. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  44419. };
  44420. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  44421. /*** End of inlined file: juce_GroupComponent.h ***/
  44422. #endif
  44423. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44424. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  44425. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44426. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44427. /*** Start of inlined file: juce_TabbedComponent.h ***/
  44428. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44429. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44430. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  44431. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44432. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44433. class TabbedButtonBar;
  44434. /** In a TabbedButtonBar, this component is used for each of the buttons.
  44435. If you want to create a TabbedButtonBar with custom tab components, derive
  44436. your component from this class, and override the TabbedButtonBar::createTabButton()
  44437. method to create it instead of the default one.
  44438. @see TabbedButtonBar
  44439. */
  44440. class JUCE_API TabBarButton : public Button
  44441. {
  44442. public:
  44443. /** Creates the tab button. */
  44444. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  44445. /** Destructor. */
  44446. ~TabBarButton();
  44447. /** Chooses the best length for the tab, given the specified depth.
  44448. If the tab is horizontal, this should return its width, and the depth
  44449. specifies its height. If it's vertical, it should return the height, and
  44450. the depth is actually its width.
  44451. */
  44452. virtual int getBestTabLength (int depth);
  44453. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  44454. void clicked (const ModifierKeys& mods);
  44455. bool hitTest (int x, int y);
  44456. protected:
  44457. friend class TabbedButtonBar;
  44458. TabbedButtonBar& owner;
  44459. int overlapPixels;
  44460. DropShadowEffect shadow;
  44461. /** Returns an area of the component that's safe to draw in.
  44462. This deals with the orientation of the tabs, which affects which side is
  44463. touching the tabbed box's content component.
  44464. */
  44465. const Rectangle<int> getActiveArea();
  44466. /** Returns this tab's index in its tab bar. */
  44467. int getIndex() const;
  44468. private:
  44469. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  44470. };
  44471. /**
  44472. A vertical or horizontal bar containing tabs that you can select.
  44473. You can use one of these to generate things like a dialog box that has
  44474. tabbed pages you can flip between. Attach a ChangeListener to the
  44475. button bar to be told when the user changes the page.
  44476. An easier method than doing this is to use a TabbedComponent, which
  44477. contains its own TabbedButtonBar and which takes care of the layout
  44478. and other housekeeping.
  44479. @see TabbedComponent
  44480. */
  44481. class JUCE_API TabbedButtonBar : public Component,
  44482. public ChangeBroadcaster
  44483. {
  44484. public:
  44485. /** The placement of the tab-bar
  44486. @see setOrientation, getOrientation
  44487. */
  44488. enum Orientation
  44489. {
  44490. TabsAtTop,
  44491. TabsAtBottom,
  44492. TabsAtLeft,
  44493. TabsAtRight
  44494. };
  44495. /** Creates a TabbedButtonBar with a given placement.
  44496. You can change the orientation later if you need to.
  44497. */
  44498. TabbedButtonBar (Orientation orientation);
  44499. /** Destructor. */
  44500. ~TabbedButtonBar();
  44501. /** Changes the bar's orientation.
  44502. This won't change the bar's actual size - you'll need to do that yourself,
  44503. but this determines which direction the tabs go in, and which side they're
  44504. stuck to.
  44505. */
  44506. void setOrientation (Orientation orientation);
  44507. /** Returns the current orientation.
  44508. @see setOrientation
  44509. */
  44510. Orientation getOrientation() const throw() { return orientation; }
  44511. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  44512. fit a lot of tabs on-screen.
  44513. */
  44514. void setMinimumTabScaleFactor (double newMinimumScale);
  44515. /** Deletes all the tabs from the bar.
  44516. @see addTab
  44517. */
  44518. void clearTabs();
  44519. /** Adds a tab to the bar.
  44520. Tabs are added in left-to-right reading order.
  44521. If this is the first tab added, it'll also be automatically selected.
  44522. */
  44523. void addTab (const String& tabName,
  44524. const Colour& tabBackgroundColour,
  44525. int insertIndex = -1);
  44526. /** Changes the name of one of the tabs. */
  44527. void setTabName (int tabIndex,
  44528. const String& newName);
  44529. /** Gets rid of one of the tabs. */
  44530. void removeTab (int tabIndex);
  44531. /** Moves a tab to a new index in the list.
  44532. Pass -1 as the index to move it to the end of the list.
  44533. */
  44534. void moveTab (int currentIndex, int newIndex);
  44535. /** Returns the number of tabs in the bar. */
  44536. int getNumTabs() const;
  44537. /** Returns a list of all the tab names in the bar. */
  44538. const StringArray getTabNames() const;
  44539. /** Changes the currently selected tab.
  44540. This will send a change message and cause a synchronous callback to
  44541. the currentTabChanged() method. (But if the given tab is already selected,
  44542. nothing will be done).
  44543. To deselect all the tabs, use an index of -1.
  44544. */
  44545. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44546. /** Returns the name of the currently selected tab.
  44547. This could be an empty string if none are selected.
  44548. */
  44549. const String getCurrentTabName() const;
  44550. /** Returns the index of the currently selected tab.
  44551. This could return -1 if none are selected.
  44552. */
  44553. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  44554. /** Returns the button for a specific tab.
  44555. The button that is returned may be deleted later by this component, so don't hang
  44556. on to the pointer that is returned. A null pointer may be returned if the index is
  44557. out of range.
  44558. */
  44559. TabBarButton* getTabButton (int index) const;
  44560. /** Returns the index of a TabBarButton if it belongs to this bar. */
  44561. int indexOfTabButton (const TabBarButton* button) const;
  44562. /** Callback method to indicate the selected tab has been changed.
  44563. @see setCurrentTabIndex
  44564. */
  44565. virtual void currentTabChanged (int newCurrentTabIndex,
  44566. const String& newCurrentTabName);
  44567. /** Callback method to indicate that the user has right-clicked on a tab.
  44568. (Or ctrl-clicked on the Mac)
  44569. */
  44570. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  44571. /** Returns the colour of a tab.
  44572. This is the colour that was specified in addTab().
  44573. */
  44574. const Colour getTabBackgroundColour (int tabIndex);
  44575. /** Changes the background colour of a tab.
  44576. @see addTab, getTabBackgroundColour
  44577. */
  44578. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44579. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44580. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44581. methods.
  44582. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44583. */
  44584. enum ColourIds
  44585. {
  44586. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  44587. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  44588. the look and feel will choose an appropriate colour. */
  44589. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  44590. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  44591. this isn't specified, the look and feel will choose an appropriate
  44592. colour. */
  44593. };
  44594. /** @internal */
  44595. void resized();
  44596. /** @internal */
  44597. void lookAndFeelChanged();
  44598. protected:
  44599. /** This creates one of the tabs.
  44600. If you need to use custom tab components, you can override this method and
  44601. return your own class instead of the default.
  44602. */
  44603. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44604. private:
  44605. Orientation orientation;
  44606. struct TabInfo
  44607. {
  44608. ScopedPointer<TabBarButton> component;
  44609. String name;
  44610. Colour colour;
  44611. };
  44612. OwnedArray <TabInfo> tabs;
  44613. double minimumScale;
  44614. int currentTabIndex;
  44615. class BehindFrontTabComp;
  44616. friend class BehindFrontTabComp;
  44617. friend class ScopedPointer<BehindFrontTabComp>;
  44618. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  44619. ScopedPointer<Button> extraTabsButton;
  44620. void showExtraItemsMenu();
  44621. static void extraItemsMenuCallback (int, TabbedButtonBar*);
  44622. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  44623. };
  44624. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44625. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  44626. /**
  44627. A component with a TabbedButtonBar along one of its sides.
  44628. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  44629. with addTab(), and this will take care of showing the pages for you when the
  44630. user clicks on a different tab.
  44631. @see TabbedButtonBar
  44632. */
  44633. class JUCE_API TabbedComponent : public Component
  44634. {
  44635. public:
  44636. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  44637. Once created, add some tabs with the addTab() method.
  44638. */
  44639. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  44640. /** Destructor. */
  44641. ~TabbedComponent();
  44642. /** Changes the placement of the tabs.
  44643. This will rearrange the layout to place the tabs along the appropriate
  44644. side of this component, and will shift the content component accordingly.
  44645. @see TabbedButtonBar::setOrientation
  44646. */
  44647. void setOrientation (TabbedButtonBar::Orientation orientation);
  44648. /** Returns the current tab placement.
  44649. @see setOrientation, TabbedButtonBar::getOrientation
  44650. */
  44651. TabbedButtonBar::Orientation getOrientation() const throw();
  44652. /** Specifies how many pixels wide or high the tab-bar should be.
  44653. If the tabs are placed along the top or bottom, this specified the height
  44654. of the bar; if they're along the left or right edges, it'll be the width
  44655. of the bar.
  44656. */
  44657. void setTabBarDepth (int newDepth);
  44658. /** Returns the current thickness of the tab bar.
  44659. @see setTabBarDepth
  44660. */
  44661. int getTabBarDepth() const throw() { return tabDepth; }
  44662. /** Specifies the thickness of an outline that should be drawn around the content component.
  44663. If this thickness is > 0, a line will be drawn around the three sides of the content
  44664. component which don't touch the tab-bar, and the content component will be inset by this amount.
  44665. To set the colour of the line, use setColour (outlineColourId, ...).
  44666. */
  44667. void setOutline (int newThickness);
  44668. /** Specifies a gap to leave around the edge of the content component.
  44669. Each edge of the content component will be indented by the given number of pixels.
  44670. */
  44671. void setIndent (int indentThickness);
  44672. /** Removes all the tabs from the bar.
  44673. @see TabbedButtonBar::clearTabs
  44674. */
  44675. void clearTabs();
  44676. /** Adds a tab to the tab-bar.
  44677. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  44678. is true, it will be deleted when the tab is removed or when this object is
  44679. deleted.
  44680. @see TabbedButtonBar::addTab
  44681. */
  44682. void addTab (const String& tabName,
  44683. const Colour& tabBackgroundColour,
  44684. Component* contentComponent,
  44685. bool deleteComponentWhenNotNeeded,
  44686. int insertIndex = -1);
  44687. /** Changes the name of one of the tabs. */
  44688. void setTabName (int tabIndex, const String& newName);
  44689. /** Gets rid of one of the tabs. */
  44690. void removeTab (int tabIndex);
  44691. /** Returns the number of tabs in the bar. */
  44692. int getNumTabs() const;
  44693. /** Returns a list of all the tab names in the bar. */
  44694. const StringArray getTabNames() const;
  44695. /** Returns the content component that was added for the given index.
  44696. Be sure not to use or delete the components that are returned, as this may interfere
  44697. with the TabbedComponent's use of them.
  44698. */
  44699. Component* getTabContentComponent (int tabIndex) const throw();
  44700. /** Returns the colour of one of the tabs. */
  44701. const Colour getTabBackgroundColour (int tabIndex) const throw();
  44702. /** Changes the background colour of one of the tabs. */
  44703. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44704. /** Changes the currently-selected tab.
  44705. To deselect all the tabs, pass -1 as the index.
  44706. @see TabbedButtonBar::setCurrentTabIndex
  44707. */
  44708. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44709. /** Returns the index of the currently selected tab.
  44710. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  44711. */
  44712. int getCurrentTabIndex() const;
  44713. /** Returns the name of the currently selected tab.
  44714. @see addTab, TabbedButtonBar::getCurrentTabName()
  44715. */
  44716. const String getCurrentTabName() const;
  44717. /** Returns the current component that's filling the panel.
  44718. This will return 0 if there isn't one.
  44719. */
  44720. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  44721. /** Callback method to indicate the selected tab has been changed.
  44722. @see setCurrentTabIndex
  44723. */
  44724. virtual void currentTabChanged (int newCurrentTabIndex,
  44725. const String& newCurrentTabName);
  44726. /** Callback method to indicate that the user has right-clicked on a tab.
  44727. (Or ctrl-clicked on the Mac)
  44728. */
  44729. virtual void popupMenuClickOnTab (int tabIndex,
  44730. const String& tabName);
  44731. /** Returns the tab button bar component that is being used.
  44732. */
  44733. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  44734. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44735. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44736. methods.
  44737. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44738. */
  44739. enum ColourIds
  44740. {
  44741. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  44742. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  44743. (See setOutline) */
  44744. };
  44745. /** @internal */
  44746. void paint (Graphics& g);
  44747. /** @internal */
  44748. void resized();
  44749. /** @internal */
  44750. void lookAndFeelChanged();
  44751. protected:
  44752. /** This creates one of the tab buttons.
  44753. If you need to use custom tab components, you can override this method and
  44754. return your own class instead of the default.
  44755. */
  44756. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44757. /** @internal */
  44758. ScopedPointer<TabbedButtonBar> tabs;
  44759. private:
  44760. Array <WeakReference<Component> > contentComponents;
  44761. WeakReference<Component> panelComponent;
  44762. int tabDepth;
  44763. int outlineThickness, edgeIndent;
  44764. class ButtonBar;
  44765. friend class ButtonBar;
  44766. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  44767. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  44768. };
  44769. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44770. /*** End of inlined file: juce_TabbedComponent.h ***/
  44771. /*** Start of inlined file: juce_DocumentWindow.h ***/
  44772. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44773. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44774. /*** Start of inlined file: juce_MenuBarModel.h ***/
  44775. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  44776. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  44777. /**
  44778. A class for controlling MenuBar components.
  44779. This class is used to tell a MenuBar what menus to show, and to respond
  44780. to a menu being selected.
  44781. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  44782. */
  44783. class JUCE_API MenuBarModel : private AsyncUpdater,
  44784. private ApplicationCommandManagerListener
  44785. {
  44786. public:
  44787. MenuBarModel() throw();
  44788. /** Destructor. */
  44789. virtual ~MenuBarModel();
  44790. /** Call this when some of your menu items have changed.
  44791. This method will cause a callback to any MenuBarListener objects that
  44792. are registered with this model.
  44793. If this model is displaying items from an ApplicationCommandManager, you
  44794. can use the setApplicationCommandManagerToWatch() method to cause
  44795. change messages to be sent automatically when the ApplicationCommandManager
  44796. is changed.
  44797. @see addListener, removeListener, MenuBarListener
  44798. */
  44799. void menuItemsChanged();
  44800. /** Tells the menu bar to listen to the specified command manager, and to update
  44801. itself when the commands change.
  44802. This will also allow it to flash a menu name when a command from that menu
  44803. is invoked using a keystroke.
  44804. */
  44805. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  44806. /** A class to receive callbacks when a MenuBarModel changes.
  44807. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  44808. */
  44809. class JUCE_API Listener
  44810. {
  44811. public:
  44812. /** Destructor. */
  44813. virtual ~Listener() {}
  44814. /** This callback is made when items are changed in the menu bar model.
  44815. */
  44816. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  44817. /** This callback is made when an application command is invoked that
  44818. is represented by one of the items in the menu bar model.
  44819. */
  44820. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  44821. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  44822. };
  44823. /** Registers a listener for callbacks when the menu items in this model change.
  44824. The listener object will get callbacks when this object's menuItemsChanged()
  44825. method is called.
  44826. @see removeListener
  44827. */
  44828. void addListener (Listener* listenerToAdd) throw();
  44829. /** Removes a listener.
  44830. @see addListener
  44831. */
  44832. void removeListener (Listener* listenerToRemove) throw();
  44833. /** This method must return a list of the names of the menus. */
  44834. virtual const StringArray getMenuBarNames() = 0;
  44835. /** This should return the popup menu to display for a given top-level menu.
  44836. @param topLevelMenuIndex the index of the top-level menu to show
  44837. @param menuName the name of the top-level menu item to show
  44838. */
  44839. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  44840. const String& menuName) = 0;
  44841. /** This is called when a menu item has been clicked on.
  44842. @param menuItemID the item ID of the PopupMenu item that was selected
  44843. @param topLevelMenuIndex the index of the top-level menu from which the item was
  44844. chosen (just in case you've used duplicate ID numbers
  44845. on more than one of the popup menus)
  44846. */
  44847. virtual void menuItemSelected (int menuItemID,
  44848. int topLevelMenuIndex) = 0;
  44849. #if JUCE_MAC || DOXYGEN
  44850. /** MAC ONLY - Sets the model that is currently being shown as the main
  44851. menu bar at the top of the screen on the Mac.
  44852. You can pass 0 to stop the current model being displayed. Be careful
  44853. not to delete a model while it is being used.
  44854. An optional extra menu can be specified, containing items to add to the top of
  44855. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  44856. an apple, it's the one next to it, with your application's name at the top
  44857. and the services menu etc on it). When one of these items is selected, the
  44858. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  44859. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  44860. object then newMenuBarModel must be non-null.
  44861. */
  44862. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  44863. const PopupMenu* extraAppleMenuItems = 0);
  44864. /** MAC ONLY - Returns the menu model that is currently being shown as
  44865. the main menu bar.
  44866. */
  44867. static MenuBarModel* getMacMainMenu();
  44868. #endif
  44869. /** @internal */
  44870. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  44871. /** @internal */
  44872. void applicationCommandListChanged();
  44873. /** @internal */
  44874. void handleAsyncUpdate();
  44875. private:
  44876. ApplicationCommandManager* manager;
  44877. ListenerList <Listener> listeners;
  44878. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  44879. };
  44880. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  44881. typedef MenuBarModel::Listener MenuBarModelListener;
  44882. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  44883. /*** End of inlined file: juce_MenuBarModel.h ***/
  44884. /**
  44885. A resizable window with a title bar and maximise, minimise and close buttons.
  44886. This subclass of ResizableWindow creates a fairly standard type of window with
  44887. a title bar and various buttons. The name of the component is shown in the
  44888. title bar, and an icon can optionally be specified with setIcon().
  44889. All the methods available to a ResizableWindow are also available to this,
  44890. so it can easily be made resizable, minimised, maximised, etc.
  44891. It's not advisable to add child components directly to a DocumentWindow: put them
  44892. inside your content component instead. And overriding methods like resized(), moved(), etc
  44893. is also not recommended - instead override these methods for your content component.
  44894. (If for some obscure reason you do need to override these methods, always remember to
  44895. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  44896. decorations correctly).
  44897. You can also automatically add a menu bar to the window, using the setMenuBar()
  44898. method.
  44899. @see ResizableWindow, DialogWindow
  44900. */
  44901. class JUCE_API DocumentWindow : public ResizableWindow
  44902. {
  44903. public:
  44904. /** The set of available button-types that can be put on the title bar.
  44905. @see setTitleBarButtonsRequired
  44906. */
  44907. enum TitleBarButtons
  44908. {
  44909. minimiseButton = 1,
  44910. maximiseButton = 2,
  44911. closeButton = 4,
  44912. /** A combination of all the buttons above. */
  44913. allButtons = 7
  44914. };
  44915. /** Creates a DocumentWindow.
  44916. @param name the name to give the component - this is also
  44917. the title shown at the top of the window. To change
  44918. this later, use setName()
  44919. @param backgroundColour the colour to use for filling the window's background.
  44920. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  44921. should be shown on the title bar. This value is a bitwise
  44922. combination of values from the TitleBarButtons enum. Note
  44923. that it can be "allButtons" to get them all. You
  44924. can change this later with the setTitleBarButtonsRequired()
  44925. method, which can also specify where they are positioned.
  44926. @param addToDesktop if true, the window will be automatically added to the
  44927. desktop; if false, you can use it as a child component
  44928. @see TitleBarButtons
  44929. */
  44930. DocumentWindow (const String& name,
  44931. const Colour& backgroundColour,
  44932. int requiredButtons,
  44933. bool addToDesktop = true);
  44934. /** Destructor.
  44935. If a content component has been set with setContentOwned(), it will be deleted.
  44936. */
  44937. ~DocumentWindow();
  44938. /** Changes the component's name.
  44939. (This is overridden from Component::setName() to cause a repaint, as
  44940. the name is what gets drawn across the window's title bar).
  44941. */
  44942. void setName (const String& newName);
  44943. /** Sets an icon to show in the title bar, next to the title.
  44944. A copy is made internally of the image, so the caller can delete the
  44945. image after calling this. If 0 is passed-in, any existing icon will be
  44946. removed.
  44947. */
  44948. void setIcon (const Image& imageToUse);
  44949. /** Changes the height of the title-bar. */
  44950. void setTitleBarHeight (int newHeight);
  44951. /** Returns the current title bar height. */
  44952. int getTitleBarHeight() const;
  44953. /** Changes the set of title-bar buttons being shown.
  44954. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  44955. should be shown on the title bar. This value is a bitwise
  44956. combination of values from the TitleBarButtons enum. Note
  44957. that it can be "allButtons" to get them all.
  44958. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  44959. left side of the bar; if false, they'll be placed at the right
  44960. */
  44961. void setTitleBarButtonsRequired (int requiredButtons,
  44962. bool positionTitleBarButtonsOnLeft);
  44963. /** Sets whether the title should be centred within the window.
  44964. If true, the title text is shown in the middle of the title-bar; if false,
  44965. it'll be shown at the left of the bar.
  44966. */
  44967. void setTitleBarTextCentred (bool textShouldBeCentred);
  44968. /** Creates a menu inside this window.
  44969. @param menuBarModel this specifies a MenuBarModel that should be used to
  44970. generate the contents of a menu bar that will be placed
  44971. just below the title bar, and just above any content
  44972. component. If this value is zero, any existing menu bar
  44973. will be removed from the component; if non-zero, one will
  44974. be added if it's required.
  44975. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  44976. or less to use the look-and-feel's default size.
  44977. */
  44978. void setMenuBar (MenuBarModel* menuBarModel,
  44979. int menuBarHeight = 0);
  44980. /** Returns the current menu bar component, or null if there isn't one.
  44981. This is probably a MenuBarComponent, unless a custom one has been set using
  44982. setMenuBarComponent().
  44983. */
  44984. Component* getMenuBarComponent() const throw();
  44985. /** Replaces the current menu bar with a custom component.
  44986. The component will be owned and deleted by the document window.
  44987. */
  44988. void setMenuBarComponent (Component* newMenuBarComponent);
  44989. /** This method is called when the user tries to close the window.
  44990. This is triggered by the user clicking the close button, or using some other
  44991. OS-specific key shortcut or OS menu for getting rid of a window.
  44992. If the window is just a pop-up, you should override this closeButtonPressed()
  44993. method and make it delete the window in whatever way is appropriate for your
  44994. app. E.g. you might just want to call "delete this".
  44995. If your app is centred around this window such that the whole app should quit when
  44996. the window is closed, then you will probably want to use this method as an opportunity
  44997. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  44998. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  44999. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  45000. or closing it via the taskbar icon on Windows).
  45001. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  45002. redirects it to call this method, so any methods of closing the window that are
  45003. caught by userTriedToCloseWindow() will also end up here).
  45004. */
  45005. virtual void closeButtonPressed();
  45006. /** Callback that is triggered when the minimise button is pressed.
  45007. The default implementation of this calls ResizableWindow::setMinimised(), but
  45008. you can override it to do more customised behaviour.
  45009. */
  45010. virtual void minimiseButtonPressed();
  45011. /** Callback that is triggered when the maximise button is pressed, or when the
  45012. title-bar is double-clicked.
  45013. The default implementation of this calls ResizableWindow::setFullScreen(), but
  45014. you can override it to do more customised behaviour.
  45015. */
  45016. virtual void maximiseButtonPressed();
  45017. /** Returns the close button, (or 0 if there isn't one). */
  45018. Button* getCloseButton() const throw();
  45019. /** Returns the minimise button, (or 0 if there isn't one). */
  45020. Button* getMinimiseButton() const throw();
  45021. /** Returns the maximise button, (or 0 if there isn't one). */
  45022. Button* getMaximiseButton() const throw();
  45023. /** A set of colour IDs to use to change the colour of various aspects of the window.
  45024. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45025. methods.
  45026. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45027. */
  45028. enum ColourIds
  45029. {
  45030. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  45031. and feel class how this is used. */
  45032. };
  45033. /** @internal */
  45034. void paint (Graphics& g);
  45035. /** @internal */
  45036. void resized();
  45037. /** @internal */
  45038. void lookAndFeelChanged();
  45039. /** @internal */
  45040. const BorderSize<int> getBorderThickness();
  45041. /** @internal */
  45042. const BorderSize<int> getContentComponentBorder();
  45043. /** @internal */
  45044. void mouseDoubleClick (const MouseEvent& e);
  45045. /** @internal */
  45046. void userTriedToCloseWindow();
  45047. /** @internal */
  45048. void activeWindowStatusChanged();
  45049. /** @internal */
  45050. int getDesktopWindowStyleFlags() const;
  45051. /** @internal */
  45052. void parentHierarchyChanged();
  45053. /** @internal */
  45054. const Rectangle<int> getTitleBarArea();
  45055. private:
  45056. int titleBarHeight, menuBarHeight, requiredButtons;
  45057. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  45058. ScopedPointer <Button> titleBarButtons [3];
  45059. Image titleBarIcon;
  45060. ScopedPointer <Component> menuBar;
  45061. MenuBarModel* menuBarModel;
  45062. class ButtonListenerProxy;
  45063. friend class ScopedPointer <ButtonListenerProxy>;
  45064. ScopedPointer <ButtonListenerProxy> buttonListener;
  45065. void repaintTitleBar();
  45066. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  45067. };
  45068. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  45069. /*** End of inlined file: juce_DocumentWindow.h ***/
  45070. class MultiDocumentPanel;
  45071. class MDITabbedComponentInternal;
  45072. /**
  45073. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  45074. component.
  45075. It's like a normal DocumentWindow but has some extra functionality to make sure
  45076. everything works nicely inside a MultiDocumentPanel.
  45077. @see MultiDocumentPanel
  45078. */
  45079. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  45080. {
  45081. public:
  45082. /**
  45083. */
  45084. MultiDocumentPanelWindow (const Colour& backgroundColour);
  45085. /** Destructor. */
  45086. ~MultiDocumentPanelWindow();
  45087. /** @internal */
  45088. void maximiseButtonPressed();
  45089. /** @internal */
  45090. void closeButtonPressed();
  45091. /** @internal */
  45092. void activeWindowStatusChanged();
  45093. /** @internal */
  45094. void broughtToFront();
  45095. private:
  45096. void updateOrder();
  45097. MultiDocumentPanel* getOwner() const throw();
  45098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  45099. };
  45100. /**
  45101. A component that contains a set of other components either in floating windows
  45102. or tabs.
  45103. This acts as a panel that can be used to hold a set of open document windows, with
  45104. different layout modes.
  45105. Use addDocument() and closeDocument() to add or remove components from the
  45106. panel - never use any of the Component methods to access the panel's child
  45107. components directly, as these are managed internally.
  45108. */
  45109. class JUCE_API MultiDocumentPanel : public Component,
  45110. private ComponentListener
  45111. {
  45112. public:
  45113. /** Creates an empty panel.
  45114. Use addDocument() and closeDocument() to add or remove components from the
  45115. panel - never use any of the Component methods to access the panel's child
  45116. components directly, as these are managed internally.
  45117. */
  45118. MultiDocumentPanel();
  45119. /** Destructor.
  45120. When deleted, this will call closeAllDocuments (false) to make sure all its
  45121. components are deleted. If you need to make sure all documents are saved
  45122. before closing, then you should call closeAllDocuments (true) and check that
  45123. it returns true before deleting the panel.
  45124. */
  45125. ~MultiDocumentPanel();
  45126. /** Tries to close all the documents.
  45127. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45128. be called for each open document, and any of these calls fails, this method
  45129. will stop and return false, leaving some documents still open.
  45130. If checkItsOkToCloseFirst is false, then all documents will be closed
  45131. unconditionally.
  45132. @see closeDocument
  45133. */
  45134. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  45135. /** Adds a document component to the panel.
  45136. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  45137. this will fail and return false. (If it does fail, the component passed-in will not be
  45138. deleted, even if deleteWhenRemoved was set to true).
  45139. The MultiDocumentPanel will deal with creating a window border to go around your component,
  45140. so just pass in the bare content component here, no need to give it a ResizableWindow
  45141. or DocumentWindow.
  45142. @param component the component to add
  45143. @param backgroundColour the background colour to use to fill the component's
  45144. window or tab
  45145. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  45146. or closeAllDocuments(), then it will be deleted. If false, then
  45147. the caller must handle the component's deletion
  45148. */
  45149. bool addDocument (Component* component,
  45150. const Colour& backgroundColour,
  45151. bool deleteWhenRemoved);
  45152. /** Closes one of the documents.
  45153. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  45154. be called, and if it fails, this method will return false without closing the
  45155. document.
  45156. If checkItsOkToCloseFirst is false, then the documents will be closed
  45157. unconditionally.
  45158. The component will be deleted if the deleteWhenRemoved parameter was set to
  45159. true when it was added with addDocument.
  45160. @see addDocument, closeAllDocuments
  45161. */
  45162. bool closeDocument (Component* component,
  45163. bool checkItsOkToCloseFirst);
  45164. /** Returns the number of open document windows.
  45165. @see getDocument
  45166. */
  45167. int getNumDocuments() const throw();
  45168. /** Returns one of the open documents.
  45169. The order of the documents in this array may change when they are added, removed
  45170. or moved around.
  45171. @see getNumDocuments
  45172. */
  45173. Component* getDocument (int index) const throw();
  45174. /** Returns the document component that is currently focused or on top.
  45175. If currently using floating windows, then this will be the component in the currently
  45176. active window, or the top component if none are active.
  45177. If it's currently in tabbed mode, then it'll return the component in the active tab.
  45178. @see setActiveDocument
  45179. */
  45180. Component* getActiveDocument() const throw();
  45181. /** Makes one of the components active and brings it to the top.
  45182. @see getActiveDocument
  45183. */
  45184. void setActiveDocument (Component* component);
  45185. /** Callback which gets invoked when the currently-active document changes. */
  45186. virtual void activeDocumentChanged();
  45187. /** Sets a limit on how many windows can be open at once.
  45188. If this is zero or less there's no limit (the default). addDocument() will fail
  45189. if this number is exceeded.
  45190. */
  45191. void setMaximumNumDocuments (int maximumNumDocuments);
  45192. /** Sets an option to make the document fullscreen if there's only one document open.
  45193. If set to true, then if there's only one document, it'll fill the whole of this
  45194. component without tabs or a window border. If false, then tabs or a window
  45195. will always be shown, even if there's only one document. If there's more than
  45196. one document open, then this option makes no difference.
  45197. */
  45198. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  45199. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  45200. */
  45201. bool isFullscreenWhenOneDocument() const throw();
  45202. /** The different layout modes available. */
  45203. enum LayoutMode
  45204. {
  45205. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  45206. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  45207. };
  45208. /** Changes the panel's mode.
  45209. @see LayoutMode, getLayoutMode
  45210. */
  45211. void setLayoutMode (LayoutMode newLayoutMode);
  45212. /** Returns the current layout mode. */
  45213. LayoutMode getLayoutMode() const throw() { return mode; }
  45214. /** Sets the background colour for the whole panel.
  45215. Each document has its own background colour, but this is the one used to fill the areas
  45216. behind them.
  45217. */
  45218. void setBackgroundColour (const Colour& newBackgroundColour);
  45219. /** Returns the current background colour.
  45220. @see setBackgroundColour
  45221. */
  45222. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  45223. /** A subclass must override this to say whether its currently ok for a document
  45224. to be closed.
  45225. This method is called by closeDocument() and closeAllDocuments() to indicate that
  45226. a document should be saved if possible, ready for it to be closed.
  45227. If this method returns true, then it means the document is ok and can be closed.
  45228. If it returns false, then it means that the closeDocument() method should stop
  45229. and not close.
  45230. Normally, you'd use this method to ask the user if they want to save any changes,
  45231. then return true if the save operation went ok. If the user cancelled the save
  45232. operation you could return false here to abort the close operation.
  45233. If your component is based on the FileBasedDocument class, then you'd probably want
  45234. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  45235. FileBasedDocument::savedOk
  45236. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  45237. */
  45238. virtual bool tryToCloseDocument (Component* component) = 0;
  45239. /** Creates a new window to be used for a document.
  45240. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  45241. but you might want to override it to return a custom component.
  45242. */
  45243. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  45244. /** @internal */
  45245. void paint (Graphics& g);
  45246. /** @internal */
  45247. void resized();
  45248. /** @internal */
  45249. void componentNameChanged (Component&);
  45250. private:
  45251. LayoutMode mode;
  45252. Array <Component*> components;
  45253. ScopedPointer<TabbedComponent> tabComponent;
  45254. Colour backgroundColour;
  45255. int maximumNumDocuments, numDocsBeforeTabsUsed;
  45256. friend class MultiDocumentPanelWindow;
  45257. friend class MDITabbedComponentInternal;
  45258. Component* getContainerComp (Component* c) const;
  45259. void updateOrder();
  45260. void addWindow (Component* component);
  45261. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  45262. };
  45263. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  45264. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  45265. #endif
  45266. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  45267. #endif
  45268. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  45269. #endif
  45270. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45271. /*** Start of inlined file: juce_ResizableEdgeComponent.h ***/
  45272. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45273. #define __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45274. /**
  45275. A component that resizes its parent component when dragged.
  45276. This component forms a bar along one edge of a component, allowing it to
  45277. be dragged by that edges to resize it.
  45278. To use it, just add it to your component, positioning it along the appropriate
  45279. edge. Make sure you reposition the resizer component each time the parent's size
  45280. changes, to keep it in the correct position.
  45281. @see ResizbleBorderComponent, ResizableCornerComponent
  45282. */
  45283. class JUCE_API ResizableEdgeComponent : public Component
  45284. {
  45285. public:
  45286. enum Edge
  45287. {
  45288. leftEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's left-hand edge. */
  45289. rightEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's right-hand edge. */
  45290. topEdge, /**< Indicates a horizontal bar that can be dragged up/down to move the top of the component. */
  45291. bottomEdge /**< Indicates a horizontal bar that can be dragged up/down to move the bottom of the component. */
  45292. };
  45293. /** Creates a resizer bar.
  45294. Pass in the target component which you want to be resized when this one is
  45295. dragged. The target component will usually be this component's parent, but this
  45296. isn't mandatory.
  45297. Remember that when the target component is resized, it'll need to move and
  45298. resize this component to keep it in place, as this won't happen automatically.
  45299. If the constrainer parameter is non-zero, then this object will be used to enforce
  45300. limits on the size and position that the component can be stretched to. Make sure
  45301. that the constrainer isn't deleted while still in use by this object.
  45302. @see ComponentBoundsConstrainer
  45303. */
  45304. ResizableEdgeComponent (Component* componentToResize,
  45305. ComponentBoundsConstrainer* constrainer,
  45306. Edge edgeToResize);
  45307. /** Destructor. */
  45308. ~ResizableEdgeComponent();
  45309. bool isVertical() const throw();
  45310. protected:
  45311. /** @internal */
  45312. void paint (Graphics& g);
  45313. /** @internal */
  45314. void mouseDown (const MouseEvent& e);
  45315. /** @internal */
  45316. void mouseDrag (const MouseEvent& e);
  45317. /** @internal */
  45318. void mouseUp (const MouseEvent& e);
  45319. private:
  45320. WeakReference<Component> component;
  45321. ComponentBoundsConstrainer* constrainer;
  45322. Rectangle<int> originalBounds;
  45323. const Edge edge;
  45324. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableEdgeComponent);
  45325. };
  45326. #endif // __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  45327. /*** End of inlined file: juce_ResizableEdgeComponent.h ***/
  45328. #endif
  45329. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  45330. #endif
  45331. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45332. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  45333. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45334. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45335. /**
  45336. For laying out a set of components, where the components have preferred sizes
  45337. and size limits, but where they are allowed to stretch to fill the available
  45338. space.
  45339. For example, if you have a component containing several other components, and
  45340. each one should be given a share of the total size, you could use one of these
  45341. to resize the child components when the parent component is resized. Then
  45342. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  45343. A StretchableLayoutManager operates only in one dimension, so if you have a set
  45344. of components stacked vertically on top of each other, you'd use one to manage their
  45345. heights. To build up complex arrangements of components, e.g. for applications
  45346. with multiple nested panels, you would use more than one StretchableLayoutManager.
  45347. E.g. by using two (one vertical, one horizontal), you could create a resizable
  45348. spreadsheet-style table.
  45349. E.g.
  45350. @code
  45351. class MyComp : public Component
  45352. {
  45353. StretchableLayoutManager myLayout;
  45354. MyComp()
  45355. {
  45356. myLayout.setItemLayout (0, // for item 0
  45357. 50, 100, // must be between 50 and 100 pixels in size
  45358. -0.6); // and its preferred size is 60% of the total available space
  45359. myLayout.setItemLayout (1, // for item 1
  45360. -0.2, -0.6, // size must be between 20% and 60% of the available space
  45361. 50); // and its preferred size is 50 pixels
  45362. }
  45363. void resized()
  45364. {
  45365. // make a list of two of our child components that we want to reposition
  45366. Component* comps[] = { myComp1, myComp2 };
  45367. // this will position the 2 components, one above the other, to fit
  45368. // vertically into the rectangle provided.
  45369. myLayout.layOutComponents (comps, 2,
  45370. 0, 0, getWidth(), getHeight(),
  45371. true);
  45372. }
  45373. };
  45374. @endcode
  45375. @see StretchableLayoutResizerBar
  45376. */
  45377. class JUCE_API StretchableLayoutManager
  45378. {
  45379. public:
  45380. /** Creates an empty layout.
  45381. You'll need to add some item properties to the layout before it can be used
  45382. to resize things - see setItemLayout().
  45383. */
  45384. StretchableLayoutManager();
  45385. /** Destructor. */
  45386. ~StretchableLayoutManager();
  45387. /** For a numbered item, this sets its size limits and preferred size.
  45388. @param itemIndex the index of the item to change.
  45389. @param minimumSize the minimum size that this item is allowed to be - a positive number
  45390. indicates an absolute size in pixels. A negative number indicates a
  45391. proportion of the available space (e.g -0.5 is 50%)
  45392. @param maximumSize the maximum size that this item is allowed to be - a positive number
  45393. indicates an absolute size in pixels. A negative number indicates a
  45394. proportion of the available space
  45395. @param preferredSize the size that this item would like to be, if there's enough room. A
  45396. positive number indicates an absolute size in pixels. A negative number
  45397. indicates a proportion of the available space
  45398. @see getItemLayout
  45399. */
  45400. void setItemLayout (int itemIndex,
  45401. double minimumSize,
  45402. double maximumSize,
  45403. double preferredSize);
  45404. /** For a numbered item, this returns its size limits and preferred size.
  45405. @param itemIndex the index of the item.
  45406. @param minimumSize the minimum size that this item is allowed to be - a positive number
  45407. indicates an absolute size in pixels. A negative number indicates a
  45408. proportion of the available space (e.g -0.5 is 50%)
  45409. @param maximumSize the maximum size that this item is allowed to be - a positive number
  45410. indicates an absolute size in pixels. A negative number indicates a
  45411. proportion of the available space
  45412. @param preferredSize the size that this item would like to be, if there's enough room. A
  45413. positive number indicates an absolute size in pixels. A negative number
  45414. indicates a proportion of the available space
  45415. @returns false if the item's properties hadn't been set
  45416. @see setItemLayout
  45417. */
  45418. bool getItemLayout (int itemIndex,
  45419. double& minimumSize,
  45420. double& maximumSize,
  45421. double& preferredSize) const;
  45422. /** Clears all the properties that have been set with setItemLayout() and resets
  45423. this object to its initial state.
  45424. */
  45425. void clearAllItems();
  45426. /** Takes a set of components that correspond to the layout's items, and positions
  45427. them to fill a space.
  45428. This will try to give each item its preferred size, whether that's a relative size
  45429. or an absolute one.
  45430. @param components an array of components that correspond to each of the
  45431. numbered items that the StretchableLayoutManager object
  45432. has been told about with setItemLayout()
  45433. @param numComponents the number of components in the array that is passed-in. This
  45434. should be the same as the number of items this object has been
  45435. told about.
  45436. @param x the left of the rectangle in which the components should
  45437. be laid out
  45438. @param y the top of the rectangle in which the components should
  45439. be laid out
  45440. @param width the width of the rectangle in which the components should
  45441. be laid out
  45442. @param height the height of the rectangle in which the components should
  45443. be laid out
  45444. @param vertically if true, the components will be positioned in a vertical stack,
  45445. so that they fill the height of the rectangle. If false, they
  45446. will be placed side-by-side in a horizontal line, filling the
  45447. available width
  45448. @param resizeOtherDimension if true, this means that the components will have their
  45449. other dimension resized to fit the space - i.e. if the 'vertically'
  45450. parameter is true, their x-positions and widths are adjusted to fit
  45451. the x and width parameters; if 'vertically' is false, their y-positions
  45452. and heights are adjusted to fit the y and height parameters.
  45453. */
  45454. void layOutComponents (Component** components,
  45455. int numComponents,
  45456. int x, int y, int width, int height,
  45457. bool vertically,
  45458. bool resizeOtherDimension);
  45459. /** Returns the current position of one of the items.
  45460. This is only a valid call after layOutComponents() has been called, as it
  45461. returns the last position that this item was placed at. If the layout was
  45462. vertical, the value returned will be the y position of the top of the item,
  45463. relative to the top of the rectangle in which the items were placed (so for
  45464. example, item 0 will always have position of 0, even in the rectangle passed
  45465. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  45466. the position returned is the item's left-hand position, again relative to the
  45467. x position of the rectangle used.
  45468. @see getItemCurrentSize, setItemPosition
  45469. */
  45470. int getItemCurrentPosition (int itemIndex) const;
  45471. /** Returns the current size of one of the items.
  45472. This is only meaningful after layOutComponents() has been called, as it
  45473. returns the last size that this item was given. If the layout was done
  45474. vertically, it'll return the item's height in pixels; if it was horizontal,
  45475. it'll return its width.
  45476. @see getItemCurrentRelativeSize
  45477. */
  45478. int getItemCurrentAbsoluteSize (int itemIndex) const;
  45479. /** Returns the current size of one of the items.
  45480. This is only meaningful after layOutComponents() has been called, as it
  45481. returns the last size that this item was given. If the layout was done
  45482. vertically, it'll return a negative value representing the item's height relative
  45483. to the last size used for laying the components out; if the layout was done
  45484. horizontally it'll be the proportion of its width.
  45485. @see getItemCurrentAbsoluteSize
  45486. */
  45487. double getItemCurrentRelativeSize (int itemIndex) const;
  45488. /** Moves one of the items, shifting along any other items as necessary in
  45489. order to get it to the desired position.
  45490. Calling this method will also update the preferred sizes of the items it
  45491. shuffles along, so that they reflect their new positions.
  45492. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  45493. about when it's dragged).
  45494. @param itemIndex the item to move
  45495. @param newPosition the absolute position that you'd like this item to move
  45496. to. The item might not be able to always reach exactly this position,
  45497. because other items may have minimum sizes that constrain how
  45498. far it can go
  45499. */
  45500. void setItemPosition (int itemIndex,
  45501. int newPosition);
  45502. private:
  45503. struct ItemLayoutProperties
  45504. {
  45505. int itemIndex;
  45506. int currentSize;
  45507. double minSize, maxSize, preferredSize;
  45508. };
  45509. OwnedArray <ItemLayoutProperties> items;
  45510. int totalSize;
  45511. static int sizeToRealSize (double size, int totalSpace);
  45512. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  45513. void setTotalSize (int newTotalSize);
  45514. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  45515. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  45516. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  45517. void updatePrefSizesToMatchCurrentPositions();
  45518. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  45519. };
  45520. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45521. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  45522. #endif
  45523. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45524. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45525. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45526. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45527. /**
  45528. A component that acts as one of the vertical or horizontal bars you see being
  45529. used to resize panels in a window.
  45530. One of these acts with a StretchableLayoutManager to resize the other components.
  45531. @see StretchableLayoutManager
  45532. */
  45533. class JUCE_API StretchableLayoutResizerBar : public Component
  45534. {
  45535. public:
  45536. /** Creates a resizer bar for use on a specified layout.
  45537. @param layoutToUse the layout that will be affected when this bar
  45538. is dragged
  45539. @param itemIndexInLayout the item index in the layout that corresponds to
  45540. this bar component. You'll need to set up the item
  45541. properties in a suitable way for a divider bar, e.g.
  45542. for an 8-pixel wide bar which, you could call
  45543. myLayout->setItemLayout (barIndex, 8, 8, 8)
  45544. @param isBarVertical true if it's an upright bar that you drag left and
  45545. right; false for a horizontal one that you drag up and
  45546. down
  45547. */
  45548. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  45549. int itemIndexInLayout,
  45550. bool isBarVertical);
  45551. /** Destructor. */
  45552. ~StretchableLayoutResizerBar();
  45553. /** This is called when the bar is dragged.
  45554. This method must update the positions of any components whose position is
  45555. determined by the StretchableLayoutManager, because they might have just
  45556. moved.
  45557. The default implementation calls the resized() method of this component's
  45558. parent component, because that's often where you're likely to apply the
  45559. layout, but it can be overridden for more specific needs.
  45560. */
  45561. virtual void hasBeenMoved();
  45562. /** @internal */
  45563. void paint (Graphics& g);
  45564. /** @internal */
  45565. void mouseDown (const MouseEvent& e);
  45566. /** @internal */
  45567. void mouseDrag (const MouseEvent& e);
  45568. private:
  45569. StretchableLayoutManager* layout;
  45570. int itemIndex, mouseDownPos;
  45571. bool isVertical;
  45572. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  45573. };
  45574. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45575. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45576. #endif
  45577. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45578. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  45579. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45580. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45581. /**
  45582. A utility class for fitting a set of objects whose sizes can vary between
  45583. a minimum and maximum size, into a space.
  45584. This is a trickier algorithm than it would first seem, so I've put it in this
  45585. class to allow it to be shared by various bits of code.
  45586. To use it, create one of these objects, call addItem() to add the list of items
  45587. you need, then call resizeToFit(), which will change all their sizes. You can
  45588. then retrieve the new sizes with getItemSize() and getNumItems().
  45589. It's currently used by the TableHeaderComponent for stretching out the table
  45590. headings to fill the table's width.
  45591. */
  45592. class StretchableObjectResizer
  45593. {
  45594. public:
  45595. /** Creates an empty object resizer. */
  45596. StretchableObjectResizer();
  45597. /** Destructor. */
  45598. ~StretchableObjectResizer();
  45599. /** Adds an item to the list.
  45600. The order parameter lets you specify groups of items that are resized first when some
  45601. space needs to be found. Those items with an order of 0 will be the first ones to be
  45602. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  45603. will then try resizing the items with an order of 1, then 2, and so on.
  45604. */
  45605. void addItem (double currentSize,
  45606. double minSize,
  45607. double maxSize,
  45608. int order = 0);
  45609. /** Resizes all the items to fit this amount of space.
  45610. This will attempt to fit them in without exceeding each item's miniumum and
  45611. maximum sizes. In cases where none of the items can be expanded or enlarged any
  45612. further, the final size may be greater or less than the size passed in.
  45613. After calling this method, you can retrieve the new sizes with the getItemSize()
  45614. method.
  45615. */
  45616. void resizeToFit (double targetSize);
  45617. /** Returns the number of items that have been added. */
  45618. int getNumItems() const throw() { return items.size(); }
  45619. /** Returns the size of one of the items. */
  45620. double getItemSize (int index) const throw();
  45621. private:
  45622. struct Item
  45623. {
  45624. double size;
  45625. double minSize;
  45626. double maxSize;
  45627. int order;
  45628. };
  45629. OwnedArray <Item> items;
  45630. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  45631. };
  45632. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45633. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  45634. #endif
  45635. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45636. #endif
  45637. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45638. #endif
  45639. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  45640. #endif
  45641. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45642. /*** Start of inlined file: juce_LookAndFeel.h ***/
  45643. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45644. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  45645. class ToggleButton;
  45646. class TextButton;
  45647. class AlertWindow;
  45648. class TextLayout;
  45649. class ScrollBar;
  45650. class BubbleComponent;
  45651. class ComboBox;
  45652. class Button;
  45653. class FilenameComponent;
  45654. class DocumentWindow;
  45655. class ResizableWindow;
  45656. class GroupComponent;
  45657. class MenuBarComponent;
  45658. class DropShadower;
  45659. class GlyphArrangement;
  45660. class PropertyComponent;
  45661. class TableHeaderComponent;
  45662. class Toolbar;
  45663. class ToolbarItemComponent;
  45664. class PopupMenu;
  45665. class ProgressBar;
  45666. class FileBrowserComponent;
  45667. class DirectoryContentsDisplayComponent;
  45668. class FilePreviewComponent;
  45669. class ImageButton;
  45670. class CallOutBox;
  45671. class Drawable;
  45672. class CaretComponent;
  45673. /**
  45674. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  45675. can be used to apply different 'skins' to the application.
  45676. */
  45677. class JUCE_API LookAndFeel
  45678. {
  45679. public:
  45680. /** Creates the default JUCE look and feel. */
  45681. LookAndFeel();
  45682. /** Destructor. */
  45683. virtual ~LookAndFeel();
  45684. /** Returns the current default look-and-feel for a component to use when it
  45685. hasn't got one explicitly set.
  45686. @see setDefaultLookAndFeel
  45687. */
  45688. static LookAndFeel& getDefaultLookAndFeel() throw();
  45689. /** Changes the default look-and-feel.
  45690. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  45691. set to 0, it will revert to using the default one. The
  45692. object passed-in must be deleted by the caller when
  45693. it's no longer needed.
  45694. @see getDefaultLookAndFeel
  45695. */
  45696. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  45697. /** Looks for a colour that has been registered with the given colour ID number.
  45698. If a colour has been set for this ID number using setColour(), then it is
  45699. returned. If none has been set, it will just return Colours::black.
  45700. The colour IDs for various purposes are stored as enums in the components that
  45701. they are relevent to - for an example, see Slider::ColourIds,
  45702. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  45703. If you're looking up a colour for use in drawing a component, it's usually
  45704. best not to call this directly, but to use the Component::findColour() method
  45705. instead. That will first check whether a suitable colour has been registered
  45706. directly with the component, and will fall-back on calling the component's
  45707. LookAndFeel's findColour() method if none is found.
  45708. @see setColour, Component::findColour, Component::setColour
  45709. */
  45710. const Colour findColour (int colourId) const throw();
  45711. /** Registers a colour to be used for a particular purpose.
  45712. For more details, see the comments for findColour().
  45713. @see findColour, Component::findColour, Component::setColour
  45714. */
  45715. void setColour (int colourId, const Colour& colour) throw();
  45716. /** Returns true if the specified colour ID has been explicitly set using the
  45717. setColour() method.
  45718. */
  45719. bool isColourSpecified (int colourId) const throw();
  45720. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  45721. /** Allows you to change the default sans-serif font.
  45722. If you need to supply your own Typeface object for any of the default fonts, rather
  45723. than just supplying the name (e.g. if you want to use an embedded font), then
  45724. you should instead override getTypefaceForFont() to create and return the typeface.
  45725. */
  45726. void setDefaultSansSerifTypefaceName (const String& newName);
  45727. /** Override this to get the chance to swap a component's mouse cursor for a
  45728. customised one.
  45729. */
  45730. virtual const MouseCursor getMouseCursorFor (Component& component);
  45731. /** Draws the lozenge-shaped background for a standard button. */
  45732. virtual void drawButtonBackground (Graphics& g,
  45733. Button& button,
  45734. const Colour& backgroundColour,
  45735. bool isMouseOverButton,
  45736. bool isButtonDown);
  45737. virtual const Font getFontForTextButton (TextButton& button);
  45738. /** Draws the text for a TextButton. */
  45739. virtual void drawButtonText (Graphics& g,
  45740. TextButton& button,
  45741. bool isMouseOverButton,
  45742. bool isButtonDown);
  45743. /** Draws the contents of a standard ToggleButton. */
  45744. virtual void drawToggleButton (Graphics& g,
  45745. ToggleButton& button,
  45746. bool isMouseOverButton,
  45747. bool isButtonDown);
  45748. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  45749. virtual void drawTickBox (Graphics& g,
  45750. Component& component,
  45751. float x, float y, float w, float h,
  45752. bool ticked,
  45753. bool isEnabled,
  45754. bool isMouseOverButton,
  45755. bool isButtonDown);
  45756. /* AlertWindow handling..
  45757. */
  45758. virtual AlertWindow* createAlertWindow (const String& title,
  45759. const String& message,
  45760. const String& button1,
  45761. const String& button2,
  45762. const String& button3,
  45763. AlertWindow::AlertIconType iconType,
  45764. int numButtons,
  45765. Component* associatedComponent);
  45766. virtual void drawAlertBox (Graphics& g,
  45767. AlertWindow& alert,
  45768. const Rectangle<int>& textArea,
  45769. TextLayout& textLayout);
  45770. virtual int getAlertBoxWindowFlags();
  45771. virtual int getAlertWindowButtonHeight();
  45772. virtual const Font getAlertWindowMessageFont();
  45773. virtual const Font getAlertWindowFont();
  45774. void setUsingNativeAlertWindows (bool shouldUseNativeAlerts);
  45775. bool isUsingNativeAlertWindows();
  45776. /** Draws a progress bar.
  45777. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  45778. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  45779. isn't known). It can use the current time as a basis for playing an animation.
  45780. (Used by progress bars in AlertWindow).
  45781. */
  45782. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  45783. int width, int height,
  45784. double progress, const String& textToShow);
  45785. // Draws a small image that spins to indicate that something's happening..
  45786. // This method should use the current time to animate itself, so just keep
  45787. // repainting it every so often.
  45788. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  45789. int x, int y, int w, int h);
  45790. /** Draws one of the buttons on a scrollbar.
  45791. @param g the context to draw into
  45792. @param scrollbar the bar itself
  45793. @param width the width of the button
  45794. @param height the height of the button
  45795. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  45796. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  45797. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  45798. @param isButtonDown whether the mouse button's held down
  45799. */
  45800. virtual void drawScrollbarButton (Graphics& g,
  45801. ScrollBar& scrollbar,
  45802. int width, int height,
  45803. int buttonDirection,
  45804. bool isScrollbarVertical,
  45805. bool isMouseOverButton,
  45806. bool isButtonDown);
  45807. /** Draws the thumb area of a scrollbar.
  45808. @param g the context to draw into
  45809. @param scrollbar the bar itself
  45810. @param x the x position of the left edge of the thumb area to draw in
  45811. @param y the y position of the top edge of the thumb area to draw in
  45812. @param width the width of the thumb area to draw in
  45813. @param height the height of the thumb area to draw in
  45814. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  45815. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  45816. thumb, or its x position for horizontal bars
  45817. @param thumbSize for vertical bars, the height of the thumb, or its width for
  45818. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  45819. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  45820. currently dragging the thumb
  45821. @param isMouseDown whether the mouse is currently dragging the scrollbar
  45822. */
  45823. virtual void drawScrollbar (Graphics& g,
  45824. ScrollBar& scrollbar,
  45825. int x, int y,
  45826. int width, int height,
  45827. bool isScrollbarVertical,
  45828. int thumbStartPosition,
  45829. int thumbSize,
  45830. bool isMouseOver,
  45831. bool isMouseDown);
  45832. /** Returns the component effect to use for a scrollbar */
  45833. virtual ImageEffectFilter* getScrollbarEffect();
  45834. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  45835. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  45836. /** Returns the default thickness to use for a scrollbar. */
  45837. virtual int getDefaultScrollbarWidth();
  45838. /** Returns the length in pixels to use for a scrollbar button. */
  45839. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  45840. /** Returns a tick shape for use in yes/no boxes, etc. */
  45841. virtual const Path getTickShape (float height);
  45842. /** Returns a cross shape for use in yes/no boxes, etc. */
  45843. virtual const Path getCrossShape (float height);
  45844. /** Draws the + or - box in a treeview. */
  45845. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  45846. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  45847. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  45848. virtual CaretComponent* createCaretComponent (Component* keyFocusOwner);
  45849. // These return a pointer to an internally cached drawable - make sure you don't keep
  45850. // a copy of this pointer anywhere, as it may become invalid in the future.
  45851. virtual const Drawable* getDefaultFolderImage();
  45852. virtual const Drawable* getDefaultDocumentFileImage();
  45853. virtual void createFileChooserHeaderText (const String& title,
  45854. const String& instructions,
  45855. GlyphArrangement& destArrangement,
  45856. int width);
  45857. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  45858. const String& filename, Image* icon,
  45859. const String& fileSizeDescription,
  45860. const String& fileTimeDescription,
  45861. bool isDirectory,
  45862. bool isItemSelected,
  45863. int itemIndex,
  45864. DirectoryContentsDisplayComponent& component);
  45865. virtual Button* createFileBrowserGoUpButton();
  45866. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  45867. DirectoryContentsDisplayComponent* fileListComponent,
  45868. FilePreviewComponent* previewComp,
  45869. ComboBox* currentPathBox,
  45870. TextEditor* filenameBox,
  45871. Button* goUpButton);
  45872. virtual void drawBubble (Graphics& g,
  45873. float tipX, float tipY,
  45874. float boxX, float boxY, float boxW, float boxH);
  45875. /** Fills the background of a popup menu component. */
  45876. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  45877. /** Draws one of the items in a popup menu. */
  45878. virtual void drawPopupMenuItem (Graphics& g,
  45879. int width, int height,
  45880. bool isSeparator,
  45881. bool isActive,
  45882. bool isHighlighted,
  45883. bool isTicked,
  45884. bool hasSubMenu,
  45885. const String& text,
  45886. const String& shortcutKeyText,
  45887. Image* image,
  45888. const Colour* const textColour);
  45889. /** Returns the size and style of font to use in popup menus. */
  45890. virtual const Font getPopupMenuFont();
  45891. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  45892. int width, int height,
  45893. bool isScrollUpArrow);
  45894. /** Finds the best size for an item in a popup menu. */
  45895. virtual void getIdealPopupMenuItemSize (const String& text,
  45896. bool isSeparator,
  45897. int standardMenuItemHeight,
  45898. int& idealWidth,
  45899. int& idealHeight);
  45900. virtual int getMenuWindowFlags();
  45901. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  45902. bool isMouseOverBar,
  45903. MenuBarComponent& menuBar);
  45904. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  45905. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  45906. virtual void drawMenuBarItem (Graphics& g,
  45907. int width, int height,
  45908. int itemIndex,
  45909. const String& itemText,
  45910. bool isMouseOverItem,
  45911. bool isMenuOpen,
  45912. bool isMouseOverBar,
  45913. MenuBarComponent& menuBar);
  45914. virtual void drawComboBox (Graphics& g, int width, int height,
  45915. bool isButtonDown,
  45916. int buttonX, int buttonY,
  45917. int buttonW, int buttonH,
  45918. ComboBox& box);
  45919. virtual const Font getComboBoxFont (ComboBox& box);
  45920. virtual Label* createComboBoxTextBox (ComboBox& box);
  45921. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  45922. virtual void drawLabel (Graphics& g, Label& label);
  45923. virtual void drawLinearSlider (Graphics& g,
  45924. int x, int y,
  45925. int width, int height,
  45926. float sliderPos,
  45927. float minSliderPos,
  45928. float maxSliderPos,
  45929. const Slider::SliderStyle style,
  45930. Slider& slider);
  45931. virtual void drawLinearSliderBackground (Graphics& g,
  45932. int x, int y,
  45933. int width, int height,
  45934. float sliderPos,
  45935. float minSliderPos,
  45936. float maxSliderPos,
  45937. const Slider::SliderStyle style,
  45938. Slider& slider);
  45939. virtual void drawLinearSliderThumb (Graphics& g,
  45940. int x, int y,
  45941. int width, int height,
  45942. float sliderPos,
  45943. float minSliderPos,
  45944. float maxSliderPos,
  45945. const Slider::SliderStyle style,
  45946. Slider& slider);
  45947. virtual int getSliderThumbRadius (Slider& slider);
  45948. virtual void drawRotarySlider (Graphics& g,
  45949. int x, int y,
  45950. int width, int height,
  45951. float sliderPosProportional,
  45952. float rotaryStartAngle,
  45953. float rotaryEndAngle,
  45954. Slider& slider);
  45955. virtual Button* createSliderButton (bool isIncrement);
  45956. virtual Label* createSliderTextBox (Slider& slider);
  45957. virtual ImageEffectFilter* getSliderEffect();
  45958. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  45959. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  45960. virtual Button* createFilenameComponentBrowseButton (const String& text);
  45961. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  45962. ComboBox* filenameBox, Button* browseButton);
  45963. virtual void drawCornerResizer (Graphics& g,
  45964. int w, int h,
  45965. bool isMouseOver,
  45966. bool isMouseDragging);
  45967. virtual void drawResizableFrame (Graphics& g,
  45968. int w, int h,
  45969. const BorderSize<int>& borders);
  45970. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  45971. const BorderSize<int>& border,
  45972. ResizableWindow& window);
  45973. virtual void drawResizableWindowBorder (Graphics& g,
  45974. int w, int h,
  45975. const BorderSize<int>& border,
  45976. ResizableWindow& window);
  45977. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  45978. Graphics& g, int w, int h,
  45979. int titleSpaceX, int titleSpaceW,
  45980. const Image* icon,
  45981. bool drawTitleTextOnLeft);
  45982. virtual Button* createDocumentWindowButton (int buttonType);
  45983. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  45984. int titleBarX, int titleBarY,
  45985. int titleBarW, int titleBarH,
  45986. Button* minimiseButton,
  45987. Button* maximiseButton,
  45988. Button* closeButton,
  45989. bool positionTitleBarButtonsOnLeft);
  45990. virtual int getDefaultMenuBarHeight();
  45991. virtual DropShadower* createDropShadowerForComponent (Component* component);
  45992. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  45993. int w, int h,
  45994. bool isVerticalBar,
  45995. bool isMouseOver,
  45996. bool isMouseDragging);
  45997. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  45998. const String& text,
  45999. const Justification& position,
  46000. GroupComponent& group);
  46001. virtual void createTabButtonShape (Path& p,
  46002. int width, int height,
  46003. int tabIndex,
  46004. const String& text,
  46005. Button& button,
  46006. TabbedButtonBar::Orientation orientation,
  46007. bool isMouseOver,
  46008. bool isMouseDown,
  46009. bool isFrontTab);
  46010. virtual void fillTabButtonShape (Graphics& g,
  46011. const Path& path,
  46012. const Colour& preferredBackgroundColour,
  46013. int tabIndex,
  46014. const String& text,
  46015. Button& button,
  46016. TabbedButtonBar::Orientation orientation,
  46017. bool isMouseOver,
  46018. bool isMouseDown,
  46019. bool isFrontTab);
  46020. virtual void drawTabButtonText (Graphics& g,
  46021. int x, int y, int w, int h,
  46022. const Colour& preferredBackgroundColour,
  46023. int tabIndex,
  46024. const String& text,
  46025. Button& button,
  46026. TabbedButtonBar::Orientation orientation,
  46027. bool isMouseOver,
  46028. bool isMouseDown,
  46029. bool isFrontTab);
  46030. virtual int getTabButtonOverlap (int tabDepth);
  46031. virtual int getTabButtonSpaceAroundImage();
  46032. virtual int getTabButtonBestWidth (int tabIndex,
  46033. const String& text,
  46034. int tabDepth,
  46035. Button& button);
  46036. virtual void drawTabButton (Graphics& g,
  46037. int w, int h,
  46038. const Colour& preferredColour,
  46039. int tabIndex,
  46040. const String& text,
  46041. Button& button,
  46042. TabbedButtonBar::Orientation orientation,
  46043. bool isMouseOver,
  46044. bool isMouseDown,
  46045. bool isFrontTab);
  46046. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  46047. int w, int h,
  46048. TabbedButtonBar& tabBar,
  46049. TabbedButtonBar::Orientation orientation);
  46050. virtual Button* createTabBarExtrasButton();
  46051. virtual void drawImageButton (Graphics& g, Image* image,
  46052. int imageX, int imageY, int imageW, int imageH,
  46053. const Colour& overlayColour,
  46054. float imageOpacity,
  46055. ImageButton& button);
  46056. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  46057. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  46058. int width, int height,
  46059. bool isMouseOver, bool isMouseDown,
  46060. int columnFlags);
  46061. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  46062. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  46063. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  46064. bool isMouseOver, bool isMouseDown,
  46065. ToolbarItemComponent& component);
  46066. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  46067. const String& text, ToolbarItemComponent& component);
  46068. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  46069. bool isOpen, int width, int height);
  46070. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  46071. PropertyComponent& component);
  46072. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  46073. PropertyComponent& component);
  46074. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  46075. virtual void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  46076. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  46077. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  46078. /**
  46079. */
  46080. virtual void playAlertSound();
  46081. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  46082. static void drawGlassSphere (Graphics& g,
  46083. float x, float y,
  46084. float diameter,
  46085. const Colour& colour,
  46086. float outlineThickness) throw();
  46087. static void drawGlassPointer (Graphics& g,
  46088. float x, float y,
  46089. float diameter,
  46090. const Colour& colour, float outlineThickness,
  46091. int direction) throw();
  46092. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  46093. static void drawGlassLozenge (Graphics& g,
  46094. float x, float y,
  46095. float width, float height,
  46096. const Colour& colour,
  46097. float outlineThickness,
  46098. float cornerSize,
  46099. bool flatOnLeft, bool flatOnRight,
  46100. bool flatOnTop, bool flatOnBottom) throw();
  46101. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  46102. private:
  46103. friend JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  46104. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  46105. Array <int> colourIds;
  46106. Array <Colour> colours;
  46107. // default typeface names
  46108. String defaultSans, defaultSerif, defaultFixed;
  46109. ScopedPointer<Drawable> folderImage, documentImage;
  46110. bool useNativeAlertWindows;
  46111. void drawShinyButtonShape (Graphics& g,
  46112. float x, float y, float w, float h, float maxCornerSize,
  46113. const Colour& baseColour,
  46114. float strokeWidth,
  46115. bool flatOnLeft,
  46116. bool flatOnRight,
  46117. bool flatOnTop,
  46118. bool flatOnBottom) throw();
  46119. // This has been deprecated - see the new parameter list..
  46120. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  46121. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  46122. };
  46123. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  46124. /*** End of inlined file: juce_LookAndFeel.h ***/
  46125. #endif
  46126. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46127. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  46128. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46129. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46130. /**
  46131. The original Juce look-and-feel.
  46132. */
  46133. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  46134. {
  46135. public:
  46136. /** Creates the default JUCE look and feel. */
  46137. OldSchoolLookAndFeel();
  46138. /** Destructor. */
  46139. virtual ~OldSchoolLookAndFeel();
  46140. /** Draws the lozenge-shaped background for a standard button. */
  46141. virtual void drawButtonBackground (Graphics& g,
  46142. Button& button,
  46143. const Colour& backgroundColour,
  46144. bool isMouseOverButton,
  46145. bool isButtonDown);
  46146. /** Draws the contents of a standard ToggleButton. */
  46147. virtual void drawToggleButton (Graphics& g,
  46148. ToggleButton& button,
  46149. bool isMouseOverButton,
  46150. bool isButtonDown);
  46151. virtual void drawTickBox (Graphics& g,
  46152. Component& component,
  46153. float x, float y, float w, float h,
  46154. bool ticked,
  46155. bool isEnabled,
  46156. bool isMouseOverButton,
  46157. bool isButtonDown);
  46158. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46159. int width, int height,
  46160. double progress, const String& textToShow);
  46161. virtual void drawScrollbarButton (Graphics& g,
  46162. ScrollBar& scrollbar,
  46163. int width, int height,
  46164. int buttonDirection,
  46165. bool isScrollbarVertical,
  46166. bool isMouseOverButton,
  46167. bool isButtonDown);
  46168. virtual void drawScrollbar (Graphics& g,
  46169. ScrollBar& scrollbar,
  46170. int x, int y,
  46171. int width, int height,
  46172. bool isScrollbarVertical,
  46173. int thumbStartPosition,
  46174. int thumbSize,
  46175. bool isMouseOver,
  46176. bool isMouseDown);
  46177. virtual ImageEffectFilter* getScrollbarEffect();
  46178. virtual void drawTextEditorOutline (Graphics& g,
  46179. int width, int height,
  46180. TextEditor& textEditor);
  46181. /** Fills the background of a popup menu component. */
  46182. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  46183. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  46184. bool isMouseOverBar,
  46185. MenuBarComponent& menuBar);
  46186. virtual void drawComboBox (Graphics& g, int width, int height,
  46187. bool isButtonDown,
  46188. int buttonX, int buttonY,
  46189. int buttonW, int buttonH,
  46190. ComboBox& box);
  46191. virtual const Font getComboBoxFont (ComboBox& box);
  46192. virtual void drawLinearSlider (Graphics& g,
  46193. int x, int y,
  46194. int width, int height,
  46195. float sliderPos,
  46196. float minSliderPos,
  46197. float maxSliderPos,
  46198. const Slider::SliderStyle style,
  46199. Slider& slider);
  46200. virtual int getSliderThumbRadius (Slider& slider);
  46201. virtual Button* createSliderButton (bool isIncrement);
  46202. virtual ImageEffectFilter* getSliderEffect();
  46203. virtual void drawCornerResizer (Graphics& g,
  46204. int w, int h,
  46205. bool isMouseOver,
  46206. bool isMouseDragging);
  46207. virtual Button* createDocumentWindowButton (int buttonType);
  46208. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  46209. int titleBarX, int titleBarY,
  46210. int titleBarW, int titleBarH,
  46211. Button* minimiseButton,
  46212. Button* maximiseButton,
  46213. Button* closeButton,
  46214. bool positionTitleBarButtonsOnLeft);
  46215. private:
  46216. DropShadowEffect scrollbarShadow;
  46217. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  46218. };
  46219. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  46220. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  46221. #endif
  46222. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46223. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  46224. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46225. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46226. /**
  46227. A menu bar component.
  46228. @see MenuBarModel
  46229. */
  46230. class JUCE_API MenuBarComponent : public Component,
  46231. private MenuBarModel::Listener,
  46232. private Timer
  46233. {
  46234. public:
  46235. /** Creates a menu bar.
  46236. @param model the model object to use to control this bar. You can
  46237. pass 0 into this if you like, and set the model later
  46238. using the setModel() method
  46239. */
  46240. MenuBarComponent (MenuBarModel* model);
  46241. /** Destructor. */
  46242. ~MenuBarComponent();
  46243. /** Changes the model object to use to control the bar.
  46244. This can be 0, in which case the bar will be empty. Don't delete the object
  46245. that is passed-in while it's still being used by this MenuBar.
  46246. */
  46247. void setModel (MenuBarModel* newModel);
  46248. /** Returns the current menu bar model being used.
  46249. */
  46250. MenuBarModel* getModel() const throw();
  46251. /** Pops up one of the menu items.
  46252. This lets you manually open one of the menus - it could be triggered by a
  46253. key shortcut, for example.
  46254. */
  46255. void showMenu (int menuIndex);
  46256. /** @internal */
  46257. void paint (Graphics& g);
  46258. /** @internal */
  46259. void resized();
  46260. /** @internal */
  46261. void mouseEnter (const MouseEvent& e);
  46262. /** @internal */
  46263. void mouseExit (const MouseEvent& e);
  46264. /** @internal */
  46265. void mouseDown (const MouseEvent& e);
  46266. /** @internal */
  46267. void mouseDrag (const MouseEvent& e);
  46268. /** @internal */
  46269. void mouseUp (const MouseEvent& e);
  46270. /** @internal */
  46271. void mouseMove (const MouseEvent& e);
  46272. /** @internal */
  46273. void handleCommandMessage (int commandId);
  46274. /** @internal */
  46275. bool keyPressed (const KeyPress& key);
  46276. /** @internal */
  46277. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  46278. /** @internal */
  46279. void menuCommandInvoked (MenuBarModel* menuBarModel,
  46280. const ApplicationCommandTarget::InvocationInfo& info);
  46281. private:
  46282. MenuBarModel* model;
  46283. StringArray menuNames;
  46284. Array <int> xPositions;
  46285. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  46286. int lastMouseX, lastMouseY;
  46287. int getItemAt (int x, int y);
  46288. void setItemUnderMouse (int index);
  46289. void setOpenItem (int index);
  46290. void updateItemUnderMouse (int x, int y);
  46291. void timerCallback();
  46292. void repaintMenuItem (int index);
  46293. void menuDismissed (int topLevelIndex, int itemId);
  46294. static void menuBarMenuDismissedCallback (int, MenuBarComponent*, int);
  46295. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  46296. };
  46297. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  46298. /*** End of inlined file: juce_MenuBarComponent.h ***/
  46299. #endif
  46300. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  46301. #endif
  46302. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  46303. #endif
  46304. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  46305. #endif
  46306. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  46307. #endif
  46308. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  46309. #endif
  46310. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  46311. #endif
  46312. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46313. /*** Start of inlined file: juce_LassoComponent.h ***/
  46314. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46315. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46316. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  46317. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46318. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46319. /** Manages a list of selectable items.
  46320. Use one of these to keep a track of things that the user has highlighted, like
  46321. icons or things in a list.
  46322. The class is templated so that you can use it to hold either a set of pointers
  46323. to objects, or a set of ID numbers or handles, for cases where each item may
  46324. not always have a corresponding object.
  46325. To be informed when items are selected/deselected, register a ChangeListener with
  46326. this object.
  46327. @see SelectableObject
  46328. */
  46329. template <class SelectableItemType>
  46330. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  46331. {
  46332. public:
  46333. typedef SelectableItemType ItemType;
  46334. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  46335. /** Creates an empty set. */
  46336. SelectedItemSet()
  46337. {
  46338. }
  46339. /** Creates a set based on an array of items. */
  46340. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  46341. : selectedItems (items)
  46342. {
  46343. }
  46344. /** Creates a copy of another set. */
  46345. SelectedItemSet (const SelectedItemSet& other)
  46346. : selectedItems (other.selectedItems)
  46347. {
  46348. }
  46349. /** Creates a copy of another set. */
  46350. SelectedItemSet& operator= (const SelectedItemSet& other)
  46351. {
  46352. if (selectedItems != other.selectedItems)
  46353. {
  46354. selectedItems = other.selectedItems;
  46355. changed();
  46356. }
  46357. return *this;
  46358. }
  46359. /** Clears any other currently selected items, and selects this item.
  46360. If this item is already the only thing selected, no change notification
  46361. will be sent out.
  46362. @see addToSelection, addToSelectionBasedOnModifiers
  46363. */
  46364. void selectOnly (ParameterType item)
  46365. {
  46366. if (isSelected (item))
  46367. {
  46368. for (int i = selectedItems.size(); --i >= 0;)
  46369. {
  46370. if (selectedItems.getUnchecked(i) != item)
  46371. {
  46372. deselect (selectedItems.getUnchecked(i));
  46373. i = jmin (i, selectedItems.size());
  46374. }
  46375. }
  46376. }
  46377. else
  46378. {
  46379. deselectAll();
  46380. changed();
  46381. selectedItems.add (item);
  46382. itemSelected (item);
  46383. }
  46384. }
  46385. /** Selects an item.
  46386. If the item is already selected, no change notification will be sent out.
  46387. @see selectOnly, addToSelectionBasedOnModifiers
  46388. */
  46389. void addToSelection (ParameterType item)
  46390. {
  46391. if (! isSelected (item))
  46392. {
  46393. changed();
  46394. selectedItems.add (item);
  46395. itemSelected (item);
  46396. }
  46397. }
  46398. /** Selects or deselects an item.
  46399. This will use the modifier keys to decide whether to deselect other items
  46400. first.
  46401. So if the shift key is held down, the item will be added without deselecting
  46402. anything (same as calling addToSelection() )
  46403. If no modifiers are down, the current selection will be cleared first (same
  46404. as calling selectOnly() )
  46405. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  46406. so it'll be added to the set unless it's already there, in which case it'll be
  46407. deselected.
  46408. If the items that you're selecting can also be dragged, you may need to use the
  46409. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  46410. subtleties of this kind of usage.
  46411. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  46412. */
  46413. void addToSelectionBasedOnModifiers (ParameterType item,
  46414. const ModifierKeys& modifiers)
  46415. {
  46416. if (modifiers.isShiftDown())
  46417. {
  46418. addToSelection (item);
  46419. }
  46420. else if (modifiers.isCommandDown())
  46421. {
  46422. if (isSelected (item))
  46423. deselect (item);
  46424. else
  46425. addToSelection (item);
  46426. }
  46427. else
  46428. {
  46429. selectOnly (item);
  46430. }
  46431. }
  46432. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  46433. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  46434. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  46435. makes it easy to handle multiple-selection of sets of objects that can also
  46436. be dragged.
  46437. For example, if you have several items already selected, and you click on
  46438. one of them (without dragging), then you'd expect this to deselect the other, and
  46439. just select the item you clicked on. But if you had clicked on this item and
  46440. dragged it, you'd have expected them all to stay selected.
  46441. When you call this method, you'll need to store the boolean result, because the
  46442. addToSelectionOnMouseUp() method will need to be know this value.
  46443. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  46444. */
  46445. bool addToSelectionOnMouseDown (ParameterType item,
  46446. const ModifierKeys& modifiers)
  46447. {
  46448. if (isSelected (item))
  46449. {
  46450. return ! modifiers.isPopupMenu();
  46451. }
  46452. else
  46453. {
  46454. addToSelectionBasedOnModifiers (item, modifiers);
  46455. return false;
  46456. }
  46457. }
  46458. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  46459. Call this during a mouseUp callback, when you have previously called the
  46460. addToSelectionOnMouseDown() method during your mouseDown event.
  46461. See addToSelectionOnMouseDown() for more info
  46462. @param item the item to select (or deselect)
  46463. @param modifiers the modifiers from the mouse-up event
  46464. @param wasItemDragged true if your item was dragged during the mouse click
  46465. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  46466. back from the addToSelectionOnMouseDown() call that you
  46467. should have made during the matching mouseDown event
  46468. */
  46469. void addToSelectionOnMouseUp (ParameterType item,
  46470. const ModifierKeys& modifiers,
  46471. const bool wasItemDragged,
  46472. const bool resultOfMouseDownSelectMethod)
  46473. {
  46474. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  46475. addToSelectionBasedOnModifiers (item, modifiers);
  46476. }
  46477. /** Deselects an item. */
  46478. void deselect (ParameterType item)
  46479. {
  46480. const int i = selectedItems.indexOf (item);
  46481. if (i >= 0)
  46482. {
  46483. changed();
  46484. itemDeselected (selectedItems.remove (i));
  46485. }
  46486. }
  46487. /** Deselects all items. */
  46488. void deselectAll()
  46489. {
  46490. if (selectedItems.size() > 0)
  46491. {
  46492. changed();
  46493. for (int i = selectedItems.size(); --i >= 0;)
  46494. {
  46495. itemDeselected (selectedItems.remove (i));
  46496. i = jmin (i, selectedItems.size());
  46497. }
  46498. }
  46499. }
  46500. /** Returns the number of currently selected items.
  46501. @see getSelectedItem
  46502. */
  46503. int getNumSelected() const throw()
  46504. {
  46505. return selectedItems.size();
  46506. }
  46507. /** Returns one of the currently selected items.
  46508. Returns 0 if the index is out-of-range.
  46509. @see getNumSelected
  46510. */
  46511. SelectableItemType getSelectedItem (const int index) const throw()
  46512. {
  46513. return selectedItems [index];
  46514. }
  46515. /** True if this item is currently selected. */
  46516. bool isSelected (ParameterType item) const throw()
  46517. {
  46518. return selectedItems.contains (item);
  46519. }
  46520. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  46521. /** Can be overridden to do special handling when an item is selected.
  46522. For example, if the item is an object, you might want to call it and tell
  46523. it that it's being selected.
  46524. */
  46525. virtual void itemSelected (SelectableItemType item) { (void) item; }
  46526. /** Can be overridden to do special handling when an item is deselected.
  46527. For example, if the item is an object, you might want to call it and tell
  46528. it that it's being deselected.
  46529. */
  46530. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  46531. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  46532. */
  46533. void changed (const bool synchronous = false)
  46534. {
  46535. if (synchronous)
  46536. sendSynchronousChangeMessage();
  46537. else
  46538. sendChangeMessage();
  46539. }
  46540. private:
  46541. Array <SelectableItemType> selectedItems;
  46542. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  46543. };
  46544. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46545. /*** End of inlined file: juce_SelectedItemSet.h ***/
  46546. /**
  46547. A class used by the LassoComponent to manage the things that it selects.
  46548. This allows the LassoComponent to find out which items are within the lasso,
  46549. and to change the list of selected items.
  46550. @see LassoComponent, SelectedItemSet
  46551. */
  46552. template <class SelectableItemType>
  46553. class LassoSource
  46554. {
  46555. public:
  46556. /** Destructor. */
  46557. virtual ~LassoSource() {}
  46558. /** Returns the set of items that lie within a given lassoable region.
  46559. Your implementation of this method must find all the relevent items that lie
  46560. within the given rectangle. and add them to the itemsFound array.
  46561. The co-ordinates are relative to the top-left of the lasso component's parent
  46562. component. (i.e. they are the same as the size and position of the lasso
  46563. component itself).
  46564. */
  46565. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  46566. const Rectangle<int>& area) = 0;
  46567. /** Returns the SelectedItemSet that the lasso should update.
  46568. This set will be continuously updated by the LassoComponent as it gets
  46569. dragged around, so make sure that you've got a ChangeListener attached to
  46570. the set so that your UI objects will know when the selection changes and
  46571. be able to update themselves appropriately.
  46572. */
  46573. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  46574. };
  46575. /**
  46576. A component that acts as a rectangular selection region, which you drag with
  46577. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  46578. To use one of these:
  46579. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  46580. component, and call its beginLasso() method, giving it a
  46581. suitable LassoSource object that it can use to find out which items are in
  46582. the active area.
  46583. - Each time your parent component gets a mouseDrag event, call dragLasso()
  46584. to update the lasso's position - it will use its LassoSource to calculate and
  46585. update the current selection.
  46586. - After the drag has finished and you get a mouseUp callback, you should call
  46587. endLasso() to clean up. This will make the lasso component invisible, and you
  46588. can remove it from the parent component, or delete it.
  46589. The class takes into account the modifier keys that are being held down while
  46590. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  46591. be added to the original selection; if ctrl or command is pressed, they will be
  46592. xor'ed with any previously selected items.
  46593. @see LassoSource, SelectedItemSet
  46594. */
  46595. template <class SelectableItemType>
  46596. class LassoComponent : public Component
  46597. {
  46598. public:
  46599. /** Creates a Lasso component.
  46600. The fill colour is used to fill the lasso'ed rectangle, and the outline
  46601. colour is used to draw a line around its edge.
  46602. */
  46603. explicit LassoComponent (const int outlineThickness_ = 1)
  46604. : source (0),
  46605. outlineThickness (outlineThickness_)
  46606. {
  46607. }
  46608. /** Destructor. */
  46609. ~LassoComponent()
  46610. {
  46611. }
  46612. /** Call this in your mouseDown event, to initialise a drag.
  46613. Pass in a suitable LassoSource object which the lasso will use to find
  46614. the items and change the selection.
  46615. After using this method to initialise the lasso, repeatedly call dragLasso()
  46616. in your component's mouseDrag callback.
  46617. @see dragLasso, endLasso, LassoSource
  46618. */
  46619. void beginLasso (const MouseEvent& e,
  46620. LassoSource <SelectableItemType>* const lassoSource)
  46621. {
  46622. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  46623. jassert (lassoSource != 0); // the source can't be null!
  46624. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  46625. source = lassoSource;
  46626. if (lassoSource != 0)
  46627. originalSelection = lassoSource->getLassoSelection().getItemArray();
  46628. setSize (0, 0);
  46629. dragStartPos = e.getMouseDownPosition();
  46630. }
  46631. /** Call this in your mouseDrag event, to update the lasso's position.
  46632. This must be repeatedly calling when the mouse is dragged, after you've
  46633. first initialised the lasso with beginLasso().
  46634. This method takes into account the modifier keys that are being held down, so
  46635. if shift is pressed, then the lassoed items will be added to any that were
  46636. previously selected; if ctrl or command is pressed, then they will be xor'ed
  46637. with previously selected items.
  46638. @see beginLasso, endLasso
  46639. */
  46640. void dragLasso (const MouseEvent& e)
  46641. {
  46642. if (source != 0)
  46643. {
  46644. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  46645. setVisible (true);
  46646. Array <SelectableItemType> itemsInLasso;
  46647. source->findLassoItemsInArea (itemsInLasso, getBounds());
  46648. if (e.mods.isShiftDown())
  46649. {
  46650. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  46651. itemsInLasso.addArray (originalSelection);
  46652. }
  46653. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  46654. {
  46655. Array <SelectableItemType> originalMinusNew (originalSelection);
  46656. originalMinusNew.removeValuesIn (itemsInLasso);
  46657. itemsInLasso.removeValuesIn (originalSelection);
  46658. itemsInLasso.addArray (originalMinusNew);
  46659. }
  46660. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  46661. }
  46662. }
  46663. /** Call this in your mouseUp event, after the lasso has been dragged.
  46664. @see beginLasso, dragLasso
  46665. */
  46666. void endLasso()
  46667. {
  46668. source = 0;
  46669. originalSelection.clear();
  46670. setVisible (false);
  46671. }
  46672. /** A set of colour IDs to use to change the colour of various aspects of the label.
  46673. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  46674. methods.
  46675. Note that you can also use the constants from TextEditor::ColourIds to change the
  46676. colour of the text editor that is opened when a label is editable.
  46677. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  46678. */
  46679. enum ColourIds
  46680. {
  46681. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  46682. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  46683. };
  46684. /** @internal */
  46685. void paint (Graphics& g)
  46686. {
  46687. g.fillAll (findColour (lassoFillColourId));
  46688. g.setColour (findColour (lassoOutlineColourId));
  46689. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  46690. // this suggests that you've left a lasso comp lying around after the
  46691. // mouse drag has finished.. Be careful to call endLasso() when you get a
  46692. // mouse-up event.
  46693. jassert (isMouseButtonDownAnywhere());
  46694. }
  46695. /** @internal */
  46696. bool hitTest (int, int) { return false; }
  46697. private:
  46698. Array <SelectableItemType> originalSelection;
  46699. LassoSource <SelectableItemType>* source;
  46700. int outlineThickness;
  46701. Point<int> dragStartPos;
  46702. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  46703. };
  46704. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46705. /*** End of inlined file: juce_LassoComponent.h ***/
  46706. #endif
  46707. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  46708. #endif
  46709. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  46710. #endif
  46711. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46712. /*** Start of inlined file: juce_MouseInputSource.h ***/
  46713. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46714. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46715. class MouseInputSourceInternal;
  46716. /**
  46717. Represents a linear source of mouse events from a mouse device or individual finger
  46718. in a multi-touch environment.
  46719. Each MouseEvent object contains a reference to the MouseInputSource that generated
  46720. it. In an environment with a single mouse for input, all events will come from the
  46721. same source, but in a multi-touch system, there may be multiple MouseInputSource
  46722. obects active, each representing a stream of events coming from a particular finger.
  46723. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  46724. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  46725. the only events that can happen between a mouseDown and its corresponding mouseUp are
  46726. mouseDrags, etc.
  46727. When there are multiple touches arriving from multiple MouseInputSources, their
  46728. event streams may arrive in an interleaved order, so you should use the getIndex()
  46729. method to find out which finger each event came from.
  46730. @see MouseEvent
  46731. */
  46732. class JUCE_API MouseInputSource
  46733. {
  46734. public:
  46735. /** Creates a MouseInputSource.
  46736. You should never actually create a MouseInputSource in your own code - the
  46737. library takes care of managing these objects.
  46738. */
  46739. MouseInputSource (int index, bool isMouseDevice);
  46740. /** Destructor. */
  46741. ~MouseInputSource();
  46742. /** Returns true if this object represents a normal desk-based mouse device. */
  46743. bool isMouse() const;
  46744. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  46745. bool isTouch() const;
  46746. /** Returns true if this source has an on-screen pointer that can hover over
  46747. items without clicking them.
  46748. */
  46749. bool canHover() const;
  46750. /** Returns true if this source may have a scroll wheel. */
  46751. bool hasMouseWheel() const;
  46752. /** Returns this source's index in the global list of possible sources.
  46753. If the system only has a single mouse, there will only be a single MouseInputSource
  46754. with an index of 0.
  46755. If the system supports multi-touch input, then the index will represent a finger
  46756. number, starting from 0. When the first touch event begins, it will have finger
  46757. number 0, and then if a second touch happens while the first is still down, it
  46758. will have index 1, etc.
  46759. */
  46760. int getIndex() const;
  46761. /** Returns true if this device is currently being pressed. */
  46762. bool isDragging() const;
  46763. /** Returns the last-known screen position of this source. */
  46764. const Point<int> getScreenPosition() const;
  46765. /** Returns a set of modifiers that indicate which buttons are currently
  46766. held down on this device.
  46767. */
  46768. const ModifierKeys getCurrentModifiers() const;
  46769. /** Returns the component that was last known to be under this pointer. */
  46770. Component* getComponentUnderMouse() const;
  46771. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  46772. This is asynchronous - the event will occur on the message thread.
  46773. */
  46774. void triggerFakeMove() const;
  46775. /** Returns the number of clicks that should be counted as belonging to the
  46776. current mouse event.
  46777. So the mouse is currently down and it's the second click of a double-click, this
  46778. will return 2.
  46779. */
  46780. int getNumberOfMultipleClicks() const throw();
  46781. /** Returns the time at which the last mouse-down occurred. */
  46782. const Time getLastMouseDownTime() const throw();
  46783. /** Returns the screen position at which the last mouse-down occurred. */
  46784. const Point<int> getLastMouseDownPosition() const throw();
  46785. /** Returns true if this mouse is currently down, and if it has been dragged more
  46786. than a couple of pixels from the place it was pressed.
  46787. */
  46788. bool hasMouseMovedSignificantlySincePressed() const throw();
  46789. /** Returns true if this input source uses a visible mouse cursor. */
  46790. bool hasMouseCursor() const throw();
  46791. /** Changes the mouse cursor, (if there is one). */
  46792. void showMouseCursor (const MouseCursor& cursor);
  46793. /** Hides the mouse cursor (if there is one). */
  46794. void hideCursor();
  46795. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  46796. void revealCursor();
  46797. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  46798. void forceMouseCursorUpdate();
  46799. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  46800. bool canDoUnboundedMovement() const throw();
  46801. /** Allows the mouse to move beyond the edges of the screen.
  46802. Calling this method when the mouse button is currently pressed will remove the cursor
  46803. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  46804. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  46805. can be used for things like custom slider controls or dragging objects around, where
  46806. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  46807. The unbounded mode is automatically turned off when the mouse button is released, or
  46808. it can be turned off explicitly by calling this method again.
  46809. @param isEnabled whether to turn this mode on or off
  46810. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  46811. hidden; if true, it will only be hidden when it
  46812. is moved beyond the edge of the screen
  46813. */
  46814. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  46815. /** @internal */
  46816. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  46817. /** @internal */
  46818. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  46819. private:
  46820. friend class Desktop;
  46821. friend class ComponentPeer;
  46822. friend class MouseInputSourceInternal;
  46823. ScopedPointer<MouseInputSourceInternal> pimpl;
  46824. static const Point<int> getCurrentMousePosition();
  46825. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  46826. };
  46827. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46828. /*** End of inlined file: juce_MouseInputSource.h ***/
  46829. #endif
  46830. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  46831. #endif
  46832. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  46833. #endif
  46834. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  46835. #endif
  46836. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  46837. #endif
  46838. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  46839. #endif
  46840. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46841. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  46842. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46843. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46844. /**
  46845. A parallelogram defined by three RelativePoint positions.
  46846. @see RelativePoint, RelativeCoordinate
  46847. */
  46848. class JUCE_API RelativeParallelogram
  46849. {
  46850. public:
  46851. RelativeParallelogram();
  46852. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  46853. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  46854. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  46855. ~RelativeParallelogram();
  46856. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  46857. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  46858. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  46859. void getPath (Path& path, Expression::Scope* scope) const;
  46860. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  46861. bool isDynamic() const;
  46862. bool operator== (const RelativeParallelogram& other) const throw();
  46863. bool operator!= (const RelativeParallelogram& other) const throw();
  46864. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  46865. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  46866. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) throw();
  46867. RelativePoint topLeft, topRight, bottomLeft;
  46868. };
  46869. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46870. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  46871. #endif
  46872. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  46873. #endif
  46874. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46875. /*** Start of inlined file: juce_RelativePointPath.h ***/
  46876. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46877. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46878. class DrawablePath;
  46879. /**
  46880. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  46881. One of these paths can be converted into a Path object for drawing and manipulation, but
  46882. unlike a Path, its points can be dynamic instead of just fixed.
  46883. @see RelativePoint, RelativeCoordinate
  46884. */
  46885. class JUCE_API RelativePointPath
  46886. {
  46887. public:
  46888. RelativePointPath();
  46889. RelativePointPath (const RelativePointPath& other);
  46890. explicit RelativePointPath (const Path& path);
  46891. ~RelativePointPath();
  46892. bool operator== (const RelativePointPath& other) const throw();
  46893. bool operator!= (const RelativePointPath& other) const throw();
  46894. /** Resolves this points in this path and adds them to a normal Path object. */
  46895. void createPath (Path& path, Expression::Scope* scope) const;
  46896. /** Returns true if the path contains any non-fixed points. */
  46897. bool containsAnyDynamicPoints() const;
  46898. /** Quickly swaps the contents of this path with another. */
  46899. void swapWith (RelativePointPath& other) throw();
  46900. /** The types of element that may be contained in this path.
  46901. @see RelativePointPath::ElementBase
  46902. */
  46903. enum ElementType
  46904. {
  46905. nullElement,
  46906. startSubPathElement,
  46907. closeSubPathElement,
  46908. lineToElement,
  46909. quadraticToElement,
  46910. cubicToElement
  46911. };
  46912. /** Base class for the elements that make up a RelativePointPath.
  46913. */
  46914. class JUCE_API ElementBase
  46915. {
  46916. public:
  46917. ElementBase (ElementType type);
  46918. virtual ~ElementBase() {}
  46919. virtual const ValueTree createTree() const = 0;
  46920. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  46921. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  46922. virtual ElementBase* clone() const = 0;
  46923. bool isDynamic();
  46924. const ElementType type;
  46925. private:
  46926. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  46927. };
  46928. class JUCE_API StartSubPath : public ElementBase
  46929. {
  46930. public:
  46931. StartSubPath (const RelativePoint& pos);
  46932. const ValueTree createTree() const;
  46933. void addToPath (Path& path, Expression::Scope*) const;
  46934. RelativePoint* getControlPoints (int& numPoints);
  46935. ElementBase* clone() const;
  46936. RelativePoint startPos;
  46937. private:
  46938. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  46939. };
  46940. class JUCE_API CloseSubPath : public ElementBase
  46941. {
  46942. public:
  46943. CloseSubPath();
  46944. const ValueTree createTree() const;
  46945. void addToPath (Path& path, Expression::Scope*) const;
  46946. RelativePoint* getControlPoints (int& numPoints);
  46947. ElementBase* clone() const;
  46948. private:
  46949. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  46950. };
  46951. class JUCE_API LineTo : public ElementBase
  46952. {
  46953. public:
  46954. LineTo (const RelativePoint& endPoint);
  46955. const ValueTree createTree() const;
  46956. void addToPath (Path& path, Expression::Scope*) const;
  46957. RelativePoint* getControlPoints (int& numPoints);
  46958. ElementBase* clone() const;
  46959. RelativePoint endPoint;
  46960. private:
  46961. JUCE_DECLARE_NON_COPYABLE (LineTo);
  46962. };
  46963. class JUCE_API QuadraticTo : public ElementBase
  46964. {
  46965. public:
  46966. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  46967. const ValueTree createTree() const;
  46968. void addToPath (Path& path, Expression::Scope*) const;
  46969. RelativePoint* getControlPoints (int& numPoints);
  46970. ElementBase* clone() const;
  46971. RelativePoint controlPoints[2];
  46972. private:
  46973. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  46974. };
  46975. class JUCE_API CubicTo : public ElementBase
  46976. {
  46977. public:
  46978. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  46979. const ValueTree createTree() const;
  46980. void addToPath (Path& path, Expression::Scope*) const;
  46981. RelativePoint* getControlPoints (int& numPoints);
  46982. ElementBase* clone() const;
  46983. RelativePoint controlPoints[3];
  46984. private:
  46985. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  46986. };
  46987. void addElement (ElementBase* newElement);
  46988. OwnedArray <ElementBase> elements;
  46989. bool usesNonZeroWinding;
  46990. private:
  46991. class Positioner;
  46992. friend class Positioner;
  46993. bool containsDynamicPoints;
  46994. void applyTo (DrawablePath& path) const;
  46995. RelativePointPath& operator= (const RelativePointPath&);
  46996. JUCE_LEAK_DETECTOR (RelativePointPath);
  46997. };
  46998. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46999. /*** End of inlined file: juce_RelativePointPath.h ***/
  47000. #endif
  47001. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47002. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  47003. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47004. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47005. class Component;
  47006. /**
  47007. An rectangle stored as a set of RelativeCoordinate values.
  47008. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  47009. @see RelativeCoordinate, RelativePoint
  47010. */
  47011. class JUCE_API RelativeRectangle
  47012. {
  47013. public:
  47014. /** Creates a zero-size rectangle at the origin. */
  47015. RelativeRectangle();
  47016. /** Creates an absolute rectangle, relative to the origin. */
  47017. explicit RelativeRectangle (const Rectangle<float>& rect);
  47018. /** Creates a rectangle from four coordinates. */
  47019. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  47020. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  47021. /** Creates a rectangle from a stringified representation.
  47022. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  47023. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  47024. RelativeCoordinate class.
  47025. @see toString
  47026. */
  47027. explicit RelativeRectangle (const String& stringVersion);
  47028. bool operator== (const RelativeRectangle& other) const throw();
  47029. bool operator!= (const RelativeRectangle& other) const throw();
  47030. /** Calculates the absolute position of this rectangle.
  47031. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  47032. be needed to calculate the result.
  47033. */
  47034. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  47035. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  47036. Calling this will leave any anchor points unchanged, but will set any absolute
  47037. or relative positions to whatever values are necessary to make the resultant position
  47038. match the position that is provided.
  47039. */
  47040. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  47041. /** Returns true if this rectangle depends on any external symbols for its position.
  47042. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  47043. */
  47044. bool isDynamic() const;
  47045. /** Returns a string which represents this point.
  47046. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  47047. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  47048. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  47049. */
  47050. const String toString() const;
  47051. /** Renames a symbol if it is used by any of the coordinates.
  47052. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  47053. */
  47054. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  47055. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  47056. keep it positioned with this rectangle.
  47057. */
  47058. void applyToComponent (Component& component) const;
  47059. // The actual rectangle coords...
  47060. RelativeCoordinate left, right, top, bottom;
  47061. };
  47062. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  47063. /*** End of inlined file: juce_RelativeRectangle.h ***/
  47064. #endif
  47065. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47066. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  47067. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47068. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47069. /**
  47070. A PropertyComponent that contains an on/off toggle button.
  47071. This type of property component can be used if you have a boolean value to
  47072. toggle on/off.
  47073. @see PropertyComponent
  47074. */
  47075. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  47076. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47077. {
  47078. protected:
  47079. /** Creates a button component.
  47080. If you use this constructor, you must override the getState() and setState()
  47081. methods.
  47082. @param propertyName the property name to be passed to the PropertyComponent
  47083. @param buttonTextWhenTrue the text shown in the button when the value is true
  47084. @param buttonTextWhenFalse the text shown in the button when the value is false
  47085. */
  47086. BooleanPropertyComponent (const String& propertyName,
  47087. const String& buttonTextWhenTrue,
  47088. const String& buttonTextWhenFalse);
  47089. public:
  47090. /** Creates a button component.
  47091. @param valueToControl a Value object that this property should refer to.
  47092. @param propertyName the property name to be passed to the PropertyComponent
  47093. @param buttonText the text shown in the ToggleButton component
  47094. */
  47095. BooleanPropertyComponent (const Value& valueToControl,
  47096. const String& propertyName,
  47097. const String& buttonText);
  47098. /** Destructor. */
  47099. ~BooleanPropertyComponent();
  47100. /** Called to change the state of the boolean value. */
  47101. virtual void setState (bool newState);
  47102. /** Must return the current value of the property. */
  47103. virtual bool getState() const;
  47104. /** @internal */
  47105. void paint (Graphics& g);
  47106. /** @internal */
  47107. void refresh();
  47108. /** @internal */
  47109. void buttonClicked (Button*);
  47110. private:
  47111. ToggleButton button;
  47112. String onText, offText;
  47113. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  47114. };
  47115. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  47116. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  47117. #endif
  47118. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47119. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  47120. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47121. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47122. /**
  47123. A PropertyComponent that contains a button.
  47124. This type of property component can be used if you need a button to trigger some
  47125. kind of action.
  47126. @see PropertyComponent
  47127. */
  47128. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  47129. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47130. {
  47131. public:
  47132. /** Creates a button component.
  47133. @param propertyName the property name to be passed to the PropertyComponent
  47134. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  47135. */
  47136. ButtonPropertyComponent (const String& propertyName,
  47137. bool triggerOnMouseDown);
  47138. /** Destructor. */
  47139. ~ButtonPropertyComponent();
  47140. /** Called when the user clicks the button.
  47141. */
  47142. virtual void buttonClicked() = 0;
  47143. /** Returns the string that should be displayed in the button.
  47144. If you need to change this string, call refresh() to update the component.
  47145. */
  47146. virtual const String getButtonText() const = 0;
  47147. /** @internal */
  47148. void refresh();
  47149. /** @internal */
  47150. void buttonClicked (Button*);
  47151. private:
  47152. TextButton button;
  47153. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  47154. };
  47155. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  47156. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  47157. #endif
  47158. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47159. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  47160. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47161. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47162. /**
  47163. A PropertyComponent that shows its value as a combo box.
  47164. This type of property component contains a list of options and has a
  47165. combo box to choose one.
  47166. Your subclass's constructor must add some strings to the choices StringArray
  47167. and these are shown in the list.
  47168. The getIndex() method will be called to find out which option is the currently
  47169. selected one. If you call refresh() it will call getIndex() to check whether
  47170. the value has changed, and will update the combo box if needed.
  47171. If the user selects a different item from the list, setIndex() will be
  47172. called to let your class process this.
  47173. @see PropertyComponent, PropertyPanel
  47174. */
  47175. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  47176. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  47177. {
  47178. protected:
  47179. /** Creates the component.
  47180. Your subclass's constructor must add a list of options to the choices
  47181. member variable.
  47182. */
  47183. ChoicePropertyComponent (const String& propertyName);
  47184. public:
  47185. /** Creates the component.
  47186. @param valueToControl the value that the combo box will read and control
  47187. @param propertyName the name of the property
  47188. @param choices the list of possible values that the drop-down list will contain
  47189. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  47190. These are the values that will be read and written to the
  47191. valueToControl value. This array must contain the same number of items
  47192. as the choices array
  47193. */
  47194. ChoicePropertyComponent (const Value& valueToControl,
  47195. const String& propertyName,
  47196. const StringArray& choices,
  47197. const Array <var>& correspondingValues);
  47198. /** Destructor. */
  47199. ~ChoicePropertyComponent();
  47200. /** Called when the user selects an item from the combo box.
  47201. Your subclass must use this callback to update the value that this component
  47202. represents. The index is the index of the chosen item in the choices
  47203. StringArray.
  47204. */
  47205. virtual void setIndex (int newIndex);
  47206. /** Returns the index of the item that should currently be shown.
  47207. This is the index of the item in the choices StringArray that will be
  47208. shown.
  47209. */
  47210. virtual int getIndex() const;
  47211. /** Returns the list of options. */
  47212. const StringArray& getChoices() const;
  47213. /** @internal */
  47214. void refresh();
  47215. /** @internal */
  47216. void comboBoxChanged (ComboBox*);
  47217. protected:
  47218. /** The list of options that will be shown in the combo box.
  47219. Your subclass must populate this array in its constructor. If any empty
  47220. strings are added, these will be replaced with horizontal separators (see
  47221. ComboBox::addSeparator() for more info).
  47222. */
  47223. StringArray choices;
  47224. private:
  47225. ComboBox comboBox;
  47226. bool isCustomClass;
  47227. class RemapperValueSource;
  47228. void createComboBox();
  47229. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  47230. };
  47231. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  47232. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  47233. #endif
  47234. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  47235. #endif
  47236. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  47237. #endif
  47238. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47239. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  47240. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47241. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47242. /**
  47243. A PropertyComponent that shows its value as a slider.
  47244. @see PropertyComponent, Slider
  47245. */
  47246. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  47247. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  47248. {
  47249. protected:
  47250. /** Creates the property component.
  47251. The ranges, interval and skew factor are passed to the Slider component.
  47252. If you need to customise the slider in other ways, your constructor can
  47253. access the slider member variable and change it directly.
  47254. */
  47255. SliderPropertyComponent (const String& propertyName,
  47256. double rangeMin,
  47257. double rangeMax,
  47258. double interval,
  47259. double skewFactor = 1.0);
  47260. public:
  47261. /** Creates the property component.
  47262. The ranges, interval and skew factor are passed to the Slider component.
  47263. If you need to customise the slider in other ways, your constructor can
  47264. access the slider member variable and change it directly.
  47265. */
  47266. SliderPropertyComponent (const Value& valueToControl,
  47267. const String& propertyName,
  47268. double rangeMin,
  47269. double rangeMax,
  47270. double interval,
  47271. double skewFactor = 1.0);
  47272. /** Destructor. */
  47273. ~SliderPropertyComponent();
  47274. /** Called when the user moves the slider to change its value.
  47275. Your subclass must use this method to update whatever item this property
  47276. represents.
  47277. */
  47278. virtual void setValue (double newValue);
  47279. /** Returns the value that the slider should show. */
  47280. virtual double getValue() const;
  47281. /** @internal */
  47282. void refresh();
  47283. /** @internal */
  47284. void sliderValueChanged (Slider*);
  47285. protected:
  47286. /** The slider component being used in this component.
  47287. Your subclass has access to this in case it needs to customise it in some way.
  47288. */
  47289. Slider slider;
  47290. private:
  47291. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  47292. };
  47293. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  47294. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  47295. #endif
  47296. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47297. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  47298. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47299. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47300. /**
  47301. A PropertyComponent that shows its value as editable text.
  47302. @see PropertyComponent
  47303. */
  47304. class JUCE_API TextPropertyComponent : public PropertyComponent
  47305. {
  47306. protected:
  47307. /** Creates a text property component.
  47308. The maxNumChars is used to set the length of string allowable, and isMultiLine
  47309. sets whether the text editor allows carriage returns.
  47310. @see TextEditor
  47311. */
  47312. TextPropertyComponent (const String& propertyName,
  47313. int maxNumChars,
  47314. bool isMultiLine);
  47315. public:
  47316. /** Creates a text property component.
  47317. The maxNumChars is used to set the length of string allowable, and isMultiLine
  47318. sets whether the text editor allows carriage returns.
  47319. @see TextEditor
  47320. */
  47321. TextPropertyComponent (const Value& valueToControl,
  47322. const String& propertyName,
  47323. int maxNumChars,
  47324. bool isMultiLine);
  47325. /** Destructor. */
  47326. ~TextPropertyComponent();
  47327. /** Called when the user edits the text.
  47328. Your subclass must use this callback to change the value of whatever item
  47329. this property component represents.
  47330. */
  47331. virtual void setText (const String& newText);
  47332. /** Returns the text that should be shown in the text editor.
  47333. */
  47334. virtual const String getText() const;
  47335. /** @internal */
  47336. void refresh();
  47337. /** @internal */
  47338. void textWasEdited();
  47339. private:
  47340. ScopedPointer<Label> textEditor;
  47341. void createEditor (int maxNumChars, bool isMultiLine);
  47342. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  47343. };
  47344. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  47345. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  47346. #endif
  47347. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47348. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  47349. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47350. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47351. #if JUCE_WINDOWS || DOXYGEN
  47352. /**
  47353. A Windows-specific class that can create and embed an ActiveX control inside
  47354. itself.
  47355. To use it, create one of these, put it in place and make sure it's visible in a
  47356. window, then use createControl() to instantiate an ActiveX control. The control
  47357. will then be moved and resized to follow the movements of this component.
  47358. Of course, since the control is a heavyweight window, it'll obliterate any
  47359. juce components that may overlap this component, but that's life.
  47360. */
  47361. class JUCE_API ActiveXControlComponent : public Component
  47362. {
  47363. public:
  47364. /** Create an initially-empty container. */
  47365. ActiveXControlComponent();
  47366. /** Destructor. */
  47367. ~ActiveXControlComponent();
  47368. /** Tries to create an ActiveX control and embed it in this peer.
  47369. The peer controlIID is a pointer to an IID structure - it's treated
  47370. as a void* because when including the Juce headers, you might not always
  47371. have included windows.h first, in which case IID wouldn't be defined.
  47372. e.g. @code
  47373. const IID myIID = __uuidof (QTControl);
  47374. myControlComp->createControl (&myIID);
  47375. @endcode
  47376. */
  47377. bool createControl (const void* controlIID);
  47378. /** Deletes the ActiveX control, if one has been created.
  47379. */
  47380. void deleteControl();
  47381. /** Returns true if a control is currently in use. */
  47382. bool isControlOpen() const throw() { return control != 0; }
  47383. /** Does a QueryInterface call on the embedded control object.
  47384. This allows you to cast the control to whatever type of COM object you need.
  47385. The iid parameter is a pointer to an IID structure - it's treated
  47386. as a void* because when including the Juce headers, you might not always
  47387. have included windows.h first, in which case IID wouldn't be defined, but
  47388. you should just pass a pointer to an IID.
  47389. e.g. @code
  47390. const IID iid = __uuidof (IOleWindow);
  47391. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  47392. if (oleWindow != 0)
  47393. {
  47394. HWND hwnd;
  47395. oleWindow->GetWindow (&hwnd);
  47396. ...
  47397. oleWindow->Release();
  47398. }
  47399. @endcode
  47400. */
  47401. void* queryInterface (const void* iid) const;
  47402. /** Set this to false to stop mouse events being allowed through to the control.
  47403. */
  47404. void setMouseEventsAllowed (bool eventsCanReachControl);
  47405. /** Returns true if mouse events are allowed to get through to the control.
  47406. */
  47407. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  47408. /** @internal */
  47409. void paint (Graphics& g);
  47410. /** @internal */
  47411. void* originalWndProc;
  47412. private:
  47413. class Pimpl;
  47414. friend class Pimpl;
  47415. friend class ScopedPointer <Pimpl>;
  47416. ScopedPointer <Pimpl> control;
  47417. bool mouseEventsAllowed;
  47418. void setControlBounds (const Rectangle<int>& bounds) const;
  47419. void setControlVisible (bool b) const;
  47420. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  47421. };
  47422. #endif
  47423. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  47424. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  47425. #endif
  47426. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47427. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  47428. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47429. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47430. /**
  47431. A component containing controls to let the user change the audio settings of
  47432. an AudioDeviceManager object.
  47433. Very easy to use - just create one of these and show it to the user.
  47434. @see AudioDeviceManager
  47435. */
  47436. class JUCE_API AudioDeviceSelectorComponent : public Component,
  47437. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  47438. public ButtonListener,
  47439. public ChangeListener
  47440. {
  47441. public:
  47442. /** Creates the component.
  47443. If your app needs only output channels, you might ask for a maximum of 0 input
  47444. channels, and the component won't display any options for choosing the input
  47445. channels. And likewise if you're doing an input-only app.
  47446. @param deviceManager the device manager that this component should control
  47447. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  47448. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  47449. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  47450. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  47451. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  47452. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  47453. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  47454. treated as a set of separate mono channels.
  47455. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  47456. are shown, with an "advanced" button that shows the rest of them
  47457. */
  47458. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  47459. const int minAudioInputChannels,
  47460. const int maxAudioInputChannels,
  47461. const int minAudioOutputChannels,
  47462. const int maxAudioOutputChannels,
  47463. const bool showMidiInputOptions,
  47464. const bool showMidiOutputSelector,
  47465. const bool showChannelsAsStereoPairs,
  47466. const bool hideAdvancedOptionsWithButton);
  47467. /** Destructor */
  47468. ~AudioDeviceSelectorComponent();
  47469. /** @internal */
  47470. void resized();
  47471. /** @internal */
  47472. void comboBoxChanged (ComboBox*);
  47473. /** @internal */
  47474. void buttonClicked (Button*);
  47475. /** @internal */
  47476. void changeListenerCallback (ChangeBroadcaster*);
  47477. /** @internal */
  47478. void childBoundsChanged (Component*);
  47479. private:
  47480. AudioDeviceManager& deviceManager;
  47481. ScopedPointer<ComboBox> deviceTypeDropDown;
  47482. ScopedPointer<Label> deviceTypeDropDownLabel;
  47483. ScopedPointer<Component> audioDeviceSettingsComp;
  47484. String audioDeviceSettingsCompType;
  47485. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  47486. const bool showChannelsAsStereoPairs;
  47487. const bool hideAdvancedOptionsWithButton;
  47488. class MidiInputSelectorComponentListBox;
  47489. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  47490. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  47491. ScopedPointer<ComboBox> midiOutputSelector;
  47492. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  47493. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  47494. };
  47495. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  47496. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  47497. #endif
  47498. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47499. /*** Start of inlined file: juce_BubbleComponent.h ***/
  47500. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47501. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47502. /**
  47503. A component for showing a message or other graphics inside a speech-bubble-shaped
  47504. outline, pointing at a location on the screen.
  47505. This is a base class that just draws and positions the bubble shape, but leaves
  47506. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  47507. that draws a text message.
  47508. To use it, create your subclass, then either add it to a parent component or
  47509. put it on the desktop with addToDesktop (0), use setPosition() to
  47510. resize and position it, then make it visible.
  47511. @see BubbleMessageComponent
  47512. */
  47513. class JUCE_API BubbleComponent : public Component
  47514. {
  47515. protected:
  47516. /** Creates a BubbleComponent.
  47517. Your subclass will need to implement the getContentSize() and paintContent()
  47518. methods to draw the bubble's contents.
  47519. */
  47520. BubbleComponent();
  47521. public:
  47522. /** Destructor. */
  47523. ~BubbleComponent();
  47524. /** A list of permitted placements for the bubble, relative to the co-ordinates
  47525. at which it should be pointing.
  47526. @see setAllowedPlacement
  47527. */
  47528. enum BubblePlacement
  47529. {
  47530. above = 1,
  47531. below = 2,
  47532. left = 4,
  47533. right = 8
  47534. };
  47535. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  47536. point at which it's pointing.
  47537. By default when setPosition() is called, the bubble will place itself either
  47538. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  47539. the values in BubblePlacement to restrict this choice.
  47540. E.g. if you only want your bubble to appear above or below the target area,
  47541. use setAllowedPlacement (above | below);
  47542. @see BubblePlacement
  47543. */
  47544. void setAllowedPlacement (int newPlacement);
  47545. /** Moves and resizes the bubble to point at a given component.
  47546. This will resize the bubble to fit its content, then find a position for it
  47547. so that it's next to, but doesn't overlap the given component.
  47548. It'll put itself either above, below, or to the side of the component depending
  47549. on where there's the most space, honouring any restrictions that were set
  47550. with setAllowedPlacement().
  47551. */
  47552. void setPosition (Component* componentToPointTo);
  47553. /** Moves and resizes the bubble to point at a given point.
  47554. This will resize the bubble to fit its content, then position it
  47555. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  47556. are relative to either the bubble component's parent component if it has one, or
  47557. they are screen co-ordinates if not.
  47558. It'll put itself either above, below, or to the side of this point, depending
  47559. on where there's the most space, honouring any restrictions that were set
  47560. with setAllowedPlacement().
  47561. */
  47562. void setPosition (int arrowTipX,
  47563. int arrowTipY);
  47564. /** Moves and resizes the bubble to point at a given rectangle.
  47565. This will resize the bubble to fit its content, then find a position for it
  47566. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  47567. co-ordinates are relative to either the bubble component's parent component
  47568. if it has one, or they are screen co-ordinates if not.
  47569. It'll put itself either above, below, or to the side of the component depending
  47570. on where there's the most space, honouring any restrictions that were set
  47571. with setAllowedPlacement().
  47572. */
  47573. void setPosition (const Rectangle<int>& rectangleToPointTo);
  47574. protected:
  47575. /** Subclasses should override this to return the size of the content they
  47576. want to draw inside the bubble.
  47577. */
  47578. virtual void getContentSize (int& width, int& height) = 0;
  47579. /** Subclasses should override this to draw their bubble's contents.
  47580. The graphics object's clip region and the dimensions passed in here are
  47581. set up to paint just the rectangle inside the bubble.
  47582. */
  47583. virtual void paintContent (Graphics& g, int width, int height) = 0;
  47584. public:
  47585. /** @internal */
  47586. void paint (Graphics& g);
  47587. private:
  47588. Rectangle<int> content;
  47589. int side, allowablePlacements;
  47590. float arrowTipX, arrowTipY;
  47591. DropShadowEffect shadow;
  47592. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  47593. };
  47594. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47595. /*** End of inlined file: juce_BubbleComponent.h ***/
  47596. #endif
  47597. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47598. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  47599. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47600. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47601. /**
  47602. A speech-bubble component that displays a short message.
  47603. This can be used to show a message with the tail of the speech bubble
  47604. pointing to a particular component or location on the screen.
  47605. @see BubbleComponent
  47606. */
  47607. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  47608. private Timer
  47609. {
  47610. public:
  47611. /** Creates a bubble component.
  47612. After creating one a BubbleComponent, do the following:
  47613. - add it to an appropriate parent component, or put it on the
  47614. desktop with Component::addToDesktop (0).
  47615. - use the showAt() method to show a message.
  47616. - it will make itself invisible after it times-out (and can optionally
  47617. also delete itself), or you can reuse it somewhere else by calling
  47618. showAt() again.
  47619. */
  47620. BubbleMessageComponent (int fadeOutLengthMs = 150);
  47621. /** Destructor. */
  47622. ~BubbleMessageComponent();
  47623. /** Shows a message bubble at a particular position.
  47624. This shows the bubble with its stem pointing to the given location
  47625. (co-ordinates being relative to its parent component).
  47626. For details about exactly how it decides where to position itself, see
  47627. BubbleComponent::updatePosition().
  47628. @param x the x co-ordinate of end of the bubble's tail
  47629. @param y the y co-ordinate of end of the bubble's tail
  47630. @param message the text to display
  47631. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47632. from its parent compnent. If this is 0 or less, it
  47633. will stay there until manually removed.
  47634. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47635. mouse button is pressed (anywhere on the screen)
  47636. @param deleteSelfAfterUse if true, then the component will delete itself after
  47637. it becomes invisible
  47638. */
  47639. void showAt (int x, int y,
  47640. const String& message,
  47641. int numMillisecondsBeforeRemoving,
  47642. bool removeWhenMouseClicked = true,
  47643. bool deleteSelfAfterUse = false);
  47644. /** Shows a message bubble next to a particular component.
  47645. This shows the bubble with its stem pointing at the given component.
  47646. For details about exactly how it decides where to position itself, see
  47647. BubbleComponent::updatePosition().
  47648. @param component the component that you want to point at
  47649. @param message the text to display
  47650. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47651. from its parent compnent. If this is 0 or less, it
  47652. will stay there until manually removed.
  47653. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47654. mouse button is pressed (anywhere on the screen)
  47655. @param deleteSelfAfterUse if true, then the component will delete itself after
  47656. it becomes invisible
  47657. */
  47658. void showAt (Component* component,
  47659. const String& message,
  47660. int numMillisecondsBeforeRemoving,
  47661. bool removeWhenMouseClicked = true,
  47662. bool deleteSelfAfterUse = false);
  47663. /** @internal */
  47664. void getContentSize (int& w, int& h);
  47665. /** @internal */
  47666. void paintContent (Graphics& g, int w, int h);
  47667. /** @internal */
  47668. void timerCallback();
  47669. private:
  47670. int fadeOutLength, mouseClickCounter;
  47671. TextLayout textLayout;
  47672. int64 expiryTime;
  47673. bool deleteAfterUse;
  47674. void init (int numMillisecondsBeforeRemoving,
  47675. bool removeWhenMouseClicked,
  47676. bool deleteSelfAfterUse);
  47677. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  47678. };
  47679. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47680. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  47681. #endif
  47682. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47683. /*** Start of inlined file: juce_ColourSelector.h ***/
  47684. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47685. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  47686. /**
  47687. A component that lets the user choose a colour.
  47688. This shows RGB sliders and a colourspace that the user can pick colours from.
  47689. This class is also a ChangeBroadcaster, so listeners can register to be told
  47690. when the colour changes.
  47691. */
  47692. class JUCE_API ColourSelector : public Component,
  47693. public ChangeBroadcaster,
  47694. protected SliderListener
  47695. {
  47696. public:
  47697. /** Options for the type of selector to show. These are passed into the constructor. */
  47698. enum ColourSelectorOptions
  47699. {
  47700. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  47701. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  47702. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  47703. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  47704. };
  47705. /** Creates a ColourSelector object.
  47706. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  47707. which of the selector's features should be visible.
  47708. The edgeGap value specifies the amount of space to leave around the edge.
  47709. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  47710. colourspace and hue selector components.
  47711. */
  47712. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  47713. int edgeGap = 4,
  47714. int gapAroundColourSpaceComponent = 7);
  47715. /** Destructor. */
  47716. ~ColourSelector();
  47717. /** Returns the colour that the user has currently selected.
  47718. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  47719. register to be told when the colour changes.
  47720. @see setCurrentColour
  47721. */
  47722. const Colour getCurrentColour() const;
  47723. /** Changes the colour that is currently being shown.
  47724. */
  47725. void setCurrentColour (const Colour& newColour);
  47726. /** Tells the selector how many preset colour swatches you want to have on the component.
  47727. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47728. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47729. their values.
  47730. */
  47731. virtual int getNumSwatches() const;
  47732. /** Called by the selector to find out the colour of one of the swatches.
  47733. Your subclass should return the colour of the swatch with the given index.
  47734. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47735. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47736. their values.
  47737. */
  47738. virtual const Colour getSwatchColour (int index) const;
  47739. /** Called by the selector when the user puts a new colour into one of the swatches.
  47740. Your subclass should change the colour of the swatch with the given index.
  47741. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47742. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47743. their values.
  47744. */
  47745. virtual void setSwatchColour (int index, const Colour& newColour) const;
  47746. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  47747. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47748. methods.
  47749. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47750. */
  47751. enum ColourIds
  47752. {
  47753. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  47754. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  47755. };
  47756. private:
  47757. class ColourSpaceView;
  47758. class HueSelectorComp;
  47759. class SwatchComponent;
  47760. friend class ColourSpaceView;
  47761. friend class ScopedPointer<ColourSpaceView>;
  47762. friend class HueSelectorComp;
  47763. friend class ScopedPointer<HueSelectorComp>;
  47764. Colour colour;
  47765. float h, s, v;
  47766. ScopedPointer<Slider> sliders[4];
  47767. ScopedPointer<ColourSpaceView> colourSpace;
  47768. ScopedPointer<HueSelectorComp> hueSelector;
  47769. OwnedArray <SwatchComponent> swatchComponents;
  47770. const int flags;
  47771. int edgeGap;
  47772. Rectangle<int> previewArea;
  47773. void setHue (float newH);
  47774. void setSV (float newS, float newV);
  47775. void updateHSV();
  47776. void update();
  47777. void sliderValueChanged (Slider*);
  47778. void paint (Graphics& g);
  47779. void resized();
  47780. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  47781. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  47782. // This constructor is here temporarily to prevent old code compiling, because the parameters
  47783. // have changed - if you get an error here, update your code to use the new constructor instead..
  47784. ColourSelector (bool);
  47785. #endif
  47786. };
  47787. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  47788. /*** End of inlined file: juce_ColourSelector.h ***/
  47789. #endif
  47790. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  47791. #endif
  47792. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47793. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  47794. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47795. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47796. /**
  47797. A component that displays a piano keyboard, whose notes can be clicked on.
  47798. This component will mimic a physical midi keyboard, showing the current state of
  47799. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  47800. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  47801. Another feature is that the computer keyboard can also be used to play notes. By
  47802. default it maps the top two rows of a standard querty keyboard to the notes, but
  47803. these can be remapped if needed. It will only respond to keypresses when it has
  47804. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  47805. The component is also a ChangeBroadcaster, so if you want to be informed when the
  47806. keyboard is scrolled, you can register a ChangeListener for callbacks.
  47807. @see MidiKeyboardState
  47808. */
  47809. class JUCE_API MidiKeyboardComponent : public Component,
  47810. public MidiKeyboardStateListener,
  47811. public ChangeBroadcaster,
  47812. private Timer,
  47813. private AsyncUpdater
  47814. {
  47815. public:
  47816. /** The direction of the keyboard.
  47817. @see setOrientation
  47818. */
  47819. enum Orientation
  47820. {
  47821. horizontalKeyboard,
  47822. verticalKeyboardFacingLeft,
  47823. verticalKeyboardFacingRight,
  47824. };
  47825. /** Creates a MidiKeyboardComponent.
  47826. @param state the midi keyboard model that this component will represent
  47827. @param orientation whether the keyboard is horizonal or vertical
  47828. */
  47829. MidiKeyboardComponent (MidiKeyboardState& state,
  47830. Orientation orientation);
  47831. /** Destructor. */
  47832. ~MidiKeyboardComponent();
  47833. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  47834. on the component.
  47835. Values are 0 to 1.0, where 1.0 is the heaviest.
  47836. @see setMidiChannel
  47837. */
  47838. void setVelocity (float velocity, bool useMousePositionForVelocity);
  47839. /** Changes the midi channel number that will be used for events triggered by clicking
  47840. on the component.
  47841. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  47842. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  47843. Although this is the channel used for outgoing events, the component can display
  47844. incoming events from more than one channel - see setMidiChannelsToDisplay()
  47845. @see setVelocity
  47846. */
  47847. void setMidiChannel (int midiChannelNumber);
  47848. /** Returns the midi channel that the keyboard is using for midi messages.
  47849. @see setMidiChannel
  47850. */
  47851. int getMidiChannel() const throw() { return midiChannel; }
  47852. /** Sets a mask to indicate which incoming midi channels should be represented by
  47853. key movements.
  47854. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  47855. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  47856. in this mask, the on-screen keys will also go down.
  47857. By default, this mask is set to 0xffff (all channels displayed).
  47858. @see setMidiChannel
  47859. */
  47860. void setMidiChannelsToDisplay (int midiChannelMask);
  47861. /** Returns the current set of midi channels represented by the component.
  47862. This is the value that was set with setMidiChannelsToDisplay().
  47863. */
  47864. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  47865. /** Changes the width used to draw the white keys. */
  47866. void setKeyWidth (float widthInPixels);
  47867. /** Returns the width that was set by setKeyWidth(). */
  47868. float getKeyWidth() const throw() { return keyWidth; }
  47869. /** Changes the keyboard's current direction. */
  47870. void setOrientation (Orientation newOrientation);
  47871. /** Returns the keyboard's current direction. */
  47872. const Orientation getOrientation() const throw() { return orientation; }
  47873. /** Sets the range of midi notes that the keyboard will be limited to.
  47874. By default the range is 0 to 127 (inclusive), but you can limit this if you
  47875. only want a restricted set of the keys to be shown.
  47876. Note that the values here are inclusive and must be between 0 and 127.
  47877. */
  47878. void setAvailableRange (int lowestNote,
  47879. int highestNote);
  47880. /** Returns the first note in the available range.
  47881. @see setAvailableRange
  47882. */
  47883. int getRangeStart() const throw() { return rangeStart; }
  47884. /** Returns the last note in the available range.
  47885. @see setAvailableRange
  47886. */
  47887. int getRangeEnd() const throw() { return rangeEnd; }
  47888. /** If the keyboard extends beyond the size of the component, this will scroll
  47889. it to show the given key at the start.
  47890. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  47891. base class to send a callback to any ChangeListeners that have been registered.
  47892. */
  47893. void setLowestVisibleKey (int noteNumber);
  47894. /** Returns the number of the first key shown in the component.
  47895. @see setLowestVisibleKey
  47896. */
  47897. int getLowestVisibleKey() const throw() { return firstKey; }
  47898. /** Returns the length of the black notes.
  47899. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  47900. */
  47901. int getBlackNoteLength() const throw() { return blackNoteLength; }
  47902. /** If set to true, then scroll buttons will appear at either end of the keyboard
  47903. if there are too many notes to fit them all in the component at once.
  47904. */
  47905. void setScrollButtonsVisible (bool canScroll);
  47906. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  47907. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47908. methods.
  47909. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47910. */
  47911. enum ColourIds
  47912. {
  47913. whiteNoteColourId = 0x1005000,
  47914. blackNoteColourId = 0x1005001,
  47915. keySeparatorLineColourId = 0x1005002,
  47916. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  47917. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  47918. textLabelColourId = 0x1005005,
  47919. upDownButtonBackgroundColourId = 0x1005006,
  47920. upDownButtonArrowColourId = 0x1005007
  47921. };
  47922. /** Returns the position within the component of the left-hand edge of a key.
  47923. Depending on the keyboard's orientation, this may be a horizontal or vertical
  47924. distance, in either direction.
  47925. */
  47926. int getKeyStartPosition (const int midiNoteNumber) const;
  47927. /** Deletes all key-mappings.
  47928. @see setKeyPressForNote
  47929. */
  47930. void clearKeyMappings();
  47931. /** Maps a key-press to a given note.
  47932. @param key the key that should trigger the note
  47933. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  47934. be. The actual midi note that gets played will be
  47935. this value + (12 * the current base octave). To change
  47936. the base octave, see setKeyPressBaseOctave()
  47937. */
  47938. void setKeyPressForNote (const KeyPress& key,
  47939. int midiNoteOffsetFromC);
  47940. /** Removes any key-mappings for a given note.
  47941. For a description of what the note number means, see setKeyPressForNote().
  47942. */
  47943. void removeKeyPressForNote (int midiNoteOffsetFromC);
  47944. /** Changes the base note above which key-press-triggered notes are played.
  47945. The set of key-mappings that trigger notes can be moved up and down to cover
  47946. the entire scale using this method.
  47947. The value passed in is an octave number between 0 and 10 (inclusive), and
  47948. indicates which C is the base note to which the key-mapped notes are
  47949. relative.
  47950. */
  47951. void setKeyPressBaseOctave (int newOctaveNumber);
  47952. /** This sets the octave number which is shown as the octave number for middle C.
  47953. This affects only the default implementation of getWhiteNoteText(), which
  47954. passes this octave number to MidiMessage::getMidiNoteName() in order to
  47955. get the note text. See MidiMessage::getMidiNoteName() for more info about
  47956. the parameter.
  47957. By default this value is set to 3.
  47958. @see getOctaveForMiddleC
  47959. */
  47960. void setOctaveForMiddleC (int octaveNumForMiddleC);
  47961. /** This returns the value set by setOctaveForMiddleC().
  47962. @see setOctaveForMiddleC
  47963. */
  47964. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  47965. /** @internal */
  47966. void paint (Graphics& g);
  47967. /** @internal */
  47968. void resized();
  47969. /** @internal */
  47970. void mouseMove (const MouseEvent& e);
  47971. /** @internal */
  47972. void mouseDrag (const MouseEvent& e);
  47973. /** @internal */
  47974. void mouseDown (const MouseEvent& e);
  47975. /** @internal */
  47976. void mouseUp (const MouseEvent& e);
  47977. /** @internal */
  47978. void mouseEnter (const MouseEvent& e);
  47979. /** @internal */
  47980. void mouseExit (const MouseEvent& e);
  47981. /** @internal */
  47982. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  47983. /** @internal */
  47984. void timerCallback();
  47985. /** @internal */
  47986. bool keyStateChanged (bool isKeyDown);
  47987. /** @internal */
  47988. void focusLost (FocusChangeType cause);
  47989. /** @internal */
  47990. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  47991. /** @internal */
  47992. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  47993. /** @internal */
  47994. void handleAsyncUpdate();
  47995. /** @internal */
  47996. void colourChanged();
  47997. protected:
  47998. /** Draws a white note in the given rectangle.
  47999. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48000. currently pressed down.
  48001. When doing this, be sure to note the keyboard's orientation.
  48002. */
  48003. virtual void drawWhiteNote (int midiNoteNumber,
  48004. Graphics& g,
  48005. int x, int y, int w, int h,
  48006. bool isDown, bool isOver,
  48007. const Colour& lineColour,
  48008. const Colour& textColour);
  48009. /** Draws a black note in the given rectangle.
  48010. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  48011. currently pressed down.
  48012. When doing this, be sure to note the keyboard's orientation.
  48013. */
  48014. virtual void drawBlackNote (int midiNoteNumber,
  48015. Graphics& g,
  48016. int x, int y, int w, int h,
  48017. bool isDown, bool isOver,
  48018. const Colour& noteFillColour);
  48019. /** Allows text to be drawn on the white notes.
  48020. By default this is used to label the C in each octave, but could be used for other things.
  48021. @see setOctaveForMiddleC
  48022. */
  48023. virtual const String getWhiteNoteText (const int midiNoteNumber);
  48024. /** Draws the up and down buttons that change the base note. */
  48025. virtual void drawUpDownButton (Graphics& g, int w, int h,
  48026. const bool isMouseOver,
  48027. const bool isButtonPressed,
  48028. const bool movesOctavesUp);
  48029. /** Callback when the mouse is clicked on a key.
  48030. You could use this to do things like handle right-clicks on keys, etc.
  48031. Return true if you want the click to trigger the note, or false if you
  48032. want to handle it yourself and not have the note played.
  48033. @see mouseDraggedToKey
  48034. */
  48035. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  48036. /** Callback when the mouse is dragged from one key onto another.
  48037. @see mouseDownOnKey
  48038. */
  48039. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  48040. /** Calculates the positon of a given midi-note.
  48041. This can be overridden to create layouts with custom key-widths.
  48042. @param midiNoteNumber the note to find
  48043. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  48044. @param x the x position of the left-hand edge of the key (this method
  48045. always works in terms of a horizontal keyboard)
  48046. @param w the width of the key
  48047. */
  48048. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  48049. int& x, int& w) const;
  48050. private:
  48051. friend class MidiKeyboardUpDownButton;
  48052. MidiKeyboardState& state;
  48053. int xOffset, blackNoteLength;
  48054. float keyWidth;
  48055. Orientation orientation;
  48056. int midiChannel, midiInChannelMask;
  48057. float velocity;
  48058. int noteUnderMouse, mouseDownNote;
  48059. BigInteger keysPressed, keysCurrentlyDrawnDown;
  48060. int rangeStart, rangeEnd, firstKey;
  48061. bool canScroll, mouseDragging, useMousePositionForVelocity;
  48062. ScopedPointer<Button> scrollDown, scrollUp;
  48063. Array <KeyPress> keyPresses;
  48064. Array <int> keyPressNotes;
  48065. int keyMappingOctave;
  48066. int octaveNumForMiddleC;
  48067. static const uint8 whiteNotes[];
  48068. static const uint8 blackNotes[];
  48069. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  48070. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  48071. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  48072. void resetAnyKeysInUse();
  48073. void updateNoteUnderMouse (const Point<int>& pos);
  48074. void repaintNote (const int midiNoteNumber);
  48075. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  48076. };
  48077. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  48078. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  48079. #endif
  48080. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48081. /*** Start of inlined file: juce_NSViewComponent.h ***/
  48082. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48083. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48084. #if ! DOXYGEN
  48085. class NSViewComponentInternal;
  48086. #endif
  48087. #if JUCE_MAC || DOXYGEN
  48088. /**
  48089. A Mac-specific class that can create and embed an NSView inside itself.
  48090. To use it, create one of these, put it in place and make sure it's visible in a
  48091. window, then use setView() to assign an NSView to it. The view will then be
  48092. moved and resized to follow the movements of this component.
  48093. Of course, since the view is a native object, it'll obliterate any
  48094. juce components that may overlap this component, but that's life.
  48095. */
  48096. class JUCE_API NSViewComponent : public Component
  48097. {
  48098. public:
  48099. /** Create an initially-empty container. */
  48100. NSViewComponent();
  48101. /** Destructor. */
  48102. ~NSViewComponent();
  48103. /** Assigns an NSView to this peer.
  48104. The view will be retained and released by this component for as long as
  48105. it is needed. To remove the current view, just call setView (0).
  48106. Note: a void* is used here to avoid including the cocoa headers as
  48107. part of the juce.h, but the method expects an NSView*.
  48108. */
  48109. void setView (void* nsView);
  48110. /** Returns the current NSView.
  48111. Note: a void* is returned here to avoid including the cocoa headers as
  48112. a requirement of juce.h, so you should just cast the object to an NSView*.
  48113. */
  48114. void* getView() const;
  48115. /** Resizes this component to fit the view that it contains. */
  48116. void resizeToFitView();
  48117. /** @internal */
  48118. void paint (Graphics& g);
  48119. private:
  48120. friend class NSViewComponentInternal;
  48121. ScopedPointer <NSViewComponentInternal> info;
  48122. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  48123. };
  48124. #endif
  48125. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  48126. /*** End of inlined file: juce_NSViewComponent.h ***/
  48127. #endif
  48128. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48129. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  48130. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48131. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48132. // this is used to disable OpenGL, and is defined in juce_Config.h
  48133. #if JUCE_OPENGL || DOXYGEN
  48134. /**
  48135. Represents the various properties of an OpenGL bitmap format.
  48136. @see OpenGLComponent::setPixelFormat
  48137. */
  48138. class JUCE_API OpenGLPixelFormat
  48139. {
  48140. public:
  48141. /** Creates an OpenGLPixelFormat.
  48142. The default constructor just initialises the object as a simple 8-bit
  48143. RGBA format.
  48144. */
  48145. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  48146. int alphaBits = 8,
  48147. int depthBufferBits = 16,
  48148. int stencilBufferBits = 0);
  48149. OpenGLPixelFormat (const OpenGLPixelFormat&);
  48150. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  48151. bool operator== (const OpenGLPixelFormat&) const;
  48152. int redBits; /**< The number of bits per pixel to use for the red channel. */
  48153. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  48154. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  48155. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  48156. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  48157. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  48158. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  48159. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  48160. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  48161. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  48162. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  48163. /** Returns a list of all the pixel formats that can be used in this system.
  48164. A reference component is needed in case there are multiple screens with different
  48165. capabilities - in which case, the one that the component is on will be used.
  48166. */
  48167. static void getAvailablePixelFormats (Component* component,
  48168. OwnedArray <OpenGLPixelFormat>& results);
  48169. private:
  48170. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  48171. };
  48172. /**
  48173. A base class for types of OpenGL context.
  48174. An OpenGLComponent will supply its own context for drawing in its window.
  48175. */
  48176. class JUCE_API OpenGLContext
  48177. {
  48178. public:
  48179. /** Destructor. */
  48180. virtual ~OpenGLContext();
  48181. /** Makes this context the currently active one. */
  48182. virtual bool makeActive() const throw() = 0;
  48183. /** If this context is currently active, it is disactivated. */
  48184. virtual bool makeInactive() const throw() = 0;
  48185. /** Returns true if this context is currently active. */
  48186. virtual bool isActive() const throw() = 0;
  48187. /** Swaps the buffers (if the context can do this). */
  48188. virtual void swapBuffers() = 0;
  48189. /** Sets whether the context checks the vertical sync before swapping.
  48190. The value is the number of frames to allow between buffer-swapping. This is
  48191. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  48192. and greater numbers indicate that it should swap less often.
  48193. Returns true if it sets the value successfully.
  48194. */
  48195. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  48196. /** Returns the current swap-sync interval.
  48197. See setSwapInterval() for info about the value returned.
  48198. */
  48199. virtual int getSwapInterval() const = 0;
  48200. /** Returns the pixel format being used by this context. */
  48201. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  48202. /** For windowed contexts, this moves the context within the bounds of
  48203. its parent window.
  48204. */
  48205. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  48206. /** For windowed contexts, this triggers a repaint of the window.
  48207. (Not relevent on all platforms).
  48208. */
  48209. virtual void repaint() = 0;
  48210. /** Returns an OS-dependent handle to the raw GL context.
  48211. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  48212. a GLXContext.
  48213. */
  48214. virtual void* getRawContext() const throw() = 0;
  48215. /** Deletes the context.
  48216. This must only be called on the message thread, or will deadlock.
  48217. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  48218. to call any other OpenGL function afterwards.
  48219. This doesn't touch other resources, such as window handles, etc.
  48220. You'll probably never have to call this method directly.
  48221. */
  48222. virtual void deleteContext() = 0;
  48223. /** Returns the context that's currently in active use by the calling thread.
  48224. Returns 0 if there isn't an active context.
  48225. */
  48226. static OpenGLContext* getCurrentContext();
  48227. protected:
  48228. OpenGLContext() throw();
  48229. private:
  48230. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  48231. };
  48232. /**
  48233. A component that contains an OpenGL canvas.
  48234. Override this, add it to whatever component you want to, and use the renderOpenGL()
  48235. method to draw its contents.
  48236. */
  48237. class JUCE_API OpenGLComponent : public Component
  48238. {
  48239. public:
  48240. /** Used to select the type of openGL API to use, if more than one choice is available
  48241. on a particular platform.
  48242. */
  48243. enum OpenGLType
  48244. {
  48245. openGLDefault = 0,
  48246. #if JUCE_IOS
  48247. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  48248. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  48249. #endif
  48250. };
  48251. /** Creates an OpenGLComponent. */
  48252. OpenGLComponent (OpenGLType type = openGLDefault);
  48253. /** Destructor. */
  48254. ~OpenGLComponent();
  48255. /** Changes the pixel format used by this component.
  48256. @see OpenGLPixelFormat::getAvailablePixelFormats()
  48257. */
  48258. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  48259. /** Returns the pixel format that this component is currently using. */
  48260. const OpenGLPixelFormat getPixelFormat() const;
  48261. /** Specifies an OpenGL context which should be shared with the one that this
  48262. component is using.
  48263. This is an OpenGL feature that lets two contexts share their texture data.
  48264. Note that this pointer is stored by the component, and when the component
  48265. needs to recreate its internal context for some reason, the same context
  48266. will be used again to share lists. So if you pass a context in here,
  48267. don't delete the context while this component is still using it! You can
  48268. call shareWith (0) to stop this component from sharing with it.
  48269. */
  48270. void shareWith (OpenGLContext* contextToShareListsWith);
  48271. /** Returns the context that this component is sharing with.
  48272. @see shareWith
  48273. */
  48274. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  48275. /** Flips the openGL buffers over. */
  48276. void swapBuffers();
  48277. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  48278. When this is called, makeCurrentContextActive() will already have been called
  48279. for you, so you just need to draw.
  48280. */
  48281. virtual void renderOpenGL() = 0;
  48282. /** This method is called when the component creates a new OpenGL context.
  48283. A new context may be created when the component is first used, or when it
  48284. is moved to a different window, or when the window is hidden and re-shown,
  48285. etc.
  48286. You can use this callback as an opportunity to set up things like textures
  48287. that your context needs.
  48288. New contexts are created on-demand by the makeCurrentContextActive() method - so
  48289. if the context is deleted, e.g. by changing the pixel format or window, no context
  48290. will be created until the next call to makeCurrentContextActive(), which will
  48291. synchronously create one and call this method. This means that if you're using
  48292. a non-GUI thread for rendering, you can make sure this method is be called by
  48293. your renderer thread.
  48294. When this callback happens, the context will already have been made current
  48295. using the makeCurrentContextActive() method, so there's no need to call it
  48296. again in your code.
  48297. */
  48298. virtual void newOpenGLContextCreated() = 0;
  48299. /** Returns the context that will draw into this component.
  48300. This may return 0 if the component is currently invisible or hasn't currently
  48301. got a context. The context object can be deleted and a new one created during
  48302. the lifetime of this component, and there may be times when it doesn't have one.
  48303. @see newOpenGLContextCreated()
  48304. */
  48305. OpenGLContext* getCurrentContext() const throw() { return context; }
  48306. /** Makes this component the current openGL context.
  48307. You might want to use this in things like your resize() method, before calling
  48308. GL commands.
  48309. If this returns false, then the context isn't active, so you should avoid
  48310. making any calls.
  48311. This call may actually create a context if one isn't currently initialised. If
  48312. it does this, it will also synchronously call the newOpenGLContextCreated()
  48313. method to let you initialise it as necessary.
  48314. @see OpenGLContext::makeActive
  48315. */
  48316. bool makeCurrentContextActive();
  48317. /** Stops the current component being the active OpenGL context.
  48318. This is the opposite of makeCurrentContextActive()
  48319. @see OpenGLContext::makeInactive
  48320. */
  48321. void makeCurrentContextInactive();
  48322. /** Returns true if this component is the active openGL context for the
  48323. current thread.
  48324. @see OpenGLContext::isActive
  48325. */
  48326. bool isActiveContext() const throw();
  48327. /** Calls the rendering callback, and swaps the buffers afterwards.
  48328. This is called automatically by paint() when the component needs to be rendered.
  48329. It can be overridden if you need to decouple the rendering from the paint callback
  48330. and render with a custom thread.
  48331. Returns true if the operation succeeded.
  48332. */
  48333. virtual bool renderAndSwapBuffers();
  48334. /** This returns a critical section that can be used to lock the current context.
  48335. Because the context that is used by this component can change, e.g. when the
  48336. component is shown or hidden, then if you're rendering to it on a background
  48337. thread, this allows you to lock the context for the duration of your rendering
  48338. routine.
  48339. */
  48340. CriticalSection& getContextLock() throw() { return contextLock; }
  48341. /** Returns the native handle of an embedded heavyweight window, if there is one.
  48342. E.g. On windows, this will return the HWND of the sub-window containing
  48343. the opengl context, on the mac it'll be the NSOpenGLView.
  48344. */
  48345. void* getNativeWindowHandle() const;
  48346. /** Delete the context.
  48347. This can be called back on the same thread that created the context. */
  48348. void deleteContext();
  48349. /** @internal */
  48350. void paint (Graphics& g);
  48351. private:
  48352. const OpenGLType type;
  48353. class OpenGLComponentWatcher;
  48354. friend class OpenGLComponentWatcher;
  48355. friend class ScopedPointer <OpenGLComponentWatcher>;
  48356. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  48357. ScopedPointer <OpenGLContext> context;
  48358. OpenGLContext* contextToShareListsWith;
  48359. CriticalSection contextLock;
  48360. OpenGLPixelFormat preferredPixelFormat;
  48361. bool needToUpdateViewport;
  48362. OpenGLContext* createContext();
  48363. void updateContextPosition();
  48364. void internalRepaint (int x, int y, int w, int h);
  48365. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  48366. };
  48367. #endif
  48368. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  48369. /*** End of inlined file: juce_OpenGLComponent.h ***/
  48370. #endif
  48371. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48372. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  48373. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48374. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48375. /**
  48376. A component with a set of buttons at the top for changing between pages of
  48377. preferences.
  48378. This is just a handy way of writing a Mac-style preferences panel where you
  48379. have a row of buttons along the top for the different preference categories,
  48380. each button having an icon above its name. Clicking these will show an
  48381. appropriate prefs page below it.
  48382. You can either put one of these inside your own component, or just use the
  48383. showInDialogBox() method to show it in a window and run it modally.
  48384. To use it, just add a set of named pages with the addSettingsPage() method,
  48385. and implement the createComponentForPage() method to create suitable components
  48386. for each of these pages.
  48387. */
  48388. class JUCE_API PreferencesPanel : public Component,
  48389. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  48390. {
  48391. public:
  48392. /** Creates an empty panel.
  48393. Use addSettingsPage() to add some pages to it in your constructor.
  48394. */
  48395. PreferencesPanel();
  48396. /** Destructor. */
  48397. ~PreferencesPanel();
  48398. /** Creates a page using a set of drawables to define the page's icon.
  48399. Note that the other version of this method is much easier if you're using
  48400. an image instead of a custom drawable.
  48401. @param pageTitle the name of this preferences page - you'll need to
  48402. make sure your createComponentForPage() method creates
  48403. a suitable component when it is passed this name
  48404. @param normalIcon the drawable to display in the page's button normally
  48405. @param overIcon the drawable to display in the page's button when the mouse is over
  48406. @param downIcon the drawable to display in the page's button when the button is down
  48407. @see DrawableButton
  48408. */
  48409. void addSettingsPage (const String& pageTitle,
  48410. const Drawable* normalIcon,
  48411. const Drawable* overIcon,
  48412. const Drawable* downIcon);
  48413. /** Creates a page using a set of drawables to define the page's icon.
  48414. The other version of this method gives you more control over the icon, but this
  48415. one is much easier if you're just loading it from a file.
  48416. @param pageTitle the name of this preferences page - you'll need to
  48417. make sure your createComponentForPage() method creates
  48418. a suitable component when it is passed this name
  48419. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  48420. For this to look good, you'll probably want to use a nice
  48421. transparent png file.
  48422. @param imageDataSize the size of the image data, in bytes
  48423. */
  48424. void addSettingsPage (const String& pageTitle,
  48425. const void* imageData,
  48426. int imageDataSize);
  48427. /** Utility method to display this panel in a DialogWindow.
  48428. Calling this will create a DialogWindow containing this panel with the
  48429. given size and title, and will run it modally, returning when the user
  48430. closes the dialog box.
  48431. */
  48432. void showInDialogBox (const String& dialogTitle,
  48433. int dialogWidth,
  48434. int dialogHeight,
  48435. const Colour& backgroundColour = Colours::white);
  48436. /** Subclasses must override this to return a component for each preferences page.
  48437. The subclass should return a pointer to a new component representing the named
  48438. page, which the panel will then display.
  48439. The panel will delete the component later when the user goes to another page
  48440. or deletes the panel.
  48441. */
  48442. virtual Component* createComponentForPage (const String& pageName) = 0;
  48443. /** Changes the current page being displayed. */
  48444. void setCurrentPage (const String& pageName);
  48445. /** Returns the size of the buttons shown along the top. */
  48446. int getButtonSize() const throw();
  48447. /** Changes the size of the buttons shown along the top. */
  48448. void setButtonSize (int newSize);
  48449. /** @internal */
  48450. void resized();
  48451. /** @internal */
  48452. void paint (Graphics& g);
  48453. /** @internal */
  48454. void buttonClicked (Button* button);
  48455. private:
  48456. String currentPageName;
  48457. ScopedPointer <Component> currentPage;
  48458. OwnedArray<DrawableButton> buttons;
  48459. int buttonSize;
  48460. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  48461. };
  48462. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  48463. /*** End of inlined file: juce_PreferencesPanel.h ***/
  48464. #endif
  48465. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48466. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  48467. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48468. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48469. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  48470. // amalgamated build)
  48471. #ifndef DOXYGEN
  48472. #if JUCE_WINDOWS
  48473. typedef ActiveXControlComponent QTCompBaseClass;
  48474. #elif JUCE_MAC
  48475. typedef NSViewComponent QTCompBaseClass;
  48476. #endif
  48477. #endif
  48478. // this is used to disable QuickTime, and is defined in juce_Config.h
  48479. #if JUCE_QUICKTIME || DOXYGEN
  48480. /**
  48481. A window that can play back a QuickTime movie.
  48482. */
  48483. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  48484. {
  48485. public:
  48486. /** Creates a QuickTimeMovieComponent, initially blank.
  48487. Use the loadMovie() method to load a movie once you've added the
  48488. component to a window, (or put it on the desktop as a heavyweight window).
  48489. Loading a movie when the component isn't visible can cause problems, as
  48490. QuickTime needs a window handle to initialise properly.
  48491. */
  48492. QuickTimeMovieComponent();
  48493. /** Destructor. */
  48494. ~QuickTimeMovieComponent();
  48495. /** Returns true if QT is installed and working on this machine.
  48496. */
  48497. static bool isQuickTimeAvailable() throw();
  48498. /** Tries to load a QuickTime movie from a file into the player.
  48499. It's best to call this function once you've added the component to a window,
  48500. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48501. component isn't visible can cause problems, because QuickTime needs a window
  48502. handle to do its stuff.
  48503. @param movieFile the .mov file to open
  48504. @param isControllerVisible whether to show a controller bar at the bottom
  48505. @returns true if the movie opens successfully
  48506. */
  48507. bool loadMovie (const File& movieFile,
  48508. bool isControllerVisible);
  48509. /** Tries to load a QuickTime movie from a URL into the player.
  48510. It's best to call this function once you've added the component to a window,
  48511. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48512. component isn't visible can cause problems, because QuickTime needs a window
  48513. handle to do its stuff.
  48514. @param movieURL the .mov file to open
  48515. @param isControllerVisible whether to show a controller bar at the bottom
  48516. @returns true if the movie opens successfully
  48517. */
  48518. bool loadMovie (const URL& movieURL,
  48519. bool isControllerVisible);
  48520. /** Tries to load a QuickTime movie from a stream into the player.
  48521. It's best to call this function once you've added the component to a window,
  48522. (or put it on the desktop as a heavyweight window). Loading a movie when the
  48523. component isn't visible can cause problems, because QuickTime needs a window
  48524. handle to do its stuff.
  48525. @param movieStream a stream containing a .mov file. The component may try
  48526. to read the whole stream before playing, rather than
  48527. streaming from it.
  48528. @param isControllerVisible whether to show a controller bar at the bottom
  48529. @returns true if the movie opens successfully
  48530. */
  48531. bool loadMovie (InputStream* movieStream,
  48532. bool isControllerVisible);
  48533. /** Closes the movie, if one is open. */
  48534. void closeMovie();
  48535. /** Returns the movie file that is currently open.
  48536. If there isn't one, this returns File::nonexistent
  48537. */
  48538. const File getCurrentMovieFile() const;
  48539. /** Returns true if there's currently a movie open. */
  48540. bool isMovieOpen() const;
  48541. /** Returns the length of the movie, in seconds. */
  48542. double getMovieDuration() const;
  48543. /** Returns the movie's natural size, in pixels.
  48544. You can use this to resize the component to show the movie at its preferred
  48545. scale.
  48546. If no movie is loaded, the size returned will be 0 x 0.
  48547. */
  48548. void getMovieNormalSize (int& width, int& height) const;
  48549. /** This will position the component within a given area, keeping its aspect
  48550. ratio correct according to the movie's normal size.
  48551. The component will be made as large as it can go within the space, and will
  48552. be aligned according to the justification value if this means there are gaps at
  48553. the top or sides.
  48554. */
  48555. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  48556. const RectanglePlacement& placement);
  48557. /** Starts the movie playing. */
  48558. void play();
  48559. /** Stops the movie playing. */
  48560. void stop();
  48561. /** Returns true if the movie is currently playing. */
  48562. bool isPlaying() const;
  48563. /** Moves the movie's position back to the start. */
  48564. void goToStart();
  48565. /** Sets the movie's position to a given time. */
  48566. void setPosition (double seconds);
  48567. /** Returns the current play position of the movie. */
  48568. double getPosition() const;
  48569. /** Changes the movie playback rate.
  48570. A value of 1 is normal speed, greater values play it proportionately faster,
  48571. smaller values play it slower.
  48572. */
  48573. void setSpeed (float newSpeed);
  48574. /** Changes the movie's playback volume.
  48575. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  48576. */
  48577. void setMovieVolume (float newVolume);
  48578. /** Returns the movie's playback volume.
  48579. @returns the volume in the range 0 (silent) to 1.0 (full)
  48580. */
  48581. float getMovieVolume() const;
  48582. /** Tells the movie whether it should loop. */
  48583. void setLooping (bool shouldLoop);
  48584. /** Returns true if the movie is currently looping.
  48585. @see setLooping
  48586. */
  48587. bool isLooping() const;
  48588. /** True if the native QuickTime controller bar is shown in the window.
  48589. @see loadMovie
  48590. */
  48591. bool isControllerVisible() const;
  48592. /** @internal */
  48593. void paint (Graphics& g);
  48594. private:
  48595. File movieFile;
  48596. bool movieLoaded, controllerVisible, looping;
  48597. #if JUCE_WINDOWS
  48598. void parentHierarchyChanged();
  48599. void visibilityChanged();
  48600. void createControlIfNeeded();
  48601. bool isControlCreated() const;
  48602. class Pimpl;
  48603. friend class ScopedPointer <Pimpl>;
  48604. ScopedPointer <Pimpl> pimpl;
  48605. #else
  48606. void* movie;
  48607. #endif
  48608. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  48609. };
  48610. #endif
  48611. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48612. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  48613. #endif
  48614. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48615. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  48616. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48617. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48618. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  48619. /**
  48620. On Windows only, this component sits in the taskbar tray as a small icon.
  48621. To use it, just create one of these components, but don't attempt to make it
  48622. visible, add it to a parent, or put it on the desktop.
  48623. You can then call setIconImage() to create an icon for it in the taskbar.
  48624. To change the icon's tooltip, you can use setIconTooltip().
  48625. To respond to mouse-events, you can override the normal mouseDown(),
  48626. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  48627. position will not be valid, you can use this to respond to clicks. Traditionally
  48628. you'd use a left-click to show your application's window, and a right-click
  48629. to show a pop-up menu.
  48630. */
  48631. class JUCE_API SystemTrayIconComponent : public Component
  48632. {
  48633. public:
  48634. SystemTrayIconComponent();
  48635. /** Destructor. */
  48636. ~SystemTrayIconComponent();
  48637. /** Changes the image shown in the taskbar.
  48638. */
  48639. void setIconImage (const Image& newImage);
  48640. /** Changes the tooltip that Windows shows above the icon. */
  48641. void setIconTooltip (const String& tooltip);
  48642. #if JUCE_LINUX
  48643. /** @internal */
  48644. void paint (Graphics& g);
  48645. #endif
  48646. private:
  48647. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  48648. };
  48649. #endif
  48650. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48651. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  48652. #endif
  48653. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48654. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  48655. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48656. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48657. #if JUCE_WEB_BROWSER || DOXYGEN
  48658. #if ! DOXYGEN
  48659. class WebBrowserComponentInternal;
  48660. #endif
  48661. /**
  48662. A component that displays an embedded web browser.
  48663. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  48664. Windows, probably IE.
  48665. */
  48666. class JUCE_API WebBrowserComponent : public Component
  48667. {
  48668. public:
  48669. /** Creates a WebBrowserComponent.
  48670. Once it's created and visible, send the browser to a URL using goToURL().
  48671. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  48672. component is taken offscreen, it'll clear the current page
  48673. and replace it with a blank page - this can be handy to stop
  48674. the browser using resources in the background when it's not
  48675. actually being used.
  48676. */
  48677. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  48678. /** Destructor. */
  48679. ~WebBrowserComponent();
  48680. /** Sends the browser to a particular URL.
  48681. @param url the URL to go to.
  48682. @param headers an optional set of parameters to put in the HTTP header. If
  48683. you supply this, it should be a set of string in the form
  48684. "HeaderKey: HeaderValue"
  48685. @param postData an optional block of data that will be attached to the HTTP
  48686. POST request
  48687. */
  48688. void goToURL (const String& url,
  48689. const StringArray* headers = 0,
  48690. const MemoryBlock* postData = 0);
  48691. /** Stops the current page loading.
  48692. */
  48693. void stop();
  48694. /** Sends the browser back one page.
  48695. */
  48696. void goBack();
  48697. /** Sends the browser forward one page.
  48698. */
  48699. void goForward();
  48700. /** Refreshes the browser.
  48701. */
  48702. void refresh();
  48703. /** This callback is called when the browser is about to navigate
  48704. to a new location.
  48705. You can override this method to perform some action when the user
  48706. tries to go to a particular URL. To allow the operation to carry on,
  48707. return true, or return false to stop the navigation happening.
  48708. */
  48709. virtual bool pageAboutToLoad (const String& newURL);
  48710. /** @internal */
  48711. void paint (Graphics& g);
  48712. /** @internal */
  48713. void resized();
  48714. /** @internal */
  48715. void parentHierarchyChanged();
  48716. /** @internal */
  48717. void visibilityChanged();
  48718. private:
  48719. WebBrowserComponentInternal* browser;
  48720. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  48721. String lastURL;
  48722. StringArray lastHeaders;
  48723. MemoryBlock lastPostData;
  48724. void reloadLastURL();
  48725. void checkWindowAssociation();
  48726. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  48727. };
  48728. #endif
  48729. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48730. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  48731. #endif
  48732. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  48733. #endif
  48734. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48735. /*** Start of inlined file: juce_CallOutBox.h ***/
  48736. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48737. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  48738. /**
  48739. A box with a small arrow that can be used as a temporary pop-up window to show
  48740. extra controls when a button or other component is clicked.
  48741. Using one of these is similar to having a popup menu attached to a button or
  48742. other component - but it looks fancier, and has an arrow that can indicate the
  48743. object that it applies to.
  48744. Normally, you'd create one of these on the stack and run it modally, e.g.
  48745. @code
  48746. void mouseUp (const MouseEvent& e)
  48747. {
  48748. MyContentComponent content;
  48749. content.setSize (300, 300);
  48750. CallOutBox callOut (content, *this, 0);
  48751. callOut.runModalLoop();
  48752. }
  48753. @endcode
  48754. The call-out will resize and position itself when the content changes size.
  48755. */
  48756. class JUCE_API CallOutBox : public Component
  48757. {
  48758. public:
  48759. /** Creates a CallOutBox.
  48760. @param contentComponent the component to display inside the call-out. This should
  48761. already have a size set (although the call-out will also
  48762. update itself when the component's size is changed later).
  48763. Obviously this component must not be deleted until the
  48764. call-out box has been deleted.
  48765. @param componentToPointTo the component that the call-out's arrow should point towards
  48766. @param parentComponent if non-zero, this is the component to add the call-out to. If
  48767. this is zero, the call-out will be added to the desktop.
  48768. */
  48769. CallOutBox (Component& contentComponent,
  48770. Component& componentToPointTo,
  48771. Component* parentComponent);
  48772. /** Destructor. */
  48773. ~CallOutBox();
  48774. /** Changes the length of the arrow. */
  48775. void setArrowSize (float newSize);
  48776. /** Updates the position and size of the box.
  48777. You shouldn't normally need to call this, unless you need more precise control over the
  48778. layout.
  48779. @param newAreaToPointTo the rectangle to make the box's arrow point to
  48780. @param newAreaToFitIn the area within which the box's position should be constrained
  48781. */
  48782. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  48783. const Rectangle<int>& newAreaToFitIn);
  48784. /** @internal */
  48785. void paint (Graphics& g);
  48786. /** @internal */
  48787. void resized();
  48788. /** @internal */
  48789. void moved();
  48790. /** @internal */
  48791. void childBoundsChanged (Component*);
  48792. /** @internal */
  48793. bool hitTest (int x, int y);
  48794. /** @internal */
  48795. void inputAttemptWhenModal();
  48796. /** @internal */
  48797. bool keyPressed (const KeyPress& key);
  48798. /** @internal */
  48799. void handleCommandMessage (int commandId);
  48800. private:
  48801. int borderSpace;
  48802. float arrowSize;
  48803. Component& content;
  48804. Path outline;
  48805. Point<float> targetPoint;
  48806. Rectangle<int> availableArea, targetArea;
  48807. Image background;
  48808. void refreshPath();
  48809. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  48810. };
  48811. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  48812. /*** End of inlined file: juce_CallOutBox.h ***/
  48813. #endif
  48814. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  48815. /*** Start of inlined file: juce_ComponentPeer.h ***/
  48816. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  48817. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  48818. class ComponentBoundsConstrainer;
  48819. /**
  48820. The Component class uses a ComponentPeer internally to create and manage a real
  48821. operating-system window.
  48822. This is an abstract base class - the platform specific code contains implementations of
  48823. it for the various platforms.
  48824. User-code should very rarely need to have any involvement with this class.
  48825. @see Component::createNewPeer
  48826. */
  48827. class JUCE_API ComponentPeer
  48828. {
  48829. public:
  48830. /** A combination of these flags is passed to the ComponentPeer constructor. */
  48831. enum StyleFlags
  48832. {
  48833. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  48834. entry on the taskbar (ignored on MacOSX) */
  48835. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  48836. tooltip, etc. */
  48837. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  48838. through it (may not be possible on some platforms). */
  48839. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  48840. title bar and frame\. if not specified, the window will be
  48841. borderless. */
  48842. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  48843. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  48844. minimise button on it. */
  48845. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  48846. maximise button on it. */
  48847. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  48848. close button on it. */
  48849. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  48850. not be possible on all platforms). */
  48851. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  48852. do its own repainting, but only to repaint when the
  48853. performAnyPendingRepaintsNow() method is called. */
  48854. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  48855. be used for things like plugin windows, to stop them interfering
  48856. with the host's shortcut keys */
  48857. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  48858. };
  48859. /** Creates a peer.
  48860. The component is the one that we intend to represent, and the style flags are
  48861. a combination of the values in the StyleFlags enum
  48862. */
  48863. ComponentPeer (Component* component, int styleFlags);
  48864. /** Destructor. */
  48865. virtual ~ComponentPeer();
  48866. /** Returns the component being represented by this peer. */
  48867. Component* getComponent() const throw() { return component; }
  48868. /** Returns the set of style flags that were set when the window was created.
  48869. @see Component::addToDesktop
  48870. */
  48871. int getStyleFlags() const throw() { return styleFlags; }
  48872. /** Returns the raw handle to whatever kind of window is being used.
  48873. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  48874. but rememeber there's no guarantees what you'll get back.
  48875. */
  48876. virtual void* getNativeHandle() const = 0;
  48877. /** Shows or hides the window. */
  48878. virtual void setVisible (bool shouldBeVisible) = 0;
  48879. /** Changes the title of the window. */
  48880. virtual void setTitle (const String& title) = 0;
  48881. /** Moves the window without changing its size.
  48882. If the native window is contained in another window, then the co-ordinates are
  48883. relative to the parent window's origin, not the screen origin.
  48884. This should result in a callback to handleMovedOrResized().
  48885. */
  48886. virtual void setPosition (int x, int y) = 0;
  48887. /** Resizes the window without changing its position.
  48888. This should result in a callback to handleMovedOrResized().
  48889. */
  48890. virtual void setSize (int w, int h) = 0;
  48891. /** Moves and resizes the window.
  48892. If the native window is contained in another window, then the co-ordinates are
  48893. relative to the parent window's origin, not the screen origin.
  48894. This should result in a callback to handleMovedOrResized().
  48895. */
  48896. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  48897. /** Returns the current position and size of the window.
  48898. If the native window is contained in another window, then the co-ordinates are
  48899. relative to the parent window's origin, not the screen origin.
  48900. */
  48901. virtual const Rectangle<int> getBounds() const = 0;
  48902. /** Returns the x-position of this window, relative to the screen's origin. */
  48903. virtual const Point<int> getScreenPosition() const = 0;
  48904. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  48905. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  48906. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  48907. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  48908. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  48909. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  48910. /** Converts a screen area to a position relative to the top-left of this component. */
  48911. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  48912. /** Minimises the window. */
  48913. virtual void setMinimised (bool shouldBeMinimised) = 0;
  48914. /** True if the window is currently minimised. */
  48915. virtual bool isMinimised() const = 0;
  48916. /** Enable/disable fullscreen mode for the window. */
  48917. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  48918. /** True if the window is currently full-screen. */
  48919. virtual bool isFullScreen() const = 0;
  48920. /** Sets the size to restore to if fullscreen mode is turned off. */
  48921. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  48922. /** Returns the size to restore to if fullscreen mode is turned off. */
  48923. const Rectangle<int>& getNonFullScreenBounds() const throw();
  48924. /** Attempts to change the icon associated with this window.
  48925. */
  48926. virtual void setIcon (const Image& newIcon) = 0;
  48927. /** Sets a constrainer to use if the peer can resize itself.
  48928. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  48929. */
  48930. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  48931. /** Returns the current constrainer, if one has been set. */
  48932. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  48933. /** Checks if a point is in the window.
  48934. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  48935. is false, then this returns false if the point is actually inside a child of this
  48936. window.
  48937. */
  48938. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  48939. /** Returns the size of the window frame that's around this window.
  48940. Whether or not the window has a normal window frame depends on the flags
  48941. that were set when the window was created by Component::addToDesktop()
  48942. */
  48943. virtual const BorderSize<int> getFrameSize() const = 0;
  48944. /** This is called when the window's bounds change.
  48945. A peer implementation must call this when the window is moved and resized, so that
  48946. this method can pass the message on to the component.
  48947. */
  48948. void handleMovedOrResized();
  48949. /** This is called if the screen resolution changes.
  48950. A peer implementation must call this if the monitor arrangement changes or the available
  48951. screen size changes.
  48952. */
  48953. void handleScreenSizeChange();
  48954. /** This is called to repaint the component into the given context. */
  48955. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  48956. /** Sets this window to either be always-on-top or normal.
  48957. Some kinds of window might not be able to do this, so should return false.
  48958. */
  48959. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  48960. /** Brings the window to the top, optionally also giving it focus. */
  48961. virtual void toFront (bool makeActive) = 0;
  48962. /** Moves the window to be just behind another one. */
  48963. virtual void toBehind (ComponentPeer* other) = 0;
  48964. /** Called when the window is brought to the front, either by the OS or by a call
  48965. to toFront().
  48966. */
  48967. void handleBroughtToFront();
  48968. /** True if the window has the keyboard focus. */
  48969. virtual bool isFocused() const = 0;
  48970. /** Tries to give the window keyboard focus. */
  48971. virtual void grabFocus() = 0;
  48972. /** Called when the window gains keyboard focus. */
  48973. void handleFocusGain();
  48974. /** Called when the window loses keyboard focus. */
  48975. void handleFocusLoss();
  48976. Component* getLastFocusedSubcomponent() const throw();
  48977. /** Called when a key is pressed.
  48978. For keycode info, see the KeyPress class.
  48979. Returns true if the keystroke was used.
  48980. */
  48981. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  48982. /** Called whenever a key is pressed or released.
  48983. Returns true if the keystroke was used.
  48984. */
  48985. bool handleKeyUpOrDown (bool isKeyDown);
  48986. /** Called whenever a modifier key is pressed or released. */
  48987. void handleModifierKeysChange();
  48988. /** Tells the window that text input may be required at the given position.
  48989. This may cause things like a virtual on-screen keyboard to appear, depending
  48990. on the OS.
  48991. */
  48992. virtual void textInputRequired (const Point<int>& position) = 0;
  48993. /** If there's some kind of OS input-method in progress, this should dismiss it. */
  48994. virtual void dismissPendingTextInput();
  48995. /** Returns the currently focused TextInputTarget, or null if none is found. */
  48996. TextInputTarget* findCurrentTextInputTarget();
  48997. /** Invalidates a region of the window to be repainted asynchronously. */
  48998. virtual void repaint (const Rectangle<int>& area) = 0;
  48999. /** This can be called (from the message thread) to cause the immediate redrawing
  49000. of any areas of this window that need repainting.
  49001. You shouldn't ever really need to use this, it's mainly for special purposes
  49002. like supporting audio plugins where the host's event loop is out of our control.
  49003. */
  49004. virtual void performAnyPendingRepaintsNow() = 0;
  49005. /** Changes the window's transparency. */
  49006. virtual void setAlpha (float newAlpha) = 0;
  49007. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  49008. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  49009. void handleUserClosingWindow();
  49010. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  49011. void handleFileDragExit (const StringArray& files);
  49012. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  49013. /** Resets the masking region.
  49014. The subclass should call this every time it's about to call the handlePaint
  49015. method.
  49016. @see addMaskedRegion
  49017. */
  49018. void clearMaskedRegion();
  49019. /** Adds a rectangle to the set of areas not to paint over.
  49020. A component can call this on its peer during its paint() method, to signal
  49021. that the painting code should ignore a given region. The reason
  49022. for this is to stop embedded windows (such as OpenGL) getting painted over.
  49023. The masked region is cleared each time before a paint happens, so a component
  49024. will have to make sure it calls this every time it's painted.
  49025. */
  49026. void addMaskedRegion (int x, int y, int w, int h);
  49027. /** Returns the number of currently-active peers.
  49028. @see getPeer
  49029. */
  49030. static int getNumPeers() throw();
  49031. /** Returns one of the currently-active peers.
  49032. @see getNumPeers
  49033. */
  49034. static ComponentPeer* getPeer (int index) throw();
  49035. /** Checks if this peer object is valid.
  49036. @see getNumPeers
  49037. */
  49038. static bool isValidPeer (const ComponentPeer* peer) throw();
  49039. virtual const StringArray getAvailableRenderingEngines();
  49040. virtual int getCurrentRenderingEngine() const;
  49041. virtual void setCurrentRenderingEngine (int index);
  49042. protected:
  49043. Component* const component;
  49044. const int styleFlags;
  49045. RectangleList maskedRegion;
  49046. Rectangle<int> lastNonFullscreenBounds;
  49047. uint32 lastPaintTime;
  49048. ComponentBoundsConstrainer* constrainer;
  49049. static void updateCurrentModifiers() throw();
  49050. private:
  49051. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  49052. Component* lastDragAndDropCompUnderMouse;
  49053. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  49054. friend class Component;
  49055. friend class Desktop;
  49056. static ComponentPeer* getPeerFor (const Component* component) throw();
  49057. void setLastDragDropTarget (Component* comp);
  49058. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  49059. };
  49060. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  49061. /*** End of inlined file: juce_ComponentPeer.h ***/
  49062. #endif
  49063. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  49064. /*** Start of inlined file: juce_DialogWindow.h ***/
  49065. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  49066. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  49067. /**
  49068. A dialog-box style window.
  49069. This class is a convenient way of creating a DocumentWindow with a close button
  49070. that can be triggered by pressing the escape key.
  49071. Any of the methods available to a DocumentWindow or ResizableWindow are also
  49072. available to this, so it can be made resizable, have a menu bar, etc.
  49073. To add items to the box, see the ResizableWindow::setContentOwned() or
  49074. ResizableWindow::setContentNonOwned() methods. Don't add components directly to this
  49075. class - always put them in a content component!
  49076. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  49077. the user clicking the close button - for more info, see the DocumentWindow
  49078. help.
  49079. @see DocumentWindow, ResizableWindow
  49080. */
  49081. class JUCE_API DialogWindow : public DocumentWindow
  49082. {
  49083. public:
  49084. /** Creates a DialogWindow.
  49085. @param name the name to give the component - this is also
  49086. the title shown at the top of the window. To change
  49087. this later, use setName()
  49088. @param backgroundColour the colour to use for filling the window's background.
  49089. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49090. close button to be triggered
  49091. @param addToDesktop if true, the window will be automatically added to the
  49092. desktop; if false, you can use it as a child component
  49093. */
  49094. DialogWindow (const String& name,
  49095. const Colour& backgroundColour,
  49096. bool escapeKeyTriggersCloseButton,
  49097. bool addToDesktop = true);
  49098. /** Destructor.
  49099. If a content component has been set with setContentOwned(), it will be deleted.
  49100. */
  49101. ~DialogWindow();
  49102. /** Easy way of quickly showing a dialog box containing a given component.
  49103. This will open and display a DialogWindow containing a given component, making it
  49104. modal, but returning immediately to allow the dialog to finish in its own time. If
  49105. you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
  49106. instead.
  49107. To close the dialog programatically, you should call exitModalState (returnValue) on
  49108. the DialogWindow that is created. To find a pointer to this window from your
  49109. contentComponent, you can do something like this:
  49110. @code
  49111. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  49112. if (dw != 0)
  49113. dw->exitModalState (1234);
  49114. @endcode
  49115. @param dialogTitle the dialog box's title
  49116. @param contentComponent the content component for the dialog box. Make sure
  49117. that this has been set to the size you want it to
  49118. be before calling this method. The component won't
  49119. be deleted by this call, so you can re-use it or delete
  49120. it afterwards
  49121. @param componentToCentreAround if this is non-zero, it indicates a component that
  49122. you'd like to show this dialog box in front of. See the
  49123. DocumentWindow::centreAroundComponent() method for more
  49124. info on this parameter
  49125. @param backgroundColour a colour to use for the dialog box's background colour
  49126. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49127. close button to be triggered
  49128. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  49129. a corner resizer
  49130. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  49131. to use a border or corner resizer component. See ResizableWindow::setResizable()
  49132. */
  49133. static void showDialog (const String& dialogTitle,
  49134. Component* contentComponent,
  49135. Component* componentToCentreAround,
  49136. const Colour& backgroundColour,
  49137. bool escapeKeyTriggersCloseButton,
  49138. bool shouldBeResizable = false,
  49139. bool useBottomRightCornerResizer = false);
  49140. /** Easy way of quickly showing a dialog box containing a given component.
  49141. This will open and display a DialogWindow containing a given component, returning
  49142. when the user clicks its close button.
  49143. It returns the value that was returned by the dialog box's runModalLoop() call.
  49144. To close the dialog programatically, you should call exitModalState (returnValue) on
  49145. the DialogWindow that is created. To find a pointer to this window from your
  49146. contentComponent, you can do something like this:
  49147. @code
  49148. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  49149. if (dw != 0)
  49150. dw->exitModalState (1234);
  49151. @endcode
  49152. @param dialogTitle the dialog box's title
  49153. @param contentComponent the content component for the dialog box. Make sure
  49154. that this has been set to the size you want it to
  49155. be before calling this method. The component won't
  49156. be deleted by this call, so you can re-use it or delete
  49157. it afterwards
  49158. @param componentToCentreAround if this is non-zero, it indicates a component that
  49159. you'd like to show this dialog box in front of. See the
  49160. DocumentWindow::centreAroundComponent() method for more
  49161. info on this parameter
  49162. @param backgroundColour a colour to use for the dialog box's background colour
  49163. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  49164. close button to be triggered
  49165. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  49166. a corner resizer
  49167. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  49168. to use a border or corner resizer component. See ResizableWindow::setResizable()
  49169. */
  49170. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  49171. static int showModalDialog (const String& dialogTitle,
  49172. Component* contentComponent,
  49173. Component* componentToCentreAround,
  49174. const Colour& backgroundColour,
  49175. bool escapeKeyTriggersCloseButton,
  49176. bool shouldBeResizable = false,
  49177. bool useBottomRightCornerResizer = false);
  49178. #endif
  49179. protected:
  49180. /** @internal */
  49181. void resized();
  49182. private:
  49183. bool escapeKeyTriggersCloseButton;
  49184. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  49185. };
  49186. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  49187. /*** End of inlined file: juce_DialogWindow.h ***/
  49188. #endif
  49189. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  49190. #endif
  49191. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49192. /*** Start of inlined file: juce_NativeMessageBox.h ***/
  49193. #ifndef __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49194. #define __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49195. class NativeMessageBox
  49196. {
  49197. public:
  49198. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  49199. If the callback parameter is null, the box is shown modally, and the method will
  49200. block until the user has clicked the button (or pressed the escape or return keys).
  49201. If the callback parameter is non-null, the box will be displayed and placed into a
  49202. modal state, but this method will return immediately, and the callback will be invoked
  49203. later when the user dismisses the box.
  49204. @param iconType the type of icon to show
  49205. @param title the headline to show at the top of the box
  49206. @param message a longer, more descriptive message to show underneath the title
  49207. @param associatedComponent if this is non-null, it specifies the component that the
  49208. alert window should be associated with. Depending on the look
  49209. and feel, this might be used for positioning of the alert window.
  49210. */
  49211. #if JUCE_MODAL_LOOPS_PERMITTED
  49212. static void JUCE_CALLTYPE showMessageBox (AlertWindow::AlertIconType iconType,
  49213. const String& title,
  49214. const String& message,
  49215. Component* associatedComponent = 0);
  49216. #endif
  49217. /** Shows a dialog box that just has a message and a single 'ok' button to close it.
  49218. If the callback parameter is null, the box is shown modally, and the method will
  49219. block until the user has clicked the button (or pressed the escape or return keys).
  49220. If the callback parameter is non-null, the box will be displayed and placed into a
  49221. modal state, but this method will return immediately, and the callback will be invoked
  49222. later when the user dismisses the box.
  49223. @param iconType the type of icon to show
  49224. @param title the headline to show at the top of the box
  49225. @param message a longer, more descriptive message to show underneath the title
  49226. @param associatedComponent if this is non-null, it specifies the component that the
  49227. alert window should be associated with. Depending on the look
  49228. and feel, this might be used for positioning of the alert window.
  49229. */
  49230. static void JUCE_CALLTYPE showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  49231. const String& title,
  49232. const String& message,
  49233. Component* associatedComponent = 0);
  49234. /** Shows a dialog box with two buttons.
  49235. Ideal for ok/cancel or yes/no choices. The return key can also be used
  49236. to trigger the first button, and the escape key for the second button.
  49237. If the callback parameter is null, the box is shown modally, and the method will
  49238. block until the user has clicked the button (or pressed the escape or return keys).
  49239. If the callback parameter is non-null, the box will be displayed and placed into a
  49240. modal state, but this method will return immediately, and the callback will be invoked
  49241. later when the user dismisses the box.
  49242. @param iconType the type of icon to show
  49243. @param title the headline to show at the top of the box
  49244. @param message a longer, more descriptive message to show underneath the title
  49245. @param associatedComponent if this is non-null, it specifies the component that the
  49246. alert window should be associated with. Depending on the look
  49247. and feel, this might be used for positioning of the alert window.
  49248. @param callback if this is non-null, the menu will be launched asynchronously,
  49249. returning immediately, and the callback will receive a call to its
  49250. modalStateFinished() when the box is dismissed, with its parameter
  49251. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  49252. will be owned and deleted by the system, so make sure that it works
  49253. safely and doesn't keep any references to objects that might be deleted
  49254. before it gets called.
  49255. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  49256. is not null, the method always returns false, and the user's choice is delivered
  49257. later by the callback.
  49258. */
  49259. static bool JUCE_CALLTYPE showOkCancelBox (AlertWindow::AlertIconType iconType,
  49260. const String& title,
  49261. const String& message,
  49262. #if JUCE_MODAL_LOOPS_PERMITTED
  49263. Component* associatedComponent = 0,
  49264. ModalComponentManager::Callback* callback = 0);
  49265. #else
  49266. Component* associatedComponent,
  49267. ModalComponentManager::Callback* callback);
  49268. #endif
  49269. /** Shows a dialog box with three buttons.
  49270. Ideal for yes/no/cancel boxes.
  49271. The escape key can be used to trigger the third button.
  49272. If the callback parameter is null, the box is shown modally, and the method will
  49273. block until the user has clicked the button (or pressed the escape or return keys).
  49274. If the callback parameter is non-null, the box will be displayed and placed into a
  49275. modal state, but this method will return immediately, and the callback will be invoked
  49276. later when the user dismisses the box.
  49277. @param iconType the type of icon to show
  49278. @param title the headline to show at the top of the box
  49279. @param message a longer, more descriptive message to show underneath the title
  49280. @param associatedComponent if this is non-null, it specifies the component that the
  49281. alert window should be associated with. Depending on the look
  49282. and feel, this might be used for positioning of the alert window.
  49283. @param callback if this is non-null, the menu will be launched asynchronously,
  49284. returning immediately, and the callback will receive a call to its
  49285. modalStateFinished() when the box is dismissed, with its parameter
  49286. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  49287. if it was cancelled, The callback object will be owned and deleted by the
  49288. system, so make sure that it works safely and doesn't keep any references
  49289. to objects that might be deleted before it gets called.
  49290. @returns If the callback parameter has been set, this returns 0. Otherwise, it returns one
  49291. of the following values:
  49292. - 0 if 'cancel' was pressed
  49293. - 1 if 'yes' was pressed
  49294. - 2 if 'no' was pressed
  49295. */
  49296. static int JUCE_CALLTYPE showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  49297. const String& title,
  49298. const String& message,
  49299. #if JUCE_MODAL_LOOPS_PERMITTED
  49300. Component* associatedComponent = 0,
  49301. ModalComponentManager::Callback* callback = 0);
  49302. #else
  49303. Component* associatedComponent,
  49304. ModalComponentManager::Callback* callback);
  49305. #endif
  49306. };
  49307. #endif // __JUCE_NATIVEMESSAGEBOX_JUCEHEADER__
  49308. /*** End of inlined file: juce_NativeMessageBox.h ***/
  49309. #endif
  49310. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  49311. #endif
  49312. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  49313. /*** Start of inlined file: juce_SplashScreen.h ***/
  49314. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  49315. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  49316. /** A component for showing a splash screen while your app starts up.
  49317. This will automatically position itself, and delete itself when the app has
  49318. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  49319. this).
  49320. To use it, just create one of these in your JUCEApplication::initialise() method,
  49321. call its show() method and let the object delete itself later.
  49322. E.g. @code
  49323. void MyApp::initialise (const String& commandLine)
  49324. {
  49325. SplashScreen* splash = new SplashScreen();
  49326. splash->show ("welcome to my app",
  49327. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  49328. 4000, false);
  49329. .. no need to delete the splash screen - it'll do that itself.
  49330. }
  49331. @endcode
  49332. */
  49333. class JUCE_API SplashScreen : public Component,
  49334. public Timer,
  49335. private DeletedAtShutdown
  49336. {
  49337. public:
  49338. /** Creates a SplashScreen object.
  49339. After creating one of these (or your subclass of it), call one of the show()
  49340. methods to display it.
  49341. */
  49342. SplashScreen();
  49343. /** Destructor. */
  49344. ~SplashScreen();
  49345. /** Creates a SplashScreen object that will display an image.
  49346. As soon as this is called, the SplashScreen will be displayed in the centre of the
  49347. screen. This method will also dispatch any pending messages to make sure that when
  49348. it returns, the splash screen has been completely drawn, and your initialisation
  49349. code can carry on.
  49350. @param title the name to give the component
  49351. @param backgroundImage an image to draw on the component. The component's size
  49352. will be set to the size of this image, and if the image is
  49353. semi-transparent, the component will be made semi-transparent
  49354. too. This image will be deleted (or released from the ImageCache
  49355. if that's how it was created) by the splash screen object when
  49356. it is itself deleted.
  49357. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  49358. should stay visible for. If the initialisation takes longer than
  49359. this time, the splash screen will wait for it to finish before
  49360. disappearing, but if initialisation is very quick, this lets
  49361. you make sure that people get a good look at your splash.
  49362. @param useDropShadow if true, the window will have a drop shadow
  49363. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  49364. the mouse (anywhere)
  49365. */
  49366. void show (const String& title,
  49367. const Image& backgroundImage,
  49368. int minimumTimeToDisplayFor,
  49369. bool useDropShadow,
  49370. bool removeOnMouseClick = true);
  49371. /** Creates a SplashScreen object with a specified size.
  49372. For a custom splash screen, you can use this method to display it at a certain size
  49373. and then override the paint() method yourself to do whatever's necessary.
  49374. As soon as this is called, the SplashScreen will be displayed in the centre of the
  49375. screen. This method will also dispatch any pending messages to make sure that when
  49376. it returns, the splash screen has been completely drawn, and your initialisation
  49377. code can carry on.
  49378. @param title the name to give the component
  49379. @param width the width to use
  49380. @param height the height to use
  49381. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  49382. should stay visible for. If the initialisation takes longer than
  49383. this time, the splash screen will wait for it to finish before
  49384. disappearing, but if initialisation is very quick, this lets
  49385. you make sure that people get a good look at your splash.
  49386. @param useDropShadow if true, the window will have a drop shadow
  49387. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  49388. the mouse (anywhere)
  49389. */
  49390. void show (const String& title,
  49391. int width,
  49392. int height,
  49393. int minimumTimeToDisplayFor,
  49394. bool useDropShadow,
  49395. bool removeOnMouseClick = true);
  49396. /** @internal */
  49397. void paint (Graphics& g);
  49398. /** @internal */
  49399. void timerCallback();
  49400. private:
  49401. Image backgroundImage;
  49402. Time earliestTimeToDelete;
  49403. int originalClickCounter;
  49404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  49405. };
  49406. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  49407. /*** End of inlined file: juce_SplashScreen.h ***/
  49408. #endif
  49409. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49410. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  49411. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49412. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49413. /**
  49414. A thread that automatically pops up a modal dialog box with a progress bar
  49415. and cancel button while it's busy running.
  49416. These are handy for performing some sort of task while giving the user feedback
  49417. about how long there is to go, etc.
  49418. E.g. @code
  49419. class MyTask : public ThreadWithProgressWindow
  49420. {
  49421. public:
  49422. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  49423. {
  49424. }
  49425. ~MyTask()
  49426. {
  49427. }
  49428. void run()
  49429. {
  49430. for (int i = 0; i < thingsToDo; ++i)
  49431. {
  49432. // must check this as often as possible, because this is
  49433. // how we know if the user's pressed 'cancel'
  49434. if (threadShouldExit())
  49435. break;
  49436. // this will update the progress bar on the dialog box
  49437. setProgress (i / (double) thingsToDo);
  49438. // ... do the business here...
  49439. }
  49440. }
  49441. };
  49442. void doTheTask()
  49443. {
  49444. MyTask m;
  49445. if (m.runThread())
  49446. {
  49447. // thread finished normally..
  49448. }
  49449. else
  49450. {
  49451. // user pressed the cancel button..
  49452. }
  49453. }
  49454. @endcode
  49455. @see Thread, AlertWindow
  49456. */
  49457. class JUCE_API ThreadWithProgressWindow : public Thread,
  49458. private Timer
  49459. {
  49460. public:
  49461. /** Creates the thread.
  49462. Initially, the dialog box won't be visible, it'll only appear when the
  49463. runThread() method is called.
  49464. @param windowTitle the title to go at the top of the dialog box
  49465. @param hasProgressBar whether the dialog box should have a progress bar (see
  49466. setProgress() )
  49467. @param hasCancelButton whether the dialog box should have a cancel button
  49468. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  49469. the thread to stop before killing it forcibly (see
  49470. Thread::stopThread() )
  49471. @param cancelButtonText the text that should be shown in the cancel button
  49472. (if it has one)
  49473. */
  49474. ThreadWithProgressWindow (const String& windowTitle,
  49475. bool hasProgressBar,
  49476. bool hasCancelButton,
  49477. int timeOutMsWhenCancelling = 10000,
  49478. const String& cancelButtonText = "Cancel");
  49479. /** Destructor. */
  49480. ~ThreadWithProgressWindow();
  49481. /** Starts the thread and waits for it to finish.
  49482. This will start the thread, make the dialog box appear, and wait until either
  49483. the thread finishes normally, or until the cancel button is pressed.
  49484. Before returning, the dialog box will be hidden.
  49485. @param threadPriority the priority to use when starting the thread - see
  49486. Thread::startThread() for values
  49487. @returns true if the thread finished normally; false if the user pressed cancel
  49488. */
  49489. bool runThread (int threadPriority = 5);
  49490. /** The thread should call this periodically to update the position of the progress bar.
  49491. @param newProgress the progress, from 0.0 to 1.0
  49492. @see setStatusMessage
  49493. */
  49494. void setProgress (double newProgress);
  49495. /** The thread can call this to change the message that's displayed in the dialog box.
  49496. */
  49497. void setStatusMessage (const String& newStatusMessage);
  49498. /** Returns the AlertWindow that is being used.
  49499. */
  49500. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  49501. private:
  49502. void timerCallback();
  49503. double progress;
  49504. ScopedPointer <AlertWindow> alertWindow;
  49505. String message;
  49506. CriticalSection messageLock;
  49507. const int timeOutMsWhenCancelling;
  49508. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  49509. };
  49510. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  49511. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  49512. #endif
  49513. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  49514. #endif
  49515. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  49516. #endif
  49517. #ifndef __JUCE_COLOUR_JUCEHEADER__
  49518. #endif
  49519. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  49520. #endif
  49521. #ifndef __JUCE_COLOURS_JUCEHEADER__
  49522. #endif
  49523. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  49524. #endif
  49525. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  49526. /*** Start of inlined file: juce_EdgeTable.h ***/
  49527. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  49528. #define __JUCE_EDGETABLE_JUCEHEADER__
  49529. class Path;
  49530. class Image;
  49531. /**
  49532. A table of horizontal scan-line segments - used for rasterising Paths.
  49533. @see Path, Graphics
  49534. */
  49535. class JUCE_API EdgeTable
  49536. {
  49537. public:
  49538. /** Creates an edge table containing a path.
  49539. A table is created with a fixed vertical range, and only sections of the path
  49540. which lie within this range will be added to the table.
  49541. @param clipLimits only the region of the path that lies within this area will be added
  49542. @param pathToAdd the path to add to the table
  49543. @param transform a transform to apply to the path being added
  49544. */
  49545. EdgeTable (const Rectangle<int>& clipLimits,
  49546. const Path& pathToAdd,
  49547. const AffineTransform& transform);
  49548. /** Creates an edge table containing a rectangle. */
  49549. EdgeTable (const Rectangle<int>& rectangleToAdd);
  49550. /** Creates an edge table containing a rectangle list. */
  49551. EdgeTable (const RectangleList& rectanglesToAdd);
  49552. /** Creates an edge table containing a rectangle. */
  49553. EdgeTable (const Rectangle<float>& rectangleToAdd);
  49554. /** Creates a copy of another edge table. */
  49555. EdgeTable (const EdgeTable& other);
  49556. /** Copies from another edge table. */
  49557. EdgeTable& operator= (const EdgeTable& other);
  49558. /** Destructor. */
  49559. ~EdgeTable();
  49560. void clipToRectangle (const Rectangle<int>& r);
  49561. void excludeRectangle (const Rectangle<int>& r);
  49562. void clipToEdgeTable (const EdgeTable& other);
  49563. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  49564. bool isEmpty() throw();
  49565. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  49566. void translate (float dx, int dy) throw();
  49567. /** Reduces the amount of space the table has allocated.
  49568. This will shrink the table down to use as little memory as possible - useful for
  49569. read-only tables that get stored and re-used for rendering.
  49570. */
  49571. void optimiseTable();
  49572. /** Iterates the lines in the table, for rendering.
  49573. This function will iterate each line in the table, and call a user-defined class
  49574. to render each pixel or continuous line of pixels that the table contains.
  49575. @param iterationCallback this templated class must contain the following methods:
  49576. @code
  49577. inline void setEdgeTableYPos (int y);
  49578. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  49579. inline void handleEdgeTablePixelFull (int x) const;
  49580. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  49581. inline void handleEdgeTableLineFull (int x, int width) const;
  49582. @endcode
  49583. (these don't necessarily have to be 'const', but it might help it go faster)
  49584. */
  49585. template <class EdgeTableIterationCallback>
  49586. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  49587. {
  49588. const int* lineStart = table;
  49589. for (int y = 0; y < bounds.getHeight(); ++y)
  49590. {
  49591. const int* line = lineStart;
  49592. lineStart += lineStrideElements;
  49593. int numPoints = line[0];
  49594. if (--numPoints > 0)
  49595. {
  49596. int x = *++line;
  49597. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  49598. int levelAccumulator = 0;
  49599. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  49600. while (--numPoints >= 0)
  49601. {
  49602. const int level = *++line;
  49603. jassert (isPositiveAndBelow (level, (int) 256));
  49604. const int endX = *++line;
  49605. jassert (endX >= x);
  49606. const int endOfRun = (endX >> 8);
  49607. if (endOfRun == (x >> 8))
  49608. {
  49609. // small segment within the same pixel, so just save it for the next
  49610. // time round..
  49611. levelAccumulator += (endX - x) * level;
  49612. }
  49613. else
  49614. {
  49615. // plot the fist pixel of this segment, including any accumulated
  49616. // levels from smaller segments that haven't been drawn yet
  49617. levelAccumulator += (0x100 - (x & 0xff)) * level;
  49618. levelAccumulator >>= 8;
  49619. x >>= 8;
  49620. if (levelAccumulator > 0)
  49621. {
  49622. if (levelAccumulator >= 255)
  49623. iterationCallback.handleEdgeTablePixelFull (x);
  49624. else
  49625. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  49626. }
  49627. // if there's a run of similar pixels, do it all in one go..
  49628. if (level > 0)
  49629. {
  49630. jassert (endOfRun <= bounds.getRight());
  49631. const int numPix = endOfRun - ++x;
  49632. if (numPix > 0)
  49633. iterationCallback.handleEdgeTableLine (x, numPix, level);
  49634. }
  49635. // save the bit at the end to be drawn next time round the loop.
  49636. levelAccumulator = (endX & 0xff) * level;
  49637. }
  49638. x = endX;
  49639. }
  49640. levelAccumulator >>= 8;
  49641. if (levelAccumulator > 0)
  49642. {
  49643. x >>= 8;
  49644. jassert (x >= bounds.getX() && x < bounds.getRight());
  49645. if (levelAccumulator >= 255)
  49646. iterationCallback.handleEdgeTablePixelFull (x);
  49647. else
  49648. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  49649. }
  49650. }
  49651. }
  49652. }
  49653. private:
  49654. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  49655. HeapBlock<int> table;
  49656. Rectangle<int> bounds;
  49657. int maxEdgesPerLine, lineStrideElements;
  49658. bool needToCheckEmptinesss;
  49659. void addEdgePoint (int x, int y, int winding);
  49660. void remapTableForNumEdges (int newNumEdgesPerLine);
  49661. void intersectWithEdgeTableLine (int y, const int* otherLine);
  49662. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  49663. void sanitiseLevels (bool useNonZeroWinding) throw();
  49664. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  49665. JUCE_LEAK_DETECTOR (EdgeTable);
  49666. };
  49667. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  49668. /*** End of inlined file: juce_EdgeTable.h ***/
  49669. #endif
  49670. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  49671. /*** Start of inlined file: juce_FillType.h ***/
  49672. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  49673. #define __JUCE_FILLTYPE_JUCEHEADER__
  49674. /**
  49675. Represents a colour or fill pattern to use for rendering paths.
  49676. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  49677. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  49678. @see Graphics::setFillType, DrawablePath::setFill
  49679. */
  49680. class JUCE_API FillType
  49681. {
  49682. public:
  49683. /** Creates a default fill type, of solid black. */
  49684. FillType() throw();
  49685. /** Creates a fill type of a solid colour.
  49686. @see setColour
  49687. */
  49688. FillType (const Colour& colour) throw();
  49689. /** Creates a gradient fill type.
  49690. @see setGradient
  49691. */
  49692. FillType (const ColourGradient& gradient);
  49693. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  49694. and rotation of the pattern.
  49695. @see setTiledImage
  49696. */
  49697. FillType (const Image& image, const AffineTransform& transform) throw();
  49698. /** Creates a copy of another FillType. */
  49699. FillType (const FillType& other);
  49700. /** Makes a copy of another FillType. */
  49701. FillType& operator= (const FillType& other);
  49702. /** Destructor. */
  49703. ~FillType() throw();
  49704. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  49705. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  49706. /** Returns true if this is a gradient fill. */
  49707. bool isGradient() const throw() { return gradient != 0; }
  49708. /** Returns true if this is a tiled image pattern fill. */
  49709. bool isTiledImage() const throw() { return image.isValid(); }
  49710. /** Turns this object into a solid colour fill.
  49711. If the object was an image or gradient, those fields will no longer be valid. */
  49712. void setColour (const Colour& newColour) throw();
  49713. /** Turns this object into a gradient fill. */
  49714. void setGradient (const ColourGradient& newGradient);
  49715. /** Turns this object into a tiled image fill type. The transform allows you to set
  49716. the scaling, offset and rotation of the pattern.
  49717. */
  49718. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  49719. /** Changes the opacity that should be used.
  49720. If the fill is a solid colour, this just changes the opacity of that colour. For
  49721. gradients and image tiles, it changes the opacity that will be used for them.
  49722. */
  49723. void setOpacity (float newOpacity) throw();
  49724. /** Returns the current opacity to be applied to the colour, gradient, or image.
  49725. @see setOpacity
  49726. */
  49727. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  49728. /** Returns true if this fill type is completely transparent. */
  49729. bool isInvisible() const throw();
  49730. /** The solid colour being used.
  49731. If the fill type is not a solid colour, the alpha channel of this colour indicates
  49732. the opacity that should be used for the fill, and the RGB channels are ignored.
  49733. */
  49734. Colour colour;
  49735. /** Returns the gradient that should be used for filling.
  49736. This will be zero if the object is some other type of fill.
  49737. If a gradient is active, the overall opacity with which it should be applied
  49738. is indicated by the alpha channel of the colour variable.
  49739. */
  49740. ScopedPointer <ColourGradient> gradient;
  49741. /** The image that should be used for tiling.
  49742. If an image fill is active, the overall opacity with which it should be applied
  49743. is indicated by the alpha channel of the colour variable.
  49744. */
  49745. Image image;
  49746. /** The transform that should be applied to the image or gradient that's being drawn. */
  49747. AffineTransform transform;
  49748. bool operator== (const FillType& other) const;
  49749. bool operator!= (const FillType& other) const;
  49750. private:
  49751. JUCE_LEAK_DETECTOR (FillType);
  49752. };
  49753. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  49754. /*** End of inlined file: juce_FillType.h ***/
  49755. #endif
  49756. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  49757. #endif
  49758. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  49759. #endif
  49760. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49761. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  49762. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49763. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49764. /**
  49765. Interface class for graphics context objects, used internally by the Graphics class.
  49766. Users are not supposed to create instances of this class directly - do your drawing
  49767. via the Graphics object instead.
  49768. It's a base class for different types of graphics context, that may perform software-based
  49769. or OS-accelerated rendering.
  49770. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  49771. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  49772. context.
  49773. */
  49774. class JUCE_API LowLevelGraphicsContext
  49775. {
  49776. protected:
  49777. LowLevelGraphicsContext();
  49778. public:
  49779. virtual ~LowLevelGraphicsContext();
  49780. /** Returns true if this device is vector-based, e.g. a printer. */
  49781. virtual bool isVectorDevice() const = 0;
  49782. /** Moves the origin to a new position.
  49783. The co-ords are relative to the current origin, and indicate the new position
  49784. of (0, 0).
  49785. */
  49786. virtual void setOrigin (int x, int y) = 0;
  49787. virtual void addTransform (const AffineTransform& transform) = 0;
  49788. virtual float getScaleFactor() = 0;
  49789. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  49790. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  49791. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  49792. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  49793. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  49794. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  49795. virtual const Rectangle<int> getClipBounds() const = 0;
  49796. virtual bool isClipEmpty() const = 0;
  49797. virtual void saveState() = 0;
  49798. virtual void restoreState() = 0;
  49799. virtual void beginTransparencyLayer (float opacity) = 0;
  49800. virtual void endTransparencyLayer() = 0;
  49801. virtual void setFill (const FillType& fillType) = 0;
  49802. virtual void setOpacity (float newOpacity) = 0;
  49803. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  49804. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  49805. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  49806. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  49807. virtual void drawLine (const Line <float>& line) = 0;
  49808. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  49809. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  49810. virtual void setFont (const Font& newFont) = 0;
  49811. virtual const Font getFont() = 0;
  49812. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  49813. };
  49814. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49815. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  49816. #endif
  49817. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49818. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  49819. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49820. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49821. /**
  49822. An implementation of LowLevelGraphicsContext that turns the drawing operations
  49823. into a PostScript document.
  49824. */
  49825. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  49826. {
  49827. public:
  49828. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  49829. const String& documentTitle,
  49830. int totalWidth,
  49831. int totalHeight);
  49832. ~LowLevelGraphicsPostScriptRenderer();
  49833. bool isVectorDevice() const;
  49834. void setOrigin (int x, int y);
  49835. void addTransform (const AffineTransform& transform);
  49836. float getScaleFactor();
  49837. bool clipToRectangle (const Rectangle<int>& r);
  49838. bool clipToRectangleList (const RectangleList& clipRegion);
  49839. void excludeClipRectangle (const Rectangle<int>& r);
  49840. void clipToPath (const Path& path, const AffineTransform& transform);
  49841. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  49842. void saveState();
  49843. void restoreState();
  49844. void beginTransparencyLayer (float opacity);
  49845. void endTransparencyLayer();
  49846. bool clipRegionIntersects (const Rectangle<int>& r);
  49847. const Rectangle<int> getClipBounds() const;
  49848. bool isClipEmpty() const;
  49849. void setFill (const FillType& fillType);
  49850. void setOpacity (float opacity);
  49851. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  49852. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  49853. void fillPath (const Path& path, const AffineTransform& transform);
  49854. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  49855. void drawLine (const Line <float>& line);
  49856. void drawVerticalLine (int x, float top, float bottom);
  49857. void drawHorizontalLine (int x, float top, float bottom);
  49858. const Font getFont();
  49859. void setFont (const Font& newFont);
  49860. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  49861. protected:
  49862. OutputStream& out;
  49863. int totalWidth, totalHeight;
  49864. bool needToClip;
  49865. Colour lastColour;
  49866. struct SavedState
  49867. {
  49868. SavedState();
  49869. ~SavedState();
  49870. RectangleList clip;
  49871. int xOffset, yOffset;
  49872. FillType fillType;
  49873. Font font;
  49874. private:
  49875. SavedState& operator= (const SavedState&);
  49876. };
  49877. OwnedArray <SavedState> stateStack;
  49878. void writeClip();
  49879. void writeColour (const Colour& colour);
  49880. void writePath (const Path& path) const;
  49881. void writeXY (float x, float y) const;
  49882. void writeTransform (const AffineTransform& trans) const;
  49883. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  49884. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  49885. };
  49886. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49887. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  49888. #endif
  49889. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49890. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  49891. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49892. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49893. /**
  49894. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  49895. its rendering in memory.
  49896. User code is not supposed to create instances of this class directly - do all your
  49897. rendering via the Graphics class instead.
  49898. */
  49899. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  49900. {
  49901. public:
  49902. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  49903. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  49904. ~LowLevelGraphicsSoftwareRenderer();
  49905. bool isVectorDevice() const;
  49906. void setOrigin (int x, int y);
  49907. void addTransform (const AffineTransform& transform);
  49908. float getScaleFactor();
  49909. bool clipToRectangle (const Rectangle<int>& r);
  49910. bool clipToRectangleList (const RectangleList& clipRegion);
  49911. void excludeClipRectangle (const Rectangle<int>& r);
  49912. void clipToPath (const Path& path, const AffineTransform& transform);
  49913. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  49914. bool clipRegionIntersects (const Rectangle<int>& r);
  49915. const Rectangle<int> getClipBounds() const;
  49916. bool isClipEmpty() const;
  49917. void saveState();
  49918. void restoreState();
  49919. void beginTransparencyLayer (float opacity);
  49920. void endTransparencyLayer();
  49921. void setFill (const FillType& fillType);
  49922. void setOpacity (float opacity);
  49923. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  49924. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  49925. void fillPath (const Path& path, const AffineTransform& transform);
  49926. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  49927. void drawLine (const Line <float>& line);
  49928. void drawVerticalLine (int x, float top, float bottom);
  49929. void drawHorizontalLine (int x, float top, float bottom);
  49930. void setFont (const Font& newFont);
  49931. const Font getFont();
  49932. void drawGlyph (int glyphNumber, float x, float y);
  49933. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  49934. protected:
  49935. Image image;
  49936. class GlyphCache;
  49937. class CachedGlyph;
  49938. class SavedState;
  49939. friend class ScopedPointer <SavedState>;
  49940. friend class OwnedArray <SavedState>;
  49941. friend class OwnedArray <CachedGlyph>;
  49942. ScopedPointer <SavedState> currentState;
  49943. OwnedArray <SavedState> stateStack;
  49944. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  49945. };
  49946. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49947. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  49948. #endif
  49949. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  49950. #endif
  49951. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  49952. #endif
  49953. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49954. /*** Start of inlined file: juce_DrawableComposite.h ***/
  49955. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49956. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49957. /**
  49958. A drawable object which acts as a container for a set of other Drawables.
  49959. @see Drawable
  49960. */
  49961. class JUCE_API DrawableComposite : public Drawable
  49962. {
  49963. public:
  49964. /** Creates a composite Drawable. */
  49965. DrawableComposite();
  49966. /** Creates a copy of a DrawableComposite. */
  49967. DrawableComposite (const DrawableComposite& other);
  49968. /** Destructor. */
  49969. ~DrawableComposite();
  49970. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  49971. @see setContentArea
  49972. */
  49973. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  49974. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  49975. @see setBoundingBox
  49976. */
  49977. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  49978. /** Changes the bounding box transform to match the content area, so that any sub-items will
  49979. be drawn at their untransformed positions.
  49980. */
  49981. void resetBoundingBoxToContentArea();
  49982. /** Returns the main content rectangle.
  49983. The content area is actually defined by the markers named "left", "right", "top" and
  49984. "bottom", but this method is a shortcut that returns them all at once.
  49985. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  49986. */
  49987. const RelativeRectangle getContentArea() const;
  49988. /** Changes the main content area.
  49989. The content area is actually defined by the markers named "left", "right", "top" and
  49990. "bottom", but this method is a shortcut that sets them all at once.
  49991. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  49992. */
  49993. void setContentArea (const RelativeRectangle& newArea);
  49994. /** Resets the content area and the bounding transform to fit around the area occupied
  49995. by the child components (ignoring any markers).
  49996. */
  49997. void resetContentAreaAndBoundingBoxToFitChildren();
  49998. /** The name of the marker that defines the left edge of the content area. */
  49999. static const char* const contentLeftMarkerName;
  50000. /** The name of the marker that defines the right edge of the content area. */
  50001. static const char* const contentRightMarkerName;
  50002. /** The name of the marker that defines the top edge of the content area. */
  50003. static const char* const contentTopMarkerName;
  50004. /** The name of the marker that defines the bottom edge of the content area. */
  50005. static const char* const contentBottomMarkerName;
  50006. /** @internal */
  50007. Drawable* createCopy() const;
  50008. /** @internal */
  50009. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50010. /** @internal */
  50011. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50012. /** @internal */
  50013. static const Identifier valueTreeType;
  50014. /** @internal */
  50015. const Rectangle<float> getDrawableBounds() const;
  50016. /** @internal */
  50017. void childBoundsChanged (Component*);
  50018. /** @internal */
  50019. void childrenChanged();
  50020. /** @internal */
  50021. void parentHierarchyChanged();
  50022. /** @internal */
  50023. MarkerList* getMarkers (bool xAxis);
  50024. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  50025. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50026. {
  50027. public:
  50028. ValueTreeWrapper (const ValueTree& state);
  50029. ValueTree getChildList() const;
  50030. ValueTree getChildListCreating (UndoManager* undoManager);
  50031. const RelativeParallelogram getBoundingBox() const;
  50032. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50033. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  50034. const RelativeRectangle getContentArea() const;
  50035. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  50036. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  50037. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  50038. static const Identifier topLeft, topRight, bottomLeft;
  50039. private:
  50040. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  50041. };
  50042. private:
  50043. RelativeParallelogram bounds;
  50044. MarkerList markersX, markersY;
  50045. bool updateBoundsReentrant;
  50046. friend class Drawable::Positioner<DrawableComposite>;
  50047. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50048. void recalculateCoordinates (Expression::Scope*);
  50049. void updateBoundsToFitChildren();
  50050. DrawableComposite& operator= (const DrawableComposite&);
  50051. JUCE_LEAK_DETECTOR (DrawableComposite);
  50052. };
  50053. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  50054. /*** End of inlined file: juce_DrawableComposite.h ***/
  50055. #endif
  50056. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50057. /*** Start of inlined file: juce_DrawableImage.h ***/
  50058. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50059. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50060. /**
  50061. A drawable object which is a bitmap image.
  50062. @see Drawable
  50063. */
  50064. class JUCE_API DrawableImage : public Drawable
  50065. {
  50066. public:
  50067. DrawableImage();
  50068. DrawableImage (const DrawableImage& other);
  50069. /** Destructor. */
  50070. ~DrawableImage();
  50071. /** Sets the image that this drawable will render. */
  50072. void setImage (const Image& imageToUse);
  50073. /** Returns the current image. */
  50074. const Image getImage() const { return image; }
  50075. /** Sets the opacity to use when drawing the image. */
  50076. void setOpacity (float newOpacity);
  50077. /** Returns the image's opacity. */
  50078. float getOpacity() const throw() { return opacity; }
  50079. /** Sets a colour to draw over the image's alpha channel.
  50080. By default this is transparent so isn't drawn, but if you set a non-transparent
  50081. colour here, then it will be overlaid on the image, using the image's alpha
  50082. channel as a mask.
  50083. This is handy for doing things like darkening or lightening an image by overlaying
  50084. it with semi-transparent black or white.
  50085. */
  50086. void setOverlayColour (const Colour& newOverlayColour);
  50087. /** Returns the overlay colour. */
  50088. const Colour& getOverlayColour() const throw() { return overlayColour; }
  50089. /** Sets the bounding box within which the image should be displayed. */
  50090. void setBoundingBox (const RelativeParallelogram& newBounds);
  50091. /** Returns the position to which the image's top-left corner should be remapped in the target
  50092. coordinate space when rendering this object.
  50093. @see setTransform
  50094. */
  50095. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  50096. /** @internal */
  50097. void paint (Graphics& g);
  50098. /** @internal */
  50099. bool hitTest (int x, int y);
  50100. /** @internal */
  50101. Drawable* createCopy() const;
  50102. /** @internal */
  50103. const Rectangle<float> getDrawableBounds() const;
  50104. /** @internal */
  50105. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50106. /** @internal */
  50107. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50108. /** @internal */
  50109. static const Identifier valueTreeType;
  50110. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  50111. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50112. {
  50113. public:
  50114. ValueTreeWrapper (const ValueTree& state);
  50115. const var getImageIdentifier() const;
  50116. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  50117. Value getImageIdentifierValue (UndoManager* undoManager);
  50118. float getOpacity() const;
  50119. void setOpacity (float newOpacity, UndoManager* undoManager);
  50120. Value getOpacityValue (UndoManager* undoManager);
  50121. const Colour getOverlayColour() const;
  50122. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  50123. Value getOverlayColourValue (UndoManager* undoManager);
  50124. const RelativeParallelogram getBoundingBox() const;
  50125. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50126. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  50127. };
  50128. private:
  50129. Image image;
  50130. float opacity;
  50131. Colour overlayColour;
  50132. RelativeParallelogram bounds;
  50133. friend class Drawable::Positioner<DrawableImage>;
  50134. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50135. void recalculateCoordinates (Expression::Scope*);
  50136. DrawableImage& operator= (const DrawableImage&);
  50137. JUCE_LEAK_DETECTOR (DrawableImage);
  50138. };
  50139. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  50140. /*** End of inlined file: juce_DrawableImage.h ***/
  50141. #endif
  50142. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  50143. /*** Start of inlined file: juce_DrawablePath.h ***/
  50144. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  50145. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  50146. /*** Start of inlined file: juce_DrawableShape.h ***/
  50147. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50148. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50149. /**
  50150. A base class implementing common functionality for Drawable classes which
  50151. consist of some kind of filled and stroked outline.
  50152. @see DrawablePath, DrawableRectangle
  50153. */
  50154. class JUCE_API DrawableShape : public Drawable
  50155. {
  50156. protected:
  50157. DrawableShape();
  50158. DrawableShape (const DrawableShape&);
  50159. public:
  50160. /** Destructor. */
  50161. ~DrawableShape();
  50162. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  50163. */
  50164. class RelativeFillType
  50165. {
  50166. public:
  50167. RelativeFillType();
  50168. RelativeFillType (const FillType& fill);
  50169. RelativeFillType (const RelativeFillType&);
  50170. RelativeFillType& operator= (const RelativeFillType&);
  50171. bool operator== (const RelativeFillType&) const;
  50172. bool operator!= (const RelativeFillType&) const;
  50173. bool isDynamic() const;
  50174. bool recalculateCoords (Expression::Scope* scope);
  50175. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  50176. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  50177. FillType fill;
  50178. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  50179. };
  50180. /** Sets a fill type for the path.
  50181. This colour is used to fill the path - if you don't want the path to be
  50182. filled (e.g. if you're just drawing an outline), set this to a transparent
  50183. colour.
  50184. @see setPath, setStrokeFill
  50185. */
  50186. void setFill (const FillType& newFill);
  50187. /** Sets a fill type for the path.
  50188. This colour is used to fill the path - if you don't want the path to be
  50189. filled (e.g. if you're just drawing an outline), set this to a transparent
  50190. colour.
  50191. @see setPath, setStrokeFill
  50192. */
  50193. void setFill (const RelativeFillType& newFill);
  50194. /** Returns the current fill type.
  50195. @see setFill
  50196. */
  50197. const RelativeFillType& getFill() const throw() { return mainFill; }
  50198. /** Sets the fill type with which the outline will be drawn.
  50199. @see setFill
  50200. */
  50201. void setStrokeFill (const FillType& newStrokeFill);
  50202. /** Sets the fill type with which the outline will be drawn.
  50203. @see setFill
  50204. */
  50205. void setStrokeFill (const RelativeFillType& newStrokeFill);
  50206. /** Returns the current stroke fill.
  50207. @see setStrokeFill
  50208. */
  50209. const RelativeFillType& getStrokeFill() const throw() { return strokeFill; }
  50210. /** Changes the properties of the outline that will be drawn around the path.
  50211. If the stroke has 0 thickness, no stroke will be drawn.
  50212. @see setStrokeThickness, setStrokeColour
  50213. */
  50214. void setStrokeType (const PathStrokeType& newStrokeType);
  50215. /** Changes the stroke thickness.
  50216. This is a shortcut for calling setStrokeType.
  50217. */
  50218. void setStrokeThickness (float newThickness);
  50219. /** Returns the current outline style. */
  50220. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  50221. /** @internal */
  50222. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  50223. {
  50224. public:
  50225. FillAndStrokeState (const ValueTree& state);
  50226. ValueTree getFillState (const Identifier& fillOrStrokeType);
  50227. const RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  50228. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  50229. ComponentBuilder::ImageProvider*, UndoManager*);
  50230. const PathStrokeType getStrokeType() const;
  50231. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  50232. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  50233. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  50234. };
  50235. /** @internal */
  50236. const Rectangle<float> getDrawableBounds() const;
  50237. /** @internal */
  50238. void paint (Graphics& g);
  50239. /** @internal */
  50240. bool hitTest (int x, int y);
  50241. protected:
  50242. /** Called when the cached path should be updated. */
  50243. void pathChanged();
  50244. /** Called when the cached stroke should be updated. */
  50245. void strokeChanged();
  50246. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  50247. bool isStrokeVisible() const throw();
  50248. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  50249. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  50250. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  50251. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  50252. PathStrokeType strokeType;
  50253. Path path, strokePath;
  50254. private:
  50255. class RelativePositioner;
  50256. RelativeFillType mainFill, strokeFill;
  50257. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  50258. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  50259. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  50260. DrawableShape& operator= (const DrawableShape&);
  50261. };
  50262. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50263. /*** End of inlined file: juce_DrawableShape.h ***/
  50264. /**
  50265. A drawable object which renders a filled or outlined shape.
  50266. For details on how to change the fill and stroke, see the DrawableShape class.
  50267. @see Drawable, DrawableShape
  50268. */
  50269. class JUCE_API DrawablePath : public DrawableShape
  50270. {
  50271. public:
  50272. /** Creates a DrawablePath. */
  50273. DrawablePath();
  50274. DrawablePath (const DrawablePath& other);
  50275. /** Destructor. */
  50276. ~DrawablePath();
  50277. /** Changes the path that will be drawn.
  50278. @see setFillColour, setStrokeType
  50279. */
  50280. void setPath (const Path& newPath);
  50281. /** Sets the path using a RelativePointPath.
  50282. Calling this will set up a Component::Positioner to automatically update the path
  50283. if any of the points in the source path are dynamic.
  50284. */
  50285. void setPath (const RelativePointPath& newPath);
  50286. /** Returns the current path. */
  50287. const Path& getPath() const;
  50288. /** Returns the current path for the outline. */
  50289. const Path& getStrokePath() const;
  50290. /** @internal */
  50291. Drawable* createCopy() const;
  50292. /** @internal */
  50293. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50294. /** @internal */
  50295. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50296. /** @internal */
  50297. static const Identifier valueTreeType;
  50298. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  50299. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  50300. {
  50301. public:
  50302. ValueTreeWrapper (const ValueTree& state);
  50303. bool usesNonZeroWinding() const;
  50304. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  50305. class Element
  50306. {
  50307. public:
  50308. explicit Element (const ValueTree& state);
  50309. ~Element();
  50310. const Identifier getType() const throw() { return state.getType(); }
  50311. int getNumControlPoints() const throw();
  50312. const RelativePoint getControlPoint (int index) const;
  50313. Value getControlPointValue (int index, UndoManager*) const;
  50314. const RelativePoint getStartPoint() const;
  50315. const RelativePoint getEndPoint() const;
  50316. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  50317. float getLength (Expression::Scope*) const;
  50318. ValueTreeWrapper getParent() const;
  50319. Element getPreviousElement() const;
  50320. const String getModeOfEndPoint() const;
  50321. void setModeOfEndPoint (const String& newMode, UndoManager*);
  50322. void convertToLine (UndoManager*);
  50323. void convertToCubic (Expression::Scope*, UndoManager*);
  50324. void convertToPathBreak (UndoManager* undoManager);
  50325. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  50326. void removePoint (UndoManager* undoManager);
  50327. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  50328. static const Identifier mode, startSubPathElement, closeSubPathElement,
  50329. lineToElement, quadraticToElement, cubicToElement;
  50330. static const char* cornerMode;
  50331. static const char* roundedMode;
  50332. static const char* symmetricMode;
  50333. ValueTree state;
  50334. };
  50335. ValueTree getPathState();
  50336. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  50337. void writeTo (RelativePointPath& path) const;
  50338. static const Identifier nonZeroWinding, point1, point2, point3;
  50339. };
  50340. private:
  50341. ScopedPointer<RelativePointPath> relativePath;
  50342. class RelativePositioner;
  50343. friend class RelativePositioner;
  50344. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  50345. DrawablePath& operator= (const DrawablePath&);
  50346. JUCE_LEAK_DETECTOR (DrawablePath);
  50347. };
  50348. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  50349. /*** End of inlined file: juce_DrawablePath.h ***/
  50350. #endif
  50351. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50352. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  50353. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50354. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50355. /**
  50356. A Drawable object which draws a rectangle.
  50357. For details on how to change the fill and stroke, see the DrawableShape class.
  50358. @see Drawable, DrawableShape
  50359. */
  50360. class JUCE_API DrawableRectangle : public DrawableShape
  50361. {
  50362. public:
  50363. DrawableRectangle();
  50364. DrawableRectangle (const DrawableRectangle& other);
  50365. /** Destructor. */
  50366. ~DrawableRectangle();
  50367. /** Sets the rectangle's bounds. */
  50368. void setRectangle (const RelativeParallelogram& newBounds);
  50369. /** Returns the rectangle's bounds. */
  50370. const RelativeParallelogram& getRectangle() const throw() { return bounds; }
  50371. /** Returns the corner size to be used. */
  50372. const RelativePoint getCornerSize() const { return cornerSize; }
  50373. /** Sets a new corner size for the rectangle */
  50374. void setCornerSize (const RelativePoint& newSize);
  50375. /** @internal */
  50376. Drawable* createCopy() const;
  50377. /** @internal */
  50378. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50379. /** @internal */
  50380. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50381. /** @internal */
  50382. static const Identifier valueTreeType;
  50383. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  50384. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  50385. {
  50386. public:
  50387. ValueTreeWrapper (const ValueTree& state);
  50388. const RelativeParallelogram getRectangle() const;
  50389. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  50390. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  50391. const RelativePoint getCornerSize() const;
  50392. Value getCornerSizeValue (UndoManager*) const;
  50393. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  50394. };
  50395. private:
  50396. friend class Drawable::Positioner<DrawableRectangle>;
  50397. RelativeParallelogram bounds;
  50398. RelativePoint cornerSize;
  50399. void rebuildPath();
  50400. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50401. void recalculateCoordinates (Expression::Scope*);
  50402. DrawableRectangle& operator= (const DrawableRectangle&);
  50403. JUCE_LEAK_DETECTOR (DrawableRectangle);
  50404. };
  50405. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  50406. /*** End of inlined file: juce_DrawableRectangle.h ***/
  50407. #endif
  50408. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  50409. #endif
  50410. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  50411. /*** Start of inlined file: juce_DrawableText.h ***/
  50412. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  50413. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  50414. /**
  50415. A drawable object which renders a line of text.
  50416. @see Drawable
  50417. */
  50418. class JUCE_API DrawableText : public Drawable
  50419. {
  50420. public:
  50421. /** Creates a DrawableText object. */
  50422. DrawableText();
  50423. DrawableText (const DrawableText& other);
  50424. /** Destructor. */
  50425. ~DrawableText();
  50426. /** Sets the text to display.*/
  50427. void setText (const String& newText);
  50428. /** Sets the colour of the text. */
  50429. void setColour (const Colour& newColour);
  50430. /** Returns the current text colour. */
  50431. const Colour& getColour() const throw() { return colour; }
  50432. /** Sets the font to use.
  50433. Note that the font height and horizontal scale are actually based upon the position
  50434. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  50435. the height and scale control point will be moved to match the dimensions of the font supplied;
  50436. if it is false, then the new font's height and scale are ignored.
  50437. */
  50438. void setFont (const Font& newFont, bool applySizeAndScale);
  50439. /** Changes the justification of the text within the bounding box. */
  50440. void setJustification (const Justification& newJustification);
  50441. /** Returns the parallelogram that defines the text bounding box. */
  50442. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  50443. /** Sets the bounding box that contains the text. */
  50444. void setBoundingBox (const RelativeParallelogram& newBounds);
  50445. /** Returns the point within the bounds that defines the font's size and scale. */
  50446. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  50447. /** Sets the control point that defines the font's height and horizontal scale.
  50448. This position is a point within the bounding box parallelogram, whose Y position (relative
  50449. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  50450. and its X defines the font's horizontal scale.
  50451. */
  50452. void setFontSizeControlPoint (const RelativePoint& newPoint);
  50453. /** @internal */
  50454. void paint (Graphics& g);
  50455. /** @internal */
  50456. Drawable* createCopy() const;
  50457. /** @internal */
  50458. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  50459. /** @internal */
  50460. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  50461. /** @internal */
  50462. static const Identifier valueTreeType;
  50463. /** @internal */
  50464. const Rectangle<float> getDrawableBounds() const;
  50465. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  50466. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  50467. {
  50468. public:
  50469. ValueTreeWrapper (const ValueTree& state);
  50470. const String getText() const;
  50471. void setText (const String& newText, UndoManager* undoManager);
  50472. Value getTextValue (UndoManager* undoManager);
  50473. const Colour getColour() const;
  50474. void setColour (const Colour& newColour, UndoManager* undoManager);
  50475. const Justification getJustification() const;
  50476. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  50477. const Font getFont() const;
  50478. void setFont (const Font& newFont, UndoManager* undoManager);
  50479. Value getFontValue (UndoManager* undoManager);
  50480. const RelativeParallelogram getBoundingBox() const;
  50481. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  50482. const RelativePoint getFontSizeControlPoint() const;
  50483. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  50484. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  50485. };
  50486. private:
  50487. RelativeParallelogram bounds;
  50488. RelativePoint fontSizeControlPoint;
  50489. Point<float> resolvedPoints[3];
  50490. Font font, scaledFont;
  50491. String text;
  50492. Colour colour;
  50493. Justification justification;
  50494. friend class Drawable::Positioner<DrawableText>;
  50495. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  50496. void recalculateCoordinates (Expression::Scope*);
  50497. void refreshBounds();
  50498. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  50499. DrawableText& operator= (const DrawableText&);
  50500. JUCE_LEAK_DETECTOR (DrawableText);
  50501. };
  50502. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  50503. /*** End of inlined file: juce_DrawableText.h ***/
  50504. #endif
  50505. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  50506. #endif
  50507. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  50508. /*** Start of inlined file: juce_GlowEffect.h ***/
  50509. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  50510. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  50511. /**
  50512. A component effect that adds a coloured blur around the component's contents.
  50513. (This will only work on non-opaque components).
  50514. @see Component::setComponentEffect, DropShadowEffect
  50515. */
  50516. class JUCE_API GlowEffect : public ImageEffectFilter
  50517. {
  50518. public:
  50519. /** Creates a default 'glow' effect.
  50520. To customise its appearance, use the setGlowProperties() method.
  50521. */
  50522. GlowEffect();
  50523. /** Destructor. */
  50524. ~GlowEffect();
  50525. /** Sets the glow's radius and colour.
  50526. The radius is how large the blur should be, and the colour is
  50527. used to render it (for a less intense glow, lower the colour's
  50528. opacity).
  50529. */
  50530. void setGlowProperties (float newRadius,
  50531. const Colour& newColour);
  50532. /** @internal */
  50533. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  50534. private:
  50535. float radius;
  50536. Colour colour;
  50537. JUCE_LEAK_DETECTOR (GlowEffect);
  50538. };
  50539. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  50540. /*** End of inlined file: juce_GlowEffect.h ***/
  50541. #endif
  50542. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  50543. #endif
  50544. #ifndef __JUCE_FONT_JUCEHEADER__
  50545. #endif
  50546. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  50547. #endif
  50548. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  50549. #endif
  50550. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  50551. #endif
  50552. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  50553. #endif
  50554. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  50555. #endif
  50556. #ifndef __JUCE_LINE_JUCEHEADER__
  50557. #endif
  50558. #ifndef __JUCE_PATH_JUCEHEADER__
  50559. #endif
  50560. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  50561. /*** Start of inlined file: juce_PathIterator.h ***/
  50562. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  50563. #define __JUCE_PATHITERATOR_JUCEHEADER__
  50564. /**
  50565. Flattens a Path object into a series of straight-line sections.
  50566. Use one of these to iterate through a Path object, and it will convert
  50567. all the curves into line sections so it's easy to render or perform
  50568. geometric operations on.
  50569. @see Path
  50570. */
  50571. class JUCE_API PathFlatteningIterator
  50572. {
  50573. public:
  50574. /** Creates a PathFlatteningIterator.
  50575. After creation, use the next() method to initialise the fields in the
  50576. object with the first line's position.
  50577. @param path the path to iterate along
  50578. @param transform a transform to apply to each point in the path being iterated
  50579. @param tolerance the amount by which the curves are allowed to deviate from the lines
  50580. into which they are being broken down - a higher tolerance contains
  50581. less lines, so can be generated faster, but will be less smooth.
  50582. */
  50583. PathFlatteningIterator (const Path& path,
  50584. const AffineTransform& transform = AffineTransform::identity,
  50585. float tolerance = defaultTolerance);
  50586. /** Destructor. */
  50587. ~PathFlatteningIterator();
  50588. /** Fetches the next line segment from the path.
  50589. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  50590. so that they describe the new line segment.
  50591. @returns false when there are no more lines to fetch.
  50592. */
  50593. bool next();
  50594. float x1; /**< The x position of the start of the current line segment. */
  50595. float y1; /**< The y position of the start of the current line segment. */
  50596. float x2; /**< The x position of the end of the current line segment. */
  50597. float y2; /**< The y position of the end of the current line segment. */
  50598. /** Indicates whether the current line segment is closing a sub-path.
  50599. If the current line is the one that connects the end of a sub-path
  50600. back to the start again, this will be true.
  50601. */
  50602. bool closesSubPath;
  50603. /** The index of the current line within the current sub-path.
  50604. E.g. you can use this to see whether the line is the first one in the
  50605. subpath by seeing if it's 0.
  50606. */
  50607. int subPathIndex;
  50608. /** Returns true if the current segment is the last in the current sub-path. */
  50609. bool isLastInSubpath() const throw();
  50610. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  50611. static const float defaultTolerance;
  50612. private:
  50613. const Path& path;
  50614. const AffineTransform transform;
  50615. float* points;
  50616. const float toleranceSquared;
  50617. float subPathCloseX, subPathCloseY;
  50618. const bool isIdentityTransform;
  50619. HeapBlock <float> stackBase;
  50620. float* stackPos;
  50621. size_t index, stackSize;
  50622. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  50623. };
  50624. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  50625. /*** End of inlined file: juce_PathIterator.h ***/
  50626. #endif
  50627. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  50628. #endif
  50629. #ifndef __JUCE_POINT_JUCEHEADER__
  50630. #endif
  50631. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  50632. #endif
  50633. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  50634. #endif
  50635. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  50636. /*** Start of inlined file: juce_CameraDevice.h ***/
  50637. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  50638. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  50639. #if JUCE_USE_CAMERA || DOXYGEN
  50640. /**
  50641. Controls any video capture devices that might be available.
  50642. Use getAvailableDevices() to list the devices that are attached to the
  50643. system, then call openDevice to open one for use. Once you have a CameraDevice
  50644. object, you can get a viewer component from it, and use its methods to
  50645. stream to a file or capture still-frames.
  50646. */
  50647. class JUCE_API CameraDevice
  50648. {
  50649. public:
  50650. /** Destructor. */
  50651. virtual ~CameraDevice();
  50652. /** Returns a list of the available cameras on this machine.
  50653. You can open one of these devices by calling openDevice().
  50654. */
  50655. static const StringArray getAvailableDevices();
  50656. /** Opens a camera device.
  50657. The index parameter indicates which of the items returned by getAvailableDevices()
  50658. to open.
  50659. The size constraints allow the method to choose between different resolutions if
  50660. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  50661. then these will be ignored.
  50662. */
  50663. static CameraDevice* openDevice (int deviceIndex,
  50664. int minWidth = 128, int minHeight = 64,
  50665. int maxWidth = 1024, int maxHeight = 768);
  50666. /** Returns the name of this device */
  50667. const String getName() const { return name; }
  50668. /** Creates a component that can be used to display a preview of the
  50669. video from this camera.
  50670. */
  50671. Component* createViewerComponent();
  50672. /** Starts recording video to the specified file.
  50673. You should use getFileExtension() to find out the correct extension to
  50674. use for your filename.
  50675. If the file exists, it will be deleted before the recording starts.
  50676. This method may not start recording instantly, so if you need to know the
  50677. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  50678. after the recording has finished.
  50679. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  50680. or may not be used, depending on the driver.
  50681. */
  50682. void startRecordingToFile (const File& file, int quality = 2);
  50683. /** Stops recording, after a call to startRecordingToFile().
  50684. */
  50685. void stopRecording();
  50686. /** Returns the file extension that should be used for the files
  50687. that you pass to startRecordingToFile().
  50688. This may be platform-specific, e.g. ".mov" or ".avi".
  50689. */
  50690. static const String getFileExtension();
  50691. /** After calling stopRecording(), this method can be called to return the timestamp
  50692. of the first frame that was written to the file.
  50693. */
  50694. const Time getTimeOfFirstRecordedFrame() const;
  50695. /**
  50696. Receives callbacks with images from a CameraDevice.
  50697. @see CameraDevice::addListener
  50698. */
  50699. class JUCE_API Listener
  50700. {
  50701. public:
  50702. Listener() {}
  50703. virtual ~Listener() {}
  50704. /** This method is called when a new image arrives.
  50705. This may be called by any thread, so be careful about thread-safety,
  50706. and make sure that you process the data as quickly as possible to
  50707. avoid glitching!
  50708. */
  50709. virtual void imageReceived (const Image& image) = 0;
  50710. };
  50711. /** Adds a listener to receive images from the camera.
  50712. Be very careful not to delete the listener without first removing it by calling
  50713. removeListener().
  50714. */
  50715. void addListener (Listener* listenerToAdd);
  50716. /** Removes a listener that was previously added with addListener().
  50717. */
  50718. void removeListener (Listener* listenerToRemove);
  50719. protected:
  50720. /** @internal */
  50721. CameraDevice (const String& name, int index);
  50722. private:
  50723. void* internal;
  50724. bool isRecording;
  50725. String name;
  50726. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  50727. };
  50728. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  50729. typedef CameraDevice::Listener CameraImageListener;
  50730. #endif
  50731. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  50732. /*** End of inlined file: juce_CameraDevice.h ***/
  50733. #endif
  50734. #ifndef __JUCE_IMAGE_JUCEHEADER__
  50735. #endif
  50736. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50737. /*** Start of inlined file: juce_ImageCache.h ***/
  50738. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50739. #define __JUCE_IMAGECACHE_JUCEHEADER__
  50740. /**
  50741. A global cache of images that have been loaded from files or memory.
  50742. If you're loading an image and may need to use the image in more than one
  50743. place, this is used to allow the same image to be shared rather than loading
  50744. multiple copies into memory.
  50745. Another advantage is that after images are released, they will be kept in
  50746. memory for a few seconds before it is actually deleted, so if you're repeatedly
  50747. loading/deleting the same image, it'll reduce the chances of having to reload it
  50748. each time.
  50749. @see Image, ImageFileFormat
  50750. */
  50751. class JUCE_API ImageCache
  50752. {
  50753. public:
  50754. /** Loads an image from a file, (or just returns the image if it's already cached).
  50755. If the cache already contains an image that was loaded from this file,
  50756. that image will be returned. Otherwise, this method will try to load the
  50757. file, add it to the cache, and return it.
  50758. Remember that the image returned is shared, so drawing into it might
  50759. affect other things that are using it! If you want to draw on it, first
  50760. call Image::duplicateIfShared()
  50761. @param file the file to try to load
  50762. @returns the image, or null if it there was an error loading it
  50763. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50764. */
  50765. static const Image getFromFile (const File& file);
  50766. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  50767. If the cache already contains an image that was loaded from this block of memory,
  50768. that image will be returned. Otherwise, this method will try to load the
  50769. file, add it to the cache, and return it.
  50770. Remember that the image returned is shared, so drawing into it might
  50771. affect other things that are using it! If you want to draw on it, first
  50772. call Image::duplicateIfShared()
  50773. @param imageData the block of memory containing the image data
  50774. @param dataSize the data size in bytes
  50775. @returns the image, or an invalid image if it there was an error loading it
  50776. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50777. */
  50778. static const Image getFromMemory (const void* imageData, int dataSize);
  50779. /** Checks the cache for an image with a particular hashcode.
  50780. If there's an image in the cache with this hashcode, it will be returned,
  50781. otherwise it will return an invalid image.
  50782. @param hashCode the hash code that was associated with the image by addImageToCache()
  50783. @see addImageToCache
  50784. */
  50785. static const Image getFromHashCode (int64 hashCode);
  50786. /** Adds an image to the cache with a user-defined hash-code.
  50787. The image passed-in will be referenced (not copied) by the cache, so it's probably
  50788. a good idea not to draw into it after adding it, otherwise this will affect all
  50789. instances of it that may be in use.
  50790. @param image the image to add
  50791. @param hashCode the hash-code to associate with it
  50792. @see getFromHashCode
  50793. */
  50794. static void addImageToCache (const Image& image, int64 hashCode);
  50795. /** Changes the amount of time before an unused image will be removed from the cache.
  50796. By default this is about 5 seconds.
  50797. */
  50798. static void setCacheTimeout (int millisecs);
  50799. private:
  50800. class Pimpl;
  50801. friend class Pimpl;
  50802. ImageCache();
  50803. ~ImageCache();
  50804. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  50805. };
  50806. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  50807. /*** End of inlined file: juce_ImageCache.h ***/
  50808. #endif
  50809. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50810. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  50811. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50812. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50813. /**
  50814. Represents a filter kernel to use in convoluting an image.
  50815. @see Image::applyConvolution
  50816. */
  50817. class JUCE_API ImageConvolutionKernel
  50818. {
  50819. public:
  50820. /** Creates an empty convulution kernel.
  50821. @param size the length of each dimension of the kernel, so e.g. if the size
  50822. is 5, it will create a 5x5 kernel
  50823. */
  50824. ImageConvolutionKernel (int size);
  50825. /** Destructor. */
  50826. ~ImageConvolutionKernel();
  50827. /** Resets all values in the kernel to zero. */
  50828. void clear();
  50829. /** Returns one of the kernel values. */
  50830. float getKernelValue (int x, int y) const throw();
  50831. /** Sets the value of a specific cell in the kernel.
  50832. The x and y parameters must be in the range 0 < x < getKernelSize().
  50833. @see setOverallSum
  50834. */
  50835. void setKernelValue (int x, int y, float value) throw();
  50836. /** Rescales all values in the kernel to make the total add up to a fixed value.
  50837. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  50838. */
  50839. void setOverallSum (float desiredTotalSum);
  50840. /** Multiplies all values in the kernel by a value. */
  50841. void rescaleAllValues (float multiplier);
  50842. /** Intialises the kernel for a gaussian blur.
  50843. @param blurRadius this may be larger or smaller than the kernel's actual
  50844. size but this will obviously be wasteful or clip at the
  50845. edges. Ideally the kernel should be just larger than
  50846. (blurRadius * 2).
  50847. */
  50848. void createGaussianBlur (float blurRadius);
  50849. /** Returns the size of the kernel.
  50850. E.g. if it's a 3x3 kernel, this returns 3.
  50851. */
  50852. int getKernelSize() const { return size; }
  50853. /** Applies the kernel to an image.
  50854. @param destImage the image that will receive the resultant convoluted pixels.
  50855. @param sourceImage the source image to read from - this can be the same image as
  50856. the destination, but if different, it must be exactly the same
  50857. size and format.
  50858. @param destinationArea the region of the image to apply the filter to
  50859. */
  50860. void applyToImage (Image& destImage,
  50861. const Image& sourceImage,
  50862. const Rectangle<int>& destinationArea) const;
  50863. private:
  50864. HeapBlock <float> values;
  50865. const int size;
  50866. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  50867. };
  50868. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50869. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  50870. #endif
  50871. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50872. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  50873. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50874. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50875. /**
  50876. Base-class for codecs that can read and write image file formats such
  50877. as PNG, JPEG, etc.
  50878. This class also contains static methods to make it easy to load images
  50879. from files, streams or from memory.
  50880. @see Image, ImageCache
  50881. */
  50882. class JUCE_API ImageFileFormat
  50883. {
  50884. protected:
  50885. /** Creates an ImageFormat. */
  50886. ImageFileFormat() {}
  50887. public:
  50888. /** Destructor. */
  50889. virtual ~ImageFileFormat() {}
  50890. /** Returns a description of this file format.
  50891. E.g. "JPEG", "PNG"
  50892. */
  50893. virtual const String getFormatName() = 0;
  50894. /** Returns true if the given stream seems to contain data that this format
  50895. understands.
  50896. The format class should only read the first few bytes of the stream and sniff
  50897. for header bytes that it understands.
  50898. @see decodeImage
  50899. */
  50900. virtual bool canUnderstand (InputStream& input) = 0;
  50901. /** Tries to decode and return an image from the given stream.
  50902. This will be called for an image format after calling its canUnderStand() method
  50903. to see if it can handle the stream.
  50904. @param input the stream to read the data from. The stream will be positioned
  50905. at the start of the image data (but this may not necessarily
  50906. be position 0)
  50907. @returns the image that was decoded, or an invalid image if it fails.
  50908. @see loadFrom
  50909. */
  50910. virtual const Image decodeImage (InputStream& input) = 0;
  50911. /** Attempts to write an image to a stream.
  50912. To specify extra information like encoding quality, there will be appropriate parameters
  50913. in the subclasses of the specific file types.
  50914. @returns true if it nothing went wrong.
  50915. */
  50916. virtual bool writeImageToStream (const Image& sourceImage,
  50917. OutputStream& destStream) = 0;
  50918. /** Tries the built-in decoders to see if it can find one to read this stream.
  50919. There are currently built-in decoders for PNG, JPEG and GIF formats.
  50920. The object that is returned should not be deleted by the caller.
  50921. @see canUnderstand, decodeImage, loadFrom
  50922. */
  50923. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  50924. /** Tries to load an image from a stream.
  50925. This will use the findImageFormatForStream() method to locate a suitable
  50926. codec, and use that to load the image.
  50927. @returns the image that was decoded, or an invalid image if it fails.
  50928. */
  50929. static const Image loadFrom (InputStream& input);
  50930. /** Tries to load an image from a file.
  50931. This will use the findImageFormatForStream() method to locate a suitable
  50932. codec, and use that to load the image.
  50933. @returns the image that was decoded, or an invalid image if it fails.
  50934. */
  50935. static const Image loadFrom (const File& file);
  50936. /** Tries to load an image from a block of raw image data.
  50937. This will use the findImageFormatForStream() method to locate a suitable
  50938. codec, and use that to load the image.
  50939. @returns the image that was decoded, or an invalid image if it fails.
  50940. */
  50941. static const Image loadFrom (const void* rawData,
  50942. const int numBytesOfData);
  50943. };
  50944. /**
  50945. A subclass of ImageFileFormat for reading and writing PNG files.
  50946. @see ImageFileFormat, JPEGImageFormat
  50947. */
  50948. class JUCE_API PNGImageFormat : public ImageFileFormat
  50949. {
  50950. public:
  50951. PNGImageFormat();
  50952. ~PNGImageFormat();
  50953. const String getFormatName();
  50954. bool canUnderstand (InputStream& input);
  50955. const Image decodeImage (InputStream& input);
  50956. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50957. };
  50958. /**
  50959. A subclass of ImageFileFormat for reading and writing JPEG files.
  50960. @see ImageFileFormat, PNGImageFormat
  50961. */
  50962. class JUCE_API JPEGImageFormat : public ImageFileFormat
  50963. {
  50964. public:
  50965. JPEGImageFormat();
  50966. ~JPEGImageFormat();
  50967. /** Specifies the quality to be used when writing a JPEG file.
  50968. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  50969. any negative value is "default" quality
  50970. */
  50971. void setQuality (float newQuality);
  50972. const String getFormatName();
  50973. bool canUnderstand (InputStream& input);
  50974. const Image decodeImage (InputStream& input);
  50975. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50976. private:
  50977. float quality;
  50978. };
  50979. /**
  50980. A subclass of ImageFileFormat for reading GIF files.
  50981. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  50982. */
  50983. class JUCE_API GIFImageFormat : public ImageFileFormat
  50984. {
  50985. public:
  50986. GIFImageFormat();
  50987. ~GIFImageFormat();
  50988. const String getFormatName();
  50989. bool canUnderstand (InputStream& input);
  50990. const Image decodeImage (InputStream& input);
  50991. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50992. };
  50993. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50994. /*** End of inlined file: juce_ImageFileFormat.h ***/
  50995. #endif
  50996. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  50997. #endif
  50998. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50999. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  51000. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51001. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51002. /**
  51003. A class to take care of the logic involved with the loading/saving of some kind
  51004. of document.
  51005. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  51006. functions you need for documents that get saved to a file, so this class attempts
  51007. to abstract most of the boring stuff.
  51008. Your subclass should just implement all the pure virtual methods, and you can
  51009. then use the higher-level public methods to do the load/save dialogs, to warn the user
  51010. about overwriting files, etc.
  51011. The document object keeps track of whether it has changed since it was last saved or
  51012. loaded, so when you change something, call its changed() method. This will set a
  51013. flag so it knows it needs saving, and will also broadcast a change message using the
  51014. ChangeBroadcaster base class.
  51015. @see ChangeBroadcaster
  51016. */
  51017. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  51018. {
  51019. public:
  51020. /** Creates a FileBasedDocument.
  51021. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  51022. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  51023. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  51024. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  51025. */
  51026. FileBasedDocument (const String& fileExtension,
  51027. const String& fileWildCard,
  51028. const String& openFileDialogTitle,
  51029. const String& saveFileDialogTitle);
  51030. /** Destructor. */
  51031. virtual ~FileBasedDocument();
  51032. /** Returns true if the changed() method has been called since the file was
  51033. last saved or loaded.
  51034. @see resetChangedFlag, changed
  51035. */
  51036. bool hasChangedSinceSaved() const { return changedSinceSave; }
  51037. /** Called to indicate that the document has changed and needs saving.
  51038. This method will also trigger a change message to be sent out using the
  51039. ChangeBroadcaster base class.
  51040. After calling the method, the hasChangedSinceSaved() method will return true, until
  51041. it is reset either by saving to a file or using the resetChangedFlag() method.
  51042. @see hasChangedSinceSaved, resetChangedFlag
  51043. */
  51044. virtual void changed();
  51045. /** Sets the state of the 'changed' flag.
  51046. The 'changed' flag is set to true when the changed() method is called - use this method
  51047. to reset it or to set it without also broadcasting a change message.
  51048. @see changed, hasChangedSinceSaved
  51049. */
  51050. void setChangedFlag (bool hasChanged);
  51051. /** Tries to open a file.
  51052. If the file opens correctly, the document's file (see the getFile() method) is set
  51053. to this new one; if it fails, the document's file is left unchanged, and optionally
  51054. a message box is shown telling the user there was an error.
  51055. @returns true if the new file loaded successfully
  51056. @see loadDocument, loadFromUserSpecifiedFile
  51057. */
  51058. bool loadFrom (const File& fileToLoadFrom,
  51059. bool showMessageOnFailure);
  51060. /** Asks the user for a file and tries to load it.
  51061. This will pop up a dialog box using the title, file extension and
  51062. wildcard specified in the document's constructor, and asks the user
  51063. for a file. If they pick one, the loadFrom() method is used to
  51064. try to load it, optionally showing a message if it fails.
  51065. @returns true if a file was loaded; false if the user cancelled or if they
  51066. picked a file which failed to load correctly
  51067. @see loadFrom
  51068. */
  51069. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  51070. /** A set of possible outcomes of one of the save() methods
  51071. */
  51072. enum SaveResult
  51073. {
  51074. savedOk = 0, /**< indicates that a file was saved successfully. */
  51075. userCancelledSave, /**< indicates that the user aborted the save operation. */
  51076. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  51077. };
  51078. /** Tries to save the document to the last file it was saved or loaded from.
  51079. This will always try to write to the file, even if the document isn't flagged as
  51080. having changed.
  51081. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  51082. true, it will prompt the user to pick a file, as if
  51083. saveAsInteractive() was called.
  51084. @param showMessageOnFailure if true it will show a warning message when if the
  51085. save operation fails
  51086. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  51087. */
  51088. SaveResult save (bool askUserForFileIfNotSpecified,
  51089. bool showMessageOnFailure);
  51090. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  51091. it if they say yes.
  51092. If you've got a document open and want to close it (e.g. to quit the app), this is the
  51093. method to call.
  51094. If the document doesn't need saving it'll return the value savedOk so
  51095. you can go ahead and delete the document.
  51096. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  51097. return savedOk, so again, you can safely delete the document.
  51098. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  51099. close-document operation.
  51100. And if they click "save changes", it'll try to save and either return savedOk, or
  51101. failedToWriteToFile if there was a problem.
  51102. @see save, saveAs, saveAsInteractive
  51103. */
  51104. SaveResult saveIfNeededAndUserAgrees();
  51105. /** Tries to save the document to a specified file.
  51106. If this succeeds, it'll also change the document's internal file (as returned by
  51107. the getFile() method). If it fails, the file will be left unchanged.
  51108. @param newFile the file to try to write to
  51109. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  51110. the user first if they want to overwrite it
  51111. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  51112. use the saveAsInteractive() method to ask the user for a
  51113. filename
  51114. @param showMessageOnFailure if true and the write operation fails, it'll show
  51115. a message box to warn the user
  51116. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  51117. */
  51118. SaveResult saveAs (const File& newFile,
  51119. bool warnAboutOverwritingExistingFiles,
  51120. bool askUserForFileIfNotSpecified,
  51121. bool showMessageOnFailure);
  51122. /** Prompts the user for a filename and tries to save to it.
  51123. This will pop up a dialog box using the title, file extension and
  51124. wildcard specified in the document's constructor, and asks the user
  51125. for a file. If they pick one, the saveAs() method is used to try to save
  51126. to this file.
  51127. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  51128. the user first if they want to overwrite it
  51129. @see saveIfNeededAndUserAgrees, save, saveAs
  51130. */
  51131. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  51132. /** Returns the file that this document was last successfully saved or loaded from.
  51133. When the document object is created, this will be set to File::nonexistent.
  51134. It is changed when one of the load or save methods is used, or when setFile()
  51135. is used to explicitly set it.
  51136. */
  51137. const File getFile() const { return documentFile; }
  51138. /** Sets the file that this document thinks it was loaded from.
  51139. This won't actually load anything - it just changes the file stored internally.
  51140. @see getFile
  51141. */
  51142. void setFile (const File& newFile);
  51143. protected:
  51144. /** Overload this to return the title of the document.
  51145. This is used in message boxes, filenames and file choosers, so it should be
  51146. something sensible.
  51147. */
  51148. virtual const String getDocumentTitle() = 0;
  51149. /** This method should try to load your document from the given file.
  51150. If it fails, it should return an error message. If it succeeds, it should return
  51151. an empty string.
  51152. */
  51153. virtual const String loadDocument (const File& file) = 0;
  51154. /** This method should try to write your document to the given file.
  51155. If it fails, it should return an error message. If it succeeds, it should return
  51156. an empty string.
  51157. */
  51158. virtual const String saveDocument (const File& file) = 0;
  51159. /** This is used for dialog boxes to make them open at the last folder you
  51160. were using.
  51161. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  51162. the last document that was used - you might want to store this value
  51163. in a static variable, or even in your application's properties. It should
  51164. be a global setting rather than a property of this object.
  51165. This method works very well in conjunction with a RecentlyOpenedFilesList
  51166. object to manage your recent-files list.
  51167. As a default value, it's ok to return File::nonexistent, and the document
  51168. object will use a sensible one instead.
  51169. @see RecentlyOpenedFilesList
  51170. */
  51171. virtual const File getLastDocumentOpened() = 0;
  51172. /** This is used for dialog boxes to make them open at the last folder you
  51173. were using.
  51174. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  51175. the last document that was used - you might want to store this value
  51176. in a static variable, or even in your application's properties. It should
  51177. be a global setting rather than a property of this object.
  51178. This method works very well in conjunction with a RecentlyOpenedFilesList
  51179. object to manage your recent-files list.
  51180. @see RecentlyOpenedFilesList
  51181. */
  51182. virtual void setLastDocumentOpened (const File& file) = 0;
  51183. private:
  51184. File documentFile;
  51185. bool changedSinceSave;
  51186. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  51187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  51188. };
  51189. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  51190. /*** End of inlined file: juce_FileBasedDocument.h ***/
  51191. #endif
  51192. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  51193. #endif
  51194. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51195. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  51196. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51197. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51198. /**
  51199. Manages a set of files for use as a list of recently-opened documents.
  51200. This is a handy class for holding your list of recently-opened documents, with
  51201. helpful methods for things like purging any non-existent files, automatically
  51202. adding them to a menu, and making persistence easy.
  51203. @see File, FileBasedDocument
  51204. */
  51205. class JUCE_API RecentlyOpenedFilesList
  51206. {
  51207. public:
  51208. /** Creates an empty list.
  51209. */
  51210. RecentlyOpenedFilesList();
  51211. /** Destructor. */
  51212. ~RecentlyOpenedFilesList();
  51213. /** Sets a limit for the number of files that will be stored in the list.
  51214. When addFile() is called, then if there is no more space in the list, the
  51215. least-recently added file will be dropped.
  51216. @see getMaxNumberOfItems
  51217. */
  51218. void setMaxNumberOfItems (int newMaxNumber);
  51219. /** Returns the number of items that this list will store.
  51220. @see setMaxNumberOfItems
  51221. */
  51222. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  51223. /** Returns the number of files in the list.
  51224. The most recently added file is always at index 0.
  51225. */
  51226. int getNumFiles() const;
  51227. /** Returns one of the files in the list.
  51228. The most recently added file is always at index 0.
  51229. */
  51230. const File getFile (int index) const;
  51231. /** Returns an array of all the absolute pathnames in the list.
  51232. */
  51233. const StringArray& getAllFilenames() const throw() { return files; }
  51234. /** Clears all the files from the list. */
  51235. void clear();
  51236. /** Adds a file to the list.
  51237. The file will be added at index 0. If this file is already in the list, it will
  51238. be moved up to index 0, but a file can only appear once in the list.
  51239. If the list already contains the maximum number of items that is permitted, the
  51240. least-recently added file will be dropped from the end.
  51241. */
  51242. void addFile (const File& file);
  51243. /** Removes a file from the list. */
  51244. void removeFile (const File& file);
  51245. /** Checks each of the files in the list, removing any that don't exist.
  51246. You might want to call this after reloading a list of files, or before putting them
  51247. on a menu.
  51248. */
  51249. void removeNonExistentFiles();
  51250. /** Adds entries to a menu, representing each of the files in the list.
  51251. This is handy for creating an "open recent file..." menu in your app. The
  51252. menu items are numbered consecutively starting with the baseItemId value,
  51253. and can either be added as complete pathnames, or just the last part of the
  51254. filename.
  51255. If dontAddNonExistentFiles is true, then each file will be checked and only those
  51256. that exist will be added.
  51257. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  51258. pointers to file objects. Any files that appear in this list will not be added to the
  51259. menu - the reason for this is that you might have a number of files already open, so
  51260. might not want these to be shown in the menu.
  51261. It returns the number of items that were added.
  51262. */
  51263. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  51264. int baseItemId,
  51265. bool showFullPaths,
  51266. bool dontAddNonExistentFiles,
  51267. const File** filesToAvoid = 0);
  51268. /** Returns a string that encapsulates all the files in the list.
  51269. The string that is returned can later be passed into restoreFromString() in
  51270. order to recreate the list. This is handy for persisting your list, e.g. in
  51271. a PropertiesFile object.
  51272. @see restoreFromString
  51273. */
  51274. const String toString() const;
  51275. /** Restores the list from a previously stringified version of the list.
  51276. Pass in a stringified version created with toString() in order to persist/restore
  51277. your list.
  51278. @see toString
  51279. */
  51280. void restoreFromString (const String& stringifiedVersion);
  51281. private:
  51282. StringArray files;
  51283. int maxNumberOfItems;
  51284. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  51285. };
  51286. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  51287. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  51288. #endif
  51289. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  51290. #endif
  51291. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51292. /*** Start of inlined file: juce_SystemClipboard.h ***/
  51293. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51294. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51295. /**
  51296. Handles reading/writing to the system's clipboard.
  51297. */
  51298. class JUCE_API SystemClipboard
  51299. {
  51300. public:
  51301. /** Copies a string of text onto the clipboard */
  51302. static void copyTextToClipboard (const String& text);
  51303. /** Gets the current clipboard's contents.
  51304. Obviously this might have come from another app, so could contain
  51305. anything..
  51306. */
  51307. static const String getTextFromClipboard();
  51308. };
  51309. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  51310. /*** End of inlined file: juce_SystemClipboard.h ***/
  51311. #endif
  51312. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  51313. #endif
  51314. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  51315. #endif
  51316. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  51317. /*** Start of inlined file: juce_UnitTest.h ***/
  51318. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  51319. #define __JUCE_UNITTEST_JUCEHEADER__
  51320. class UnitTestRunner;
  51321. /**
  51322. This is a base class for classes that perform a unit test.
  51323. To write a test using this class, your code should look something like this:
  51324. @code
  51325. class MyTest : public UnitTest
  51326. {
  51327. public:
  51328. MyTest() : UnitTest ("Foobar testing") {}
  51329. void runTest()
  51330. {
  51331. beginTest ("Part 1");
  51332. expect (myFoobar.doesSomething());
  51333. expect (myFoobar.doesSomethingElse());
  51334. beginTest ("Part 2");
  51335. expect (myOtherFoobar.doesSomething());
  51336. expect (myOtherFoobar.doesSomethingElse());
  51337. ...etc..
  51338. }
  51339. };
  51340. // Creating a static instance will automatically add the instance to the array
  51341. // returned by UnitTest::getAllTests(), so the test will be included when you call
  51342. // UnitTestRunner::runAllTests()
  51343. static MyTest test;
  51344. @endcode
  51345. To run a test, use the UnitTestRunner class.
  51346. @see UnitTestRunner
  51347. */
  51348. class JUCE_API UnitTest
  51349. {
  51350. public:
  51351. /** Creates a test with the given name. */
  51352. explicit UnitTest (const String& name);
  51353. /** Destructor. */
  51354. virtual ~UnitTest();
  51355. /** Returns the name of the test. */
  51356. const String getName() const throw() { return name; }
  51357. /** Runs the test, using the specified UnitTestRunner.
  51358. You shouldn't need to call this method directly - use
  51359. UnitTestRunner::runTests() instead.
  51360. */
  51361. void performTest (UnitTestRunner* runner);
  51362. /** Returns the set of all UnitTest objects that currently exist. */
  51363. static Array<UnitTest*>& getAllTests();
  51364. /** You can optionally implement this method to set up your test.
  51365. This method will be called before runTest().
  51366. */
  51367. virtual void initialise();
  51368. /** You can optionally implement this method to clear up after your test has been run.
  51369. This method will be called after runTest() has returned.
  51370. */
  51371. virtual void shutdown();
  51372. /** Implement this method in your subclass to actually run your tests.
  51373. The content of your implementation should call beginTest() and expect()
  51374. to perform the tests.
  51375. */
  51376. virtual void runTest() = 0;
  51377. /** Tells the system that a new subsection of tests is beginning.
  51378. This should be called from your runTest() method, and may be called
  51379. as many times as you like, to demarcate different sets of tests.
  51380. */
  51381. void beginTest (const String& testName);
  51382. /** Checks that the result of a test is true, and logs this result.
  51383. In your runTest() method, you should call this method for each condition that
  51384. you want to check, e.g.
  51385. @code
  51386. void runTest()
  51387. {
  51388. beginTest ("basic tests");
  51389. expect (x + y == 2);
  51390. expect (getThing() == someThing);
  51391. ...etc...
  51392. }
  51393. @endcode
  51394. If testResult is true, a pass is logged; if it's false, a failure is logged.
  51395. If the failure message is specified, it will be written to the log if the test fails.
  51396. */
  51397. void expect (bool testResult, const String& failureMessage = String::empty);
  51398. /** Compares two values, and if they don't match, prints out a message containing the
  51399. expected and actual result values.
  51400. */
  51401. template <class ValueType>
  51402. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  51403. {
  51404. const bool result = (actual == expected);
  51405. if (! result)
  51406. {
  51407. if (failureMessage.isNotEmpty())
  51408. failureMessage << " -- ";
  51409. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  51410. }
  51411. expect (result, failureMessage);
  51412. }
  51413. /** Writes a message to the test log.
  51414. This can only be called from within your runTest() method.
  51415. */
  51416. void logMessage (const String& message);
  51417. private:
  51418. const String name;
  51419. UnitTestRunner* runner;
  51420. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  51421. };
  51422. /**
  51423. Runs a set of unit tests.
  51424. You can instantiate one of these objects and use it to invoke tests on a set of
  51425. UnitTest objects.
  51426. By using a subclass of UnitTestRunner, you can intercept logging messages and
  51427. perform custom behaviour when each test completes.
  51428. @see UnitTest
  51429. */
  51430. class JUCE_API UnitTestRunner
  51431. {
  51432. public:
  51433. /** */
  51434. UnitTestRunner();
  51435. /** Destructor. */
  51436. virtual ~UnitTestRunner();
  51437. /** Runs a set of tests.
  51438. The tests are performed in order, and the results are logged. To run all the
  51439. registered UnitTest objects that exist, use runAllTests().
  51440. */
  51441. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  51442. /** Runs all the UnitTest objects that currently exist.
  51443. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  51444. */
  51445. void runAllTests (bool assertOnFailure);
  51446. /** Contains the results of a test.
  51447. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  51448. it contains details of the number of subsequent UnitTest::expect() calls that are
  51449. made.
  51450. */
  51451. struct TestResult
  51452. {
  51453. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  51454. String unitTestName;
  51455. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  51456. String subcategoryName;
  51457. /** The number of UnitTest::expect() calls that succeeded. */
  51458. int passes;
  51459. /** The number of UnitTest::expect() calls that failed. */
  51460. int failures;
  51461. /** A list of messages describing the failed tests. */
  51462. StringArray messages;
  51463. };
  51464. /** Returns the number of TestResult objects that have been performed.
  51465. @see getResult
  51466. */
  51467. int getNumResults() const throw();
  51468. /** Returns one of the TestResult objects that describes a test that has been run.
  51469. @see getNumResults
  51470. */
  51471. const TestResult* getResult (int index) const throw();
  51472. protected:
  51473. /** Called when the list of results changes.
  51474. You can override this to perform some sort of behaviour when results are added.
  51475. */
  51476. virtual void resultsUpdated();
  51477. /** Logs a message about the current test progress.
  51478. By default this just writes the message to the Logger class, but you could override
  51479. this to do something else with the data.
  51480. */
  51481. virtual void logMessage (const String& message);
  51482. private:
  51483. friend class UnitTest;
  51484. UnitTest* currentTest;
  51485. String currentSubCategory;
  51486. OwnedArray <TestResult, CriticalSection> results;
  51487. bool assertOnFailure;
  51488. void beginNewTest (UnitTest* test, const String& subCategory);
  51489. void endTest();
  51490. void addPass();
  51491. void addFail (const String& failureMessage);
  51492. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  51493. };
  51494. #endif // __JUCE_UNITTEST_JUCEHEADER__
  51495. /*** End of inlined file: juce_UnitTest.h ***/
  51496. #endif
  51497. #endif
  51498. /*** End of inlined file: juce_app_includes.h ***/
  51499. #endif
  51500. #if JUCE_MSVC
  51501. #pragma warning (pop)
  51502. #pragma pack (pop)
  51503. #endif
  51504. END_JUCE_NAMESPACE
  51505. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  51506. #ifdef JUCE_NAMESPACE
  51507. // this will obviously save a lot of typing, but can be disabled by
  51508. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  51509. using namespace JUCE_NAMESPACE;
  51510. /* On the Mac, these symbols are defined in the Mac libraries, so
  51511. these macros make it easier to reference them without writing out
  51512. the namespace every time.
  51513. If you run into difficulties where these macros interfere with the contents
  51514. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  51515. the comments in that file for more information.
  51516. */
  51517. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  51518. #define Component JUCE_NAMESPACE::Component
  51519. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  51520. #define Point JUCE_NAMESPACE::Point
  51521. #define Button JUCE_NAMESPACE::Button
  51522. #endif
  51523. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  51524. it easier to use the juce version explicitly.
  51525. If you run into difficulties where this macro interferes with other 3rd party header
  51526. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  51527. file for more information.
  51528. */
  51529. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  51530. #define Rectangle JUCE_NAMESPACE::Rectangle
  51531. #endif
  51532. #endif
  51533. #endif
  51534. /* Easy autolinking to the right JUCE libraries under win32.
  51535. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  51536. including this header file.
  51537. */
  51538. #if JUCE_MSVC
  51539. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  51540. /** If you want your application to link to Juce as a DLL instead of
  51541. a static library (on win32), just define the JUCE_DLL macro before
  51542. including juce.h
  51543. */
  51544. #ifdef JUCE_DLL
  51545. #if JUCE_DEBUG
  51546. #define AUTOLINKEDLIB "JUCE_debug.lib"
  51547. #else
  51548. #define AUTOLINKEDLIB "JUCE.lib"
  51549. #endif
  51550. #else
  51551. #if JUCE_DEBUG
  51552. #ifdef _WIN64
  51553. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  51554. #else
  51555. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  51556. #endif
  51557. #else
  51558. #ifdef _WIN64
  51559. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  51560. #else
  51561. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  51562. #endif
  51563. #endif
  51564. #endif
  51565. #pragma comment(lib, AUTOLINKEDLIB)
  51566. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  51567. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  51568. #endif
  51569. // Auto-link the other win32 libs that are needed by library calls..
  51570. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  51571. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  51572. // Auto-links to various win32 libs that are needed by library calls..
  51573. #pragma comment(lib, "kernel32.lib")
  51574. #pragma comment(lib, "user32.lib")
  51575. #pragma comment(lib, "shell32.lib")
  51576. #pragma comment(lib, "gdi32.lib")
  51577. #pragma comment(lib, "vfw32.lib")
  51578. #pragma comment(lib, "comdlg32.lib")
  51579. #pragma comment(lib, "winmm.lib")
  51580. #pragma comment(lib, "wininet.lib")
  51581. #pragma comment(lib, "ole32.lib")
  51582. #pragma comment(lib, "oleaut32.lib")
  51583. #pragma comment(lib, "advapi32.lib")
  51584. #pragma comment(lib, "ws2_32.lib")
  51585. #pragma comment(lib, "version.lib")
  51586. #pragma comment(lib, "shlwapi.lib")
  51587. #pragma comment(lib, "imm32.lib")
  51588. #ifdef _NATIVE_WCHAR_T_DEFINED
  51589. #ifdef _DEBUG
  51590. #pragma comment(lib, "comsuppwd.lib")
  51591. #else
  51592. #pragma comment(lib, "comsuppw.lib")
  51593. #endif
  51594. #else
  51595. #ifdef _DEBUG
  51596. #pragma comment(lib, "comsuppd.lib")
  51597. #else
  51598. #pragma comment(lib, "comsupp.lib")
  51599. #endif
  51600. #endif
  51601. #if JUCE_OPENGL
  51602. #pragma comment(lib, "OpenGL32.Lib")
  51603. #pragma comment(lib, "GlU32.Lib")
  51604. #endif
  51605. #if JUCE_QUICKTIME
  51606. #pragma comment (lib, "QTMLClient.lib")
  51607. #endif
  51608. #if JUCE_USE_CAMERA
  51609. #pragma comment (lib, "Strmiids.lib")
  51610. #pragma comment (lib, "wmvcore.lib")
  51611. #endif
  51612. #if JUCE_DIRECT2D
  51613. #pragma comment (lib, "Dwrite.lib")
  51614. #pragma comment (lib, "D2d1.lib")
  51615. #endif
  51616. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  51617. #endif
  51618. #endif
  51619. #endif
  51620. #endif // __JUCE_JUCEHEADER__
  51621. /*** End of inlined file: juce.h ***/
  51622. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__